blob: 560e5b661ba16ad64494b805ac43a756ec5c8e01 [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000018
Haoyu Baib5da5752012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Mark Fasheh7c999d82023-05-04 20:23:11 +000020import static android.app.ActivityManager.UidFrozenStateChangedCallback.UID_FROZEN_STATE_FROZEN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090021import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
22import static android.content.pm.PackageManager.FEATURE_WATCH;
23import static android.content.pm.PackageManager.FEATURE_WIFI;
24import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
Chalard Jean9a396cc2018-02-21 18:43:54 +090025import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090026import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
27import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
28import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
29import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
33import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090034import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
35import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000036import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Aaron Huang9fe47be2021-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 Utsumi278db582023-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 Fasheh7c999d82023-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 Utsumi93a22182023-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;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800253
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800254import androidx.annotation.RequiresApi;
255
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900256import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400257import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400258import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700259import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900260import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800261import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900262import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800263import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000264import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900265import com.android.net.module.util.BitUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900266import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900267import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100268import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900269import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
270import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900271import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800272import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800273import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100274import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000275import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800276import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
277import com.android.networkstack.apishim.ConstantsShim;
278import com.android.networkstack.apishim.common.BroadcastOptionsShim;
279import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900280import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900281import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000282import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900283import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800284import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800285import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900286import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900287import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900288import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500289import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700290import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900291import com.android.server.connectivity.FullScore;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900292import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900293import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000294import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100295import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700296import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900297import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700298import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600299import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900300import com.android.server.connectivity.NetworkNotificationManager;
301import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900302import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900303import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900304import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700305import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900306import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900307import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700308import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800309import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000310import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800311import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600312
Josh Gao461a1222020-06-16 15:58:11 -0700313import libcore.io.IoUtils;
314
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900315import org.xmlpull.v1.XmlPullParserException;
316
The Android Open Source Project28527d22009-03-03 19:31:44 -0800317import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100318import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900319import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800320import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900321import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700322import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700323import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900324import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900325import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700326import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700327import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700328import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700329import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800330import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900331import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800332import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700333import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700334import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700335import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700336import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900337import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700338import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900339import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600340import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900341import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600342import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900343import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800344
345/**
346 * @hide
347 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800348public class ConnectivityService extends IConnectivityManager.Stub
349 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900350 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800351
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900352 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900353 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900354 private static final String NETWORK_ARG = "networks";
355 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800356 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900357
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900358 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900359 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
360 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800361
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900362 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700363
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100364 /**
365 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
366 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800367 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100368 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
369 * (preferably via runtime resource overlays).
370 */
371 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
372 "http://connectivitycheck.gstatic.com/generate_204";
373
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700374 // TODO: create better separation between radio types and network types
375
Robert Greenwalt2034b912009-08-12 16:08:25 -0700376 // how long to wait before switching back to a radio's default network
377 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
378 // system property that can override the above value
379 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
380 "android.telephony.apn-restore";
381
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900382 // How long to wait before putting up a "This network doesn't have an Internet connection,
383 // connect anyway?" dialog after the user selects a network that doesn't validate.
384 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
385
Chalard Jean5fb43c72022-09-08 19:03:14 +0900386 // How long to wait before considering that a network is bad in the absence of any form
387 // of connectivity (valid, partial, captive portal). If none has been detected after this
388 // delay, the stack considers this network bad, which may affect how it's handled in ranking
389 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900390 // Timeout in case the "actively prefer bad wifi" feature is on
391 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
392 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900393 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900394
junyulai0ac374f2020-12-14 18:41:52 +0800395 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900396 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
397 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800398 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700399
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800400 // Delimiter used when creating the broadcast delivery group for sending
401 // CONNECTIVITY_ACTION broadcast.
402 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
403
he_won.hwang881307a2022-03-15 21:23:52 +0900404 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900405 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900406
Daniel Brightf9e945b2020-06-15 16:10:01 -0700407 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900408 @VisibleForTesting
409 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700410
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900411 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700412 @VisibleForTesting
413 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900414
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900415 @VisibleForTesting
416 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800417 @VisibleForTesting
418 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900419 // True if the cell radio of the device is capable of time-sharing.
420 @VisibleForTesting
421 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900422
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800423 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800424 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800425 private final int mReleasePendingIntentDelayMs;
426
Chalard Jean46bfbf02022-02-02 00:56:25 +0900427 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900428
Motomu Utsumif360aa62023-01-30 17:52:20 +0900429 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700430
Chalard Jean9473c982021-07-29 20:03:04 +0900431 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800432 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700433 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800434 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700435
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900436 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700437
junyulaif2c67e42018-08-07 19:50:45 +0800438 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000439 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
440 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800441 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900442 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800443
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900444 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900445 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000446 private final int mWakeUpMark;
447 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000448 // The Context is created for UserHandle.ALL.
449 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900450 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900451 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700452 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700453 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800454
Chenbo Feng15416292018-11-08 17:36:21 -0800455 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800456 protected IDnsResolver mDnsResolver;
457 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800458 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700459 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900460 private final NetworkStatsManager mStatsManager;
461 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800462 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700463
Benedict Wong493e04b2018-11-09 14:45:34 -0800464 /**
465 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
466 * instances.
467 */
468 @GuardedBy("mTNSLock")
469 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800470 private final CompanionDeviceManagerProxyService mCdmps;
Benedict Wong493e04b2018-11-09 14:45:34 -0800471
472 private final Object mTNSLock = new Object();
473
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700474 private String mCurrentTcpBufferSizes;
475
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900476 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000477 new Class[] {
478 ConnectivityService.class,
479 NetworkAgent.class,
480 NetworkAgentInfo.class,
481 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900482
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500483 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400484 // Tear down networks that have no chance (e.g. even if validated) of becoming
485 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500486 // all networks have been rematched against all NetworkRequests.
487 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400488 // Don't reap networks. This should be passed when some networks have not yet been
489 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500490 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900491 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500492
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900493 private enum UnneededFor {
494 LINGER, // Determine whether this network is unneeded and should be lingered.
495 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
496 }
497
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700498 /**
paulhuaa0743d2021-05-26 21:56:03 +0800499 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800500 * should have priority. The order is passed to netd which will use it together
501 * with UID ranges to generate the corresponding IP rule. This serves to
502 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800503 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800504 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000505 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800506 *
paulhu48291862021-07-14 14:53:57 +0800507 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
508 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800509 */
paulhu48291862021-07-14 14:53:57 +0800510 // Used when sending to netd to code for "no order".
511 static final int PREFERENCE_ORDER_NONE = 0;
512 // Order for requests that don't code for a per-app preference. As it is
513 // out of the valid range, the corresponding order should be
514 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800515 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800516 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800517 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800518 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
519 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800520 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800521 static final int PREFERENCE_ORDER_OEM = 10;
522 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800523 // See {@link #setProfileNetworkPreference}.
524 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800525 static final int PREFERENCE_ORDER_PROFILE = 20;
526 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800527 // better scores are connected.
528 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800529 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800530 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900531 // Preference order that signifies the network shouldn't be set as a default network for
532 // the UIDs, only give them access to it. TODO : replace this with a boolean
533 // in NativeUidRangeConfig
534 @VisibleForTesting
535 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
536 // Bound for the lowest valid preference order.
537 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800538
539 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700540 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700541 * from one net to another. Clear happens when we get a new
542 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
543 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700544 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700545 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700546
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700547 /**
548 * used internally to reload global proxy settings
549 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700550 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700551
Robert Greenwalt34848c02011-03-25 13:09:25 -0700552 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400553 * PAC manager has received new port.
554 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800555 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400556
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700557 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900558 * used internally when registering NetworkProviders
559 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700560 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900561 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700562
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700563 /**
564 * used internally when registering NetworkAgents
565 * obj = Messenger
566 */
567 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
568
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700569 /**
570 * used to add a network request
571 * includes a NetworkRequestInfo
572 */
573 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
574
575 /**
576 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900577 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700578 * cancel it.
579 * includes a NetworkRequestInfo
580 */
581 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
582
583 /**
584 * used to add a network listener - no request
585 * includes a NetworkRequestInfo
586 */
587 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
588
589 /**
590 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400591 * arg1 = UID of caller
592 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700593 */
594 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
595
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700596 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900597 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700598 * obj = Messenger
599 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900600 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700601
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700602 /**
603 * used internally to expire a wakelock when transitioning
604 * from one net to another. Expire happens when we fail to find
605 * a new network (typically after 1 minute) -
606 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
607 * a replacement network.
608 */
609 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
610
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700611 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800612 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400613 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800614 */
615 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
616
617 /**
618 * used to remove a pending intent and its associated network request.
619 * arg1 = UID of caller
620 * obj = PendingIntent
621 */
622 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
623
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900624 /**
625 * used to specify whether a network should be used even if unvalidated.
626 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
627 * arg2 = whether to remember this choice in the future (1 or 0)
628 * obj = network
629 */
630 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
631
632 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700633 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900634 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700635 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900636
Paul Jensenc8873fc2015-06-17 14:15:39 -0400637 /**
638 * used to add a network listener with a pending intent
639 * obj = NetworkRequestInfo
640 */
641 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
642
Hugo Benichid6b510a2017-04-06 17:22:18 +0900643 /**
644 * used to specify whether a network should not be penalized when it becomes unvalidated.
645 */
646 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
647
648 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700649 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900650 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700651 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900652
Erik Kline31b4a9e2018-01-11 21:07:29 +0900653 // Handle changes in Private DNS settings.
654 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
655
dalyk1720e542018-03-05 12:42:22 -0500656 // Handle private DNS validation status updates.
657 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
658
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900659 /**
660 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
661 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800662 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
663 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
664 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900665 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900666 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900667
668 /**
669 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
670 * config was resolved.
671 * obj = PrivateDnsConfig
672 * arg2 = netid
673 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900674 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900675
676 /**
677 * Request ConnectivityService display provisioning notification.
678 * arg1 = Whether to make the notification visible.
679 * arg2 = NetID.
680 * obj = Intent to be launched when notification selected by user, null if !arg1.
681 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900682 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900683
684 /**
lucaslin2240ef62019-03-12 13:08:03 +0800685 * Used to specify whether a network should be used even if connectivity is partial.
686 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
687 * false)
688 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
689 * obj = network
690 */
lucaslin444d43a2020-02-20 16:56:59 +0800691 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800692
693 /**
lucasline117e2e2019-10-22 18:27:33 +0800694 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
695 * Both of the arguments are bitmasks, and the value of bits come from
696 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900697 * arg1 = unused
698 * arg2 = netId
699 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800700 */
lucaslin444d43a2020-02-20 16:56:59 +0800701 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800702
703 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900704 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
705 * arg1 = unused
706 * arg2 = netId
707 * obj = captive portal data
708 */
lucaslin444d43a2020-02-20 16:56:59 +0800709 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900710
711 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900712 * Used by setRequireVpnForUids.
713 * arg1 = whether the specified UID ranges are required to use a VPN.
714 * obj = Array of UidRange objects.
715 */
716 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
717
718 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900719 * Used internally when setting the default networks for OemNetworkPreferences.
720 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800721 */
722 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
723
724 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800725 * Used to indicate the system default network becomes active.
726 */
727 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
728
729 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900730 * Used internally when setting a network preference for a user profile.
731 * obj = Pair<ProfileNetworkPreference, Listener>
732 */
733 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
734
735 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000736 * Event to specify that reasons for why an uid is blocked changed.
737 * arg1 = uid
738 * arg2 = blockedReasons
739 */
740 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
741
742 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900743 * Event to register a new network offer
744 * obj = NetworkOffer
745 */
746 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
747
748 /**
749 * Event to unregister an existing network offer
750 * obj = INetworkOfferCallback
751 */
752 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
753
754 /**
paulhu51f77dc2021-06-07 02:34:20 +0000755 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
756 */
757 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
758
759 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800760 * Event to set temporary allow bad wifi within a limited time to override
761 * {@code config_networkAvoidBadWifi}.
762 */
763 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
764
765 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100766 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
767 */
768 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
769
770 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900771 * The initial evaluation period is over for this network.
772 *
773 * If no form of connectivity has been found on this network (valid, partial, captive portal)
774 * then the stack will now consider it to have been determined bad.
775 */
776 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
777
778 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000779 * Used internally when the user does not want the network from captive portal app.
780 * obj = Network
781 */
782 private static final int EVENT_USER_DOES_NOT_WANT = 58;
783
784 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000785 * Event to set VPN as preferred network for specific apps.
786 * obj = VpnNetworkPreferenceInfo
787 */
788 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
789
790 /**
chiachangwange0192a72023-02-06 13:25:01 +0000791 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
792 */
793 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
794
795 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000796 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
797 */
798 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
799
800 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900801 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
802 * should be shown.
803 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900804 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900805
806 /**
807 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
808 * should be hidden.
809 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900810 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900811
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800812 /**
813 * The maximum alive time to allow bad wifi configuration for testing.
814 */
815 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
816
Patrick Rohr2857ac42022-01-21 14:58:16 +0100817 /**
chiachangwange0192a72023-02-06 13:25:01 +0000818 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
819 * testing.
820 */
821 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
822
823 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100824 * The priority of the tc police rate limiter -- smaller value is higher priority.
825 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
826 */
827 private static final short TC_PRIO_POLICE = 1;
828
829 /**
830 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
831 */
832 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700833 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100834
Hugo Benichi47011212017-03-30 10:46:05 +0900835 private static String eventName(int what) {
836 return sMagicDecoderRing.get(what, Integer.toString(what));
837 }
838
paulhua10d8212020-11-10 15:32:56 +0800839 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900840 final DnsResolverServiceManager dsm = context.getSystemService(
841 DnsResolverServiceManager.class);
842 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800843 }
844
Cody Kesting73708bf2019-12-18 10:57:50 -0800845 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900846 @VisibleForTesting
847 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700848 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700849 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700850 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700851 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800852 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
853 @VisibleForTesting
854 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
855
Erik Kline32120082017-12-13 19:40:49 +0900856 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900857 @VisibleForTesting
858 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700859
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400860 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800861 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400862
Chalard Jean46bfbf02022-02-02 00:56:25 +0900863 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800864 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700865
Chalard Jean5d70ba42018-06-07 16:44:04 +0900866 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
867 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800868 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400869
Erik Kline05f2b402015-04-30 12:58:40 +0900870 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700871
Chalard Jean46bfbf02022-02-02 00:56:25 +0900872 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400873
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700874 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900875 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700876
Valentin Iftime9fa35092019-09-24 13:32:13 +0200877 private Set<String> mWolSupportedInterfaces;
878
Roshan Pius08c94fb2020-01-16 12:17:17 -0800879 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800880 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800881 private final AppOpsManager mAppOpsManager;
882
883 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400884
chiachangwang3d60bac2023-01-17 14:38:08 +0000885 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900886 private final QosCallbackTracker mQosCallbackTracker;
887 private final NetworkNotificationManager mNotifier;
888 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900889
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700890 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800891 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700892
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900893 // Sequence number for NetworkProvider IDs.
894 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
895 NetworkProvider.FIRST_PROVIDER_ID);
896
Erik Klineedf878b2015-07-09 18:24:03 +0900897 // NetworkRequest activity String log entries.
898 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
899 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
900
Hugo Benichid159fdd2016-07-11 11:05:12 +0900901 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900902 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900903 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
904
Hugo Benichi47011212017-03-30 10:46:05 +0900905 private static final int MAX_WAKELOCK_LOGS = 20;
906 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900907 private int mTotalWakelockAcquisitions = 0;
908 private int mTotalWakelockReleases = 0;
909 private long mTotalWakelockDurationMs = 0;
910 private long mMaxWakelockDurationMs = 0;
911 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900912
Hugo Benichi208c0102016-07-28 17:53:06 +0900913 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900914
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700915 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900916 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700917
Erik Kline95ecfee2016-10-02 18:02:14 +0900918 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900919 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900920
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900921 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800922 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
923 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800924
Patrick Rohr2857ac42022-01-21 14:58:16 +0100925 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
926 // configured via {@link
927 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
928 // Only the handler thread is allowed to access this field.
929 private long mIngressRateLimit = -1;
930
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900931 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
932 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900933 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900934 @GuardedBy("mSelfCertifiedCapabilityCache")
935 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
936 mSelfCertifiedCapabilityCache = new HashMap<>();
937
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900938 // Flag to enable the feature of closing frozen app sockets.
939 private final boolean mDestroyFrozenSockets;
940
941 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
942 private final boolean mDelayDestroyFrozenSockets;
943
944 // Uids that ConnectivityService is pending to close sockets of.
945 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
946
Robert Greenwalt802c1102014-06-02 15:32:02 -0700947 /**
948 * Implements support for the legacy "one network per network type" model.
949 *
950 * We used to have a static array of NetworkStateTrackers, one for each
951 * network type, but that doesn't work any more now that we can have,
952 * for example, more that one wifi network. This class stores all the
953 * NetworkAgentInfo objects that support a given type, but the legacy
954 * API will only see the first one.
955 *
956 * It serves two main purposes:
957 *
958 * 1. Provide information about "the network for a given type" (since this
959 * API only supports one).
960 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
961 * the first network for a given type changes, or if the default network
962 * changes.
963 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900964 @VisibleForTesting
965 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900966
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900967 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900968 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900969
Robert Greenwalt802c1102014-06-02 15:32:02 -0700970 /**
971 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
972 * Each list holds references to all NetworkAgentInfos that are used to
973 * satisfy requests for that network type.
974 *
975 * This array is built out at startup such that an unsupported network
976 * doesn't get an ArrayList instance, making this a tristate:
977 * unsupported, supported but not active and active.
978 *
979 * The actual lists are populated when we scan the network types that
980 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900981 *
982 * Threading model:
983 * - addSupportedType() is only called in the constructor
984 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
985 * They are therefore not thread-safe with respect to each other.
986 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
987 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900988 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900989 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700990 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900991 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900992 @NonNull
993 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700994
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900995 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
996 // an entry have no timer (equivalent to -1). Lazily loaded.
997 @NonNull
998 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
999
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001000 LegacyTypeTracker(@NonNull ConnectivityService service) {
1001 mService = service;
1002 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001003 }
1004
Chiachang Wang3bc52762021-11-25 14:17:57 +08001005 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1006 // addressed.
1007 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001008 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1009 final PackageManager pm = ctx.getPackageManager();
1010 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1011 addSupportedType(TYPE_WIFI);
1012 }
1013 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1014 addSupportedType(TYPE_WIFI_P2P);
1015 }
1016 if (tm.isDataCapable()) {
1017 // Telephony does not have granular support for these types: they are either all
1018 // supported, or none is supported
1019 addSupportedType(TYPE_MOBILE);
1020 addSupportedType(TYPE_MOBILE_MMS);
1021 addSupportedType(TYPE_MOBILE_SUPL);
1022 addSupportedType(TYPE_MOBILE_DUN);
1023 addSupportedType(TYPE_MOBILE_HIPRI);
1024 addSupportedType(TYPE_MOBILE_FOTA);
1025 addSupportedType(TYPE_MOBILE_IMS);
1026 addSupportedType(TYPE_MOBILE_CBS);
1027 addSupportedType(TYPE_MOBILE_IA);
1028 addSupportedType(TYPE_MOBILE_EMERGENCY);
1029 }
1030 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1031 addSupportedType(TYPE_BLUETOOTH);
1032 }
1033 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1034 // TYPE_PROXY is only used on Wear
1035 addSupportedType(TYPE_PROXY);
1036 }
1037 // Ethernet is often not specified in the configs, although many devices can use it via
1038 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001039 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001040 addSupportedType(TYPE_ETHERNET);
1041 }
1042
1043 // Always add TYPE_VPN as a supported type
1044 addSupportedType(TYPE_VPN);
1045 }
1046
1047 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001048 if (mTypeLists[type] != null) {
1049 throw new IllegalStateException(
1050 "legacy list for type " + type + "already initialized");
1051 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001052 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001053 }
1054
Robert Greenwalt802c1102014-06-02 15:32:02 -07001055 public boolean isTypeSupported(int type) {
1056 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1057 }
1058
1059 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001060 synchronized (mTypeLists) {
1061 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1062 return mTypeLists[type].get(0);
1063 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001064 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001065 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001066 }
1067
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001068 public int getRestoreTimerForType(int type) {
1069 synchronized (mTypeLists) {
1070 if (mRestoreTimers == null) {
1071 mRestoreTimers = loadRestoreTimers();
1072 }
1073 return mRestoreTimers.getOrDefault(type, -1);
1074 }
1075 }
1076
1077 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1078 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001079 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001080 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1081 for (final String config : configs) {
1082 final String[] splits = TextUtils.split(config, ",");
1083 if (splits.length != 2) {
1084 logwtf("Invalid restore timer token count: " + config);
1085 continue;
1086 }
1087 try {
1088 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1089 } catch (NumberFormatException e) {
1090 logwtf("Invalid restore timer number format: " + config, e);
1091 }
1092 }
1093 return ret;
1094 }
1095
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001096 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001097 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001098 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001099 log("Sending " + state
1100 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001101 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001102 }
1103 }
1104
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001105 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1106 // network type, to preserve previous behaviour.
1107 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1108 if (vpnNai != mService.getLegacyLockdownNai()) return;
1109
1110 if (vpnNai.declaredUnderlyingNetworks == null
1111 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1112 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1113 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1114 return;
1115 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001116 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001117 vpnNai.declaredUnderlyingNetworks[0]);
1118 if (underlyingNai == null) return;
1119
1120 final int type = underlyingNai.networkInfo.getType();
1121 final DetailedState state = DetailedState.CONNECTED;
1122 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1123 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1124 }
1125
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001126 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001127 public void add(int type, NetworkAgentInfo nai) {
1128 if (!isTypeSupported(type)) {
1129 return; // Invalid network type.
1130 }
1131 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1132
1133 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1134 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001135 return;
1136 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001137 synchronized (mTypeLists) {
1138 list.add(nai);
1139 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001140
Chalard Jean5b409c72021-02-04 13:12:59 +09001141 // Send a broadcast if this is the first network of its type or if it's the default.
1142 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001143
1144 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1145 // to preserve previous behaviour.
1146 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001147 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001148 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1149 mService.sendLegacyNetworkBroadcast(nai, state, type);
1150 }
1151
1152 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1153 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001154 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001155 }
1156
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001157 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001158 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001159 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1160 if (list == null || list.isEmpty()) {
1161 return;
1162 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001163 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001164
Hugo Benichi389633f2016-06-21 09:48:07 +09001165 synchronized (mTypeLists) {
1166 if (!list.remove(nai)) {
1167 return;
1168 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001169 }
1170
Lorenzo Colitti49767722015-05-01 00:30:10 +09001171 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001172 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1173 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001174 }
1175
1176 if (!list.isEmpty() && wasFirstNetwork) {
1177 if (DBG) log("Other network available for type " + type +
1178 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001179 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001180 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001181 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001182 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001183 }
1184 }
1185
1186 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001187 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1188 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001189 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001190 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001191 }
1192 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001193
Chalard Jean46bfbf02022-02-02 00:56:25 +09001194 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001195 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001196 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001197 final DetailedState state = nai.networkInfo.getDetailedState();
1198 for (int type = 0; type < mTypeLists.length; type++) {
1199 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001200 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001201 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001202 if (isFirst || contains && isDefault) {
1203 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001204 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001205 }
1206 }
1207 }
1208
Robert Greenwalt94e22142014-07-30 16:31:24 -07001209 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001210 pw.println("mLegacyTypeTracker:");
1211 pw.increaseIndent();
1212 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001213 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001214 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001215 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001216 pw.println();
1217 pw.println("Current state:");
1218 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001219 synchronized (mTypeLists) {
1220 for (int type = 0; type < mTypeLists.length; type++) {
1221 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1222 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001223 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001224 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001225 }
1226 }
1227 pw.decreaseIndent();
1228 pw.decreaseIndent();
1229 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001230 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001231 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001232 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001233
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001234 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001235 /**
1236 * Helper class which parses out priority arguments and dumps sections according to their
1237 * priority. If priority arguments are omitted, function calls the legacy dump command.
1238 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001239 private class LocalPriorityDump {
1240 private static final String PRIORITY_ARG = "--dump-priority";
1241 private static final String PRIORITY_ARG_HIGH = "HIGH";
1242 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1243
1244 LocalPriorityDump() {}
1245
1246 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1247 doDump(fd, pw, new String[] {DIAG_ARG});
1248 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001249 }
1250
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001251 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1252 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001253 }
1254
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001255 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1256 if (args == null) {
1257 dumpNormal(fd, pw, args);
1258 return;
1259 }
1260
1261 String priority = null;
1262 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1263 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1264 argIndex++;
1265 priority = args[argIndex];
1266 }
1267 }
1268
1269 if (PRIORITY_ARG_HIGH.equals(priority)) {
1270 dumpHigh(fd, pw);
1271 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1272 dumpNormal(fd, pw, args);
1273 } else {
1274 // ConnectivityService publishes binder service using publishBinderService() with
1275 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001276 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1277 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001278 // TODO: Integrate into signal dump.
1279 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001280 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001281 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001282 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001283
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001284 /**
1285 * Dependencies of ConnectivityService, for injection in tests.
1286 */
1287 @VisibleForTesting
1288 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001289 public int getCallingUid() {
1290 return Binder.getCallingUid();
1291 }
1292
Chalard Jeandf29a852023-05-29 17:02:43 +09001293 public boolean isAtLeastS() {
1294 return SdkLevel.isAtLeastS();
1295 }
1296
1297 public boolean isAtLeastT() {
1298 return SdkLevel.isAtLeastT();
1299 }
1300
1301 public boolean isAtLeastU() {
1302 return SdkLevel.isAtLeastU();
1303 }
1304
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001305 /**
1306 * Get system properties to use in ConnectivityService.
1307 */
1308 public MockableSystemProperties getSystemProperties() {
1309 return new MockableSystemProperties();
1310 }
1311
1312 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001313 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1314 */
1315 public ConnectivityResources getResources(@NonNull Context ctx) {
1316 return new ConnectivityResources(ctx);
1317 }
1318
1319 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001320 * Create a HandlerThread to use in ConnectivityService.
1321 */
1322 public HandlerThread makeHandlerThread() {
1323 return new HandlerThread("ConnectivityServiceThread");
1324 }
1325
1326 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001327 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001328 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001329 public NetworkStackClientBase getNetworkStack() {
1330 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001331 }
1332
1333 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001334 * @see ProxyTracker
1335 */
1336 public ProxyTracker makeProxyTracker(@NonNull Context context,
1337 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001338 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001339 }
1340
1341 /**
1342 * @see NetIdManager
1343 */
1344 public NetIdManager makeNetIdManager() {
1345 return new NetIdManager();
1346 }
1347
1348 /**
1349 * @see NetworkUtils#queryUserAccess(int, int)
1350 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001351 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1352 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001353 }
1354
1355 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001356 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1357 * requires CAP_NET_ADMIN, which the unit tests do not have.
1358 */
1359 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1360 InetSocketAddress remote) {
1361 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1362 }
1363
1364 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001365 * @see MultinetworkPolicyTracker
1366 */
1367 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1368 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1369 return new MultinetworkPolicyTracker(c, h, r);
1370 }
1371
Aaron Huang330a4c02020-10-27 03:36:19 +08001372 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001373 * @see AutomaticOnOffKeepaliveTracker
1374 */
1375 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1376 @NonNull Context c, @NonNull Handler h) {
1377 return new AutomaticOnOffKeepaliveTracker(c, h);
1378 }
1379
1380 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001381 * @see BatteryStatsManager
1382 */
1383 public void reportNetworkInterfaceForTransports(Context context, String iface,
1384 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001385 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001386 context.getSystemService(BatteryStatsManager.class);
1387 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1388 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001389
1390 public boolean getCellular464XlatEnabled() {
1391 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1392 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001393
1394 /**
1395 * @see PendingIntent#intentFilterEquals
1396 */
1397 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1398 return a.intentFilterEquals(b);
1399 }
1400
1401 /**
1402 * @see LocationPermissionChecker
1403 */
1404 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1405 return new LocationPermissionChecker(context);
1406 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001407
1408 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001409 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001410 *
1411 * This method returns null in versions before T, where carrier privilege
1412 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001413 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001414 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001415 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1416 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001417 if (isAtLeastT()) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09001418 return new CarrierPrivilegeAuthenticator(context, tm);
1419 } else {
1420 return null;
1421 }
1422 }
1423
1424 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001425 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001426 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001427 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001428 return DeviceConfigUtils.isTetheringFeatureEnabled(context, NAMESPACE_TETHERING, name,
Motomu Utsumi278db582023-04-21 12:35:22 +09001429 TETHERING_MODULE_NAME, false /* defaultValue */);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001430 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001431
1432 /**
1433 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001434 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001435 * @return BpfNetMaps implementation.
1436 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001437 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1438 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001439 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001440
1441 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001442 * @see ClatCoordinator
1443 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001444 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001445 public ClatCoordinator getClatCoordinator(INetd netd) {
1446 return new ClatCoordinator(
1447 new ClatCoordinator.Dependencies() {
1448 @NonNull
1449 public INetd getNetd() {
1450 return netd;
1451 }
1452 });
1453 }
1454
1455 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001456 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1457 */
1458 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1459 final InterfaceParams params = InterfaceParams.getByName(iface);
1460 if (params == null) {
1461 // the interface might have disappeared.
1462 logw("Failed to get interface params for interface " + iface);
1463 return;
1464 }
1465 try {
1466 // converting rateInBytesPerSecond from long to int is safe here because the
1467 // setting's range is limited to INT_MAX.
1468 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001469 Log.i(TAG,
1470 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001471 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1472 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1473 } catch (IOException e) {
1474 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1475 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1476 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1477 + ") failure: ", e);
1478 }
1479 }
1480
1481 /**
1482 * Wraps {@link TcUtils#tcFilterDelDev}
1483 */
1484 public void disableIngressRateLimit(String iface) {
1485 final InterfaceParams params = InterfaceParams.getByName(iface);
1486 if (params == null) {
1487 // the interface might have disappeared.
1488 logw("Failed to get interface params for interface " + iface);
1489 return;
1490 }
1491 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001492 Log.i(TAG,
1493 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001494 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1495 } catch (IOException e) {
1496 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1497 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1498 }
1499 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001500
1501 /**
1502 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1503 */
1504 // TODO: when available in all active branches:
1505 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1506 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1507 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1508 return BroadcastOptionsShimImpl.newInstance(options);
1509 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001510
1511 /**
1512 * Wrapper method for
1513 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1514 *
1515 * @param changeId The ID of the compatibility change in question.
1516 * @param packageName The package name of the app in question.
1517 * @param user The user that the operation is done for.
1518 * @return {@code true} if the change is enabled for the specified package.
1519 */
1520 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1521 @NonNull final UserHandle user) {
1522 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1523 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001524
1525 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001526 * As above but with a UID.
1527 * @see CompatChanges#isChangeEnabled(long, int)
1528 */
1529 public boolean isChangeEnabled(final long changeId, final int uid) {
1530 return CompatChanges.isChangeEnabled(changeId, uid);
1531 }
1532
1533 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001534 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1535 *
1536 * @param ranges target uid ranges
1537 * @param exemptUids uids to skip close socket
1538 */
1539 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1540 @NonNull final Set<Integer> exemptUids)
1541 throws SocketException, InterruptedIOException, ErrnoException {
1542 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1543 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001544
1545 /**
1546 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1547 *
1548 * @param ownerUids target uids to close sockets
1549 */
1550 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1551 throws SocketException, InterruptedIOException, ErrnoException {
1552 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1553 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001554
1555 /**
1556 * Schedule the evaluation timeout.
1557 *
1558 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1559 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1560 * of these events happen, this time will run out, after which the network is considered
1561 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1562 * on this network and considers it won't provide connectivity. In particular, that means
1563 * it's when the system prefers it to cell if it's wifi and configuration says it should
1564 * prefer bad wifi to cell.
1565 */
1566 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1567 @NonNull final Network network, final long delayMs) {
1568 handler.sendMessageDelayed(
1569 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1570 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001571 }
1572
junyulaie7c7d2a2021-01-26 15:29:15 +08001573 public ConnectivityService(Context context) {
1574 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001575 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1576 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001577 }
1578
1579 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001580 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1581 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001582 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001583
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001584 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001585 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001586 mSystemProperties = mDeps.getSystemProperties();
1587 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001588 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001589 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001590 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1591 // Pass limit - 1 to maintain backward compatibility.
1592 // TODO: Remove the workaround.
1593 mNetworkRequestCounter =
1594 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1595 mSystemNetworkRequestCounter =
1596 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001597
Hugo Benichi208c0102016-07-28 17:53:06 +09001598 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001599 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1600 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001601 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001602 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001603 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001604 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1605 mDefaultNetworkRequests.add(mDefaultRequest);
1606 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001607
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001608 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001609 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001610
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001611 // The default WiFi request is a background request so that apps using WiFi are
1612 // migrated to a better network (typically ethernet) when one comes up, instead
1613 // of staying on WiFi forever.
1614 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1615 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1616
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001617 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1618 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1619 NetworkRequest.Type.BACKGROUND_REQUEST);
1620
Chalard Jean0702f982021-09-16 21:50:07 +09001621 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1622 // TODO: Consider making the timer customizable.
1623 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1624 mCellularRadioTimesharingCapable =
1625 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1626
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001627 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1628 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1629
1630 if (SdkLevel.isAtLeastU()) {
1631 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1632 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1633 final int defaultUMarkMask = 0x80000000; // u32
1634
1635 if ((mark == 0) || (mask == 0)) {
1636 // simply treat unset/disabled as the default U value
1637 mark = defaultUMarkMask;
1638 mask = defaultUMarkMask;
1639 }
1640 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1641 // invalid device overlay settings
1642 throw new IllegalArgumentException(
1643 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1644 }
1645 }
1646
1647 mWakeUpMark = mark;
1648 mWakeUpMask = mask;
1649
Paul Hu51f816b2022-08-11 14:43:47 +00001650 mNetd = netd;
1651 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001652 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001653 mPermissionMonitor =
1654 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001655 mHandlerThread.start();
1656 mHandler = new InternalHandler(mHandlerThread.getLooper());
1657 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001658 mConnectivityDiagnosticsHandler =
1659 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001660
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001661 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001662 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001663
junyulaie7c7d2a2021-01-26 15:29:15 +08001664 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001665 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001666 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001667 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001668
Wink Saville32506bc2013-06-29 21:10:57 -07001669 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001670 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001671 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001672 mCarrierPrivilegeAuthenticator =
1673 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001674
Sudheer Shanka9967d462021-03-18 19:09:25 +00001675 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001676 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1677 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001678 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001679
1680 final PowerManager powerManager = (PowerManager) context.getSystemService(
1681 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001682 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001683 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001684
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001685 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1686 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001687 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001688 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001689 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001690 mProtectedNetworks.add(p);
1691 } else {
1692 if (DBG) loge("Ignoring protectedNetwork " + p);
1693 }
1694 }
1695
soma, kawata29444ae2019-05-23 09:30:40 +09001696 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1697
James Mattis02220e22021-03-13 19:27:21 -08001698 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001699 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001700 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001701 final IntentFilter userIntentFilter = new IntentFilter();
1702 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1703 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1704 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1705 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001706
James Mattis02220e22021-03-13 19:27:21 -08001707 // Listen to package add/removes for netd
1708 final IntentFilter packageIntentFilter = new IntentFilter();
1709 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1710 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1711 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1712 packageIntentFilter.addDataScheme("package");
1713 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001714 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001715
Motomu Utsumi1e51a642023-07-18 15:11:41 +09001716 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001717
Chalard Jean46bfbf02022-02-02 00:56:25 +09001718 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001719 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001720 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001721 } catch (RemoteException | ServiceSpecificException e) {
1722 loge("Error registering event listener :" + e);
1723 }
1724
Erik Kline05f2b402015-04-30 12:58:40 +09001725 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1726 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001727
chiachangwang7c17c282023-02-02 05:58:59 +00001728 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001729 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001730 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001731
1732 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001733 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001734 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1735 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001736 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001737 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1738 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001739
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001740 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001741 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001742 mNetworkRanker =
1743 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1744
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001745 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001746
Chiachang Wangc1215d32020-10-20 15:38:58 +08001747 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001748 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001749
Chalard Jean28018572020-12-21 18:36:52 +09001750 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1751 // request that doesn't allow fallback to the default network. It should never be visible
1752 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1753 // arguments like the handler or the DnsResolver.
1754 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001755 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001756 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001757 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001758 new LinkProperties(), new NetworkCapabilities(),
1759 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001760 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1761 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001762
1763 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001764 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1765 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1766 // Even if it could, running on S would at least require mocking out the BPF map,
1767 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1768 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001769 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001770 mDscpPolicyTracker = new DscpPolicyTracker();
1771 }
Tyler Wear72388212021-09-09 14:49:02 -07001772 } catch (ErrnoException e) {
1773 loge("Unable to create DscpPolicyTracker");
1774 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001775
1776 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1777 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001778
Chalard Jeandf29a852023-05-29 17:02:43 +09001779 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001780 mCdmps = new CompanionDeviceManagerProxyService(context);
1781 } else {
1782 mCdmps = null;
1783 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001784
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001785 mDestroyFrozenSockets = mDeps.isAtLeastU()
1786 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
1787 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1788 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
1789 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001790 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1791 new UidFrozenStateChangedCallback() {
1792 @Override
1793 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1794 if (uids.length != frozenStates.length) {
1795 Log.wtf(TAG, "uids has length " + uids.length
1796 + " but frozenStates has length " + frozenStates.length);
1797 return;
1798 }
1799
1800 final UidFrozenStateChangedArgs args =
1801 new UidFrozenStateChangedArgs(uids, frozenStates);
1802
1803 mHandler.sendMessage(
1804 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1805 }
1806 };
1807
1808 final ActivityManager activityManager =
1809 mContext.getSystemService(ActivityManager.class);
1810 activityManager.registerUidFrozenStateChangedCallback(
1811 (Runnable r) -> r.run(), frozenStateChangedCallback);
1812 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001813 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001814
Xiao Ma0a171c02022-01-23 16:14:51 +00001815 /**
1816 * Check whether or not the device supports Ethernet transport.
1817 */
1818 public static boolean deviceSupportsEthernet(final Context context) {
1819 final PackageManager pm = context.getPackageManager();
1820 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1821 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1822 }
1823
Chalard Jean46adcf32018-04-18 20:18:38 +09001824 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001825 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1826 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001827 }
1828
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001829 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1830 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001831 final NetworkCapabilities netCap = new NetworkCapabilities();
1832 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001833 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001834 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001835 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001836 return netCap;
1837 }
1838
James Mattis45d81842021-01-10 14:24:24 -08001839 private NetworkRequest createDefaultRequest() {
1840 return createDefaultInternetRequestForTransport(
1841 TYPE_NONE, NetworkRequest.Type.REQUEST);
1842 }
1843
lucaslin3ba7cc22022-12-19 02:35:33 +00001844 private NetworkRequest createVpnRequest() {
1845 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1846 .withoutDefaultCapabilities()
1847 .addTransportType(TRANSPORT_VPN)
1848 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1849 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1850 .build();
1851 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1852 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1853 }
1854
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001855 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001856 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001857 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001858 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001859 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001860 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001861 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001862 netCap.addTransportType(transportType);
1863 }
James Mattis45d81842021-01-10 14:24:24 -08001864 return createNetworkRequest(type, netCap);
1865 }
1866
1867 private NetworkRequest createNetworkRequest(
1868 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001869 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001870 }
1871
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001872 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1873 NetworkRequest.Type type) {
1874 final NetworkCapabilities netCap = new NetworkCapabilities();
1875 netCap.clearAll();
1876 netCap.addCapability(capability);
1877 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1878 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1879 }
1880
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001881 // Used only for testing.
1882 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001883 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001884 // changing ContentResolver to make registerContentObserver non-final).
1885 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1886 // by subclassing SettingsObserver.
1887 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001888 void updateAlwaysOnNetworks() {
1889 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001890 }
1891
Erik Kline9a62f012018-03-21 07:18:33 -07001892 // See FakeSettingsProvider comment above.
1893 @VisibleForTesting
1894 void updatePrivateDnsSettings() {
1895 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1896 }
1897
paulhu51f77dc2021-06-07 02:34:20 +00001898 @VisibleForTesting
1899 void updateMobileDataPreferredUids() {
1900 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1901 }
1902
Patrick Rohr2857ac42022-01-21 14:58:16 +01001903 @VisibleForTesting
1904 void updateIngressRateLimit() {
1905 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1906 }
1907
Aaron Huang40b52442021-06-08 04:34:24 +08001908 @VisibleForTesting
1909 void simulateUpdateProxyInfo(@Nullable final Network network,
1910 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001911 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08001912 new Pair<>(network, proxyInfo)).sendToTarget();
1913 }
1914
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001915 private void handleAlwaysOnNetworkRequest(
1916 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001917 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001918 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001919 handleAlwaysOnNetworkRequest(networkRequest, enable);
1920 }
1921
1922 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001923 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001924 if (enable == isEnabled) {
1925 return; // Nothing to do.
1926 }
1927
1928 if (enable) {
1929 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001930 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001931 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001932 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001933 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001934 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1935 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001936 }
1937 }
1938
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001939 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001940 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1941 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1942 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1943 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001944 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1945 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001946 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001947 }
1948
paulhu51f77dc2021-06-07 02:34:20 +00001949 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001950 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001951 private void registerSettingsCallbacks() {
1952 // Watch for global HTTP proxy changes.
1953 mSettingsObserver.observe(
1954 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1955 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1956
Chalard Jean46bfbf02022-02-02 00:56:25 +09001957 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001958 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001959 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001960 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1961
Chalard Jean46bfbf02022-02-02 00:56:25 +09001962 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001963 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001964 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001965 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001966
1967 // Watch for mobile data preferred uids changes.
1968 mSettingsObserver.observe(
1969 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1970 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001971
1972 // Watch for ingress rate limit changes.
1973 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01001974 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01001975 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1976 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001977 }
1978
Erik Kline31b4a9e2018-01-11 21:07:29 +09001979 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001980 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1981 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001982 }
1983 }
1984
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001985 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001986 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1987 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001988 return mNextNetworkRequestId++;
1989 }
1990
junyulai74f9a8b2018-06-13 15:00:37 +08001991 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09001992 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08001993 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001994 if (network == null) {
1995 return null;
1996 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001997 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001998 }
1999
2000 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002001 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002002 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002003 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002004 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002005
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002006 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002007 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002008 private NetworkAgentInfo getVpnForUid(int uid) {
2009 synchronized (mNetworkForNetId) {
2010 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2011 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002012 if (nai.isVPN() && nai.everConnected()
2013 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002014 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002015 }
2016 }
2017 }
2018 return null;
2019 }
2020
Chalard Jean46bfbf02022-02-02 00:56:25 +09002021 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002022 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002023 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002024 final NetworkAgentInfo nai = getVpnForUid(uid);
2025 if (nai != null) return nai.declaredUnderlyingNetworks;
2026 return null;
2027 }
2028
Lorenzo Colittia7574052021-01-19 01:33:05 +09002029 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002030 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002031
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002032 final Network[] networks = getVpnUnderlyingNetworks(uid);
2033 if (networks != null) {
2034 // getUnderlyingNetworks() returns:
2035 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2036 // empty array => the VPN explicitly said "no default network".
2037 // non-empty array => the VPN specified one or more default networks; we use the
2038 // first one.
2039 if (networks.length > 0) {
2040 nai = getNetworkAgentInfoForNetwork(networks[0]);
2041 } else {
2042 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002043 }
2044 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002045 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002046 }
2047
2048 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002049 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002050 */
paulhu7aeba372020-12-30 00:42:19 +08002051 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2052 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002053 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002054 if (ignoreBlocked) {
2055 return false;
2056 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002057 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002058 final long ident = Binder.clearCallingIdentity();
2059 try {
2060 final boolean metered = nc == null ? true : nc.isMetered();
2061 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2062 } finally {
2063 Binder.restoreCallingIdentity(ident);
2064 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002065 }
2066
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002067 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002068 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2069 return;
2070 }
Hugo Benichi47011212017-03-30 10:46:05 +09002071 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002072 synchronized (mBlockedAppUids) {
2073 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002074 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002075 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002076 blocked = false;
2077 } else {
2078 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002079 }
2080 }
Hugo Benichi47011212017-03-30 10:46:05 +09002081 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2082 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2083 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002084 }
2085
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002086 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002087 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2088 return;
2089 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002090 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002091 final int requestId = nri.getActiveRequest() != null
2092 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002093 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002094 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002095 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002096 }
2097
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002098 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002099 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002100 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002101 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002102 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002103 @NonNull
2104 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2105 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002106 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2107 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2108 // but only exists if an app asks about them or requests them. Ensure the requesting app
2109 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002110 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002111 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2112 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2113 null /* extraInfo */);
2114 }
2115 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002116 return filtered;
2117 }
2118
2119 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2120 boolean ignoreBlocked) {
2121 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2122 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002123 }
2124
2125 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002126 * Return NetworkInfo for the active (i.e., connected) network interface.
2127 * It is assumed that at most one network is active at a time. If more
2128 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002129 * @return the info for the active network, or {@code null} if none is
2130 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002131 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002132 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002133 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002134 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002135 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002136 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002137 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2138 if (nai == null) return null;
2139 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2140 maybeLogBlockedNetworkInfo(networkInfo, uid);
2141 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002142 }
2143
Paul Jensen1f567382015-02-13 14:18:39 -05002144 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002145 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002146 public Network getActiveNetwork() {
2147 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002148 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002149 }
2150
2151 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002152 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002153 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002154 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002155 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002156 }
2157
Chalard Jean46bfbf02022-02-02 00:56:25 +09002158 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002159 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002160 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2161 if (vpnNai != null) {
2162 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2163 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2164 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002165 }
Paul Jensen1f567382015-02-13 14:18:39 -05002166 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002167
James Mattis2516da32021-01-31 17:06:19 -08002168 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002169 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2170 ignoreBlocked)) {
2171 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002172 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002173 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002174 }
2175
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002176 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002177 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002178 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002179 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002180 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2181 if (nai == null) return null;
2182 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002183 }
2184
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002185 /** Returns a NetworkInfo object for a network that doesn't exist. */
2186 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2187 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2188 getNetworkTypeName(networkType), "" /* subtypeName */);
2189 info.setIsAvailable(true);
2190 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2191 // background data is restricted.
2192 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2193 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2194 ? DetailedState.BLOCKED
2195 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002196 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2197 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002198 return info;
2199 }
2200
Lorenzo Colittia7574052021-01-19 01:33:05 +09002201 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002202 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2203 return null;
2204 }
2205 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002206 if (nai == null) {
2207 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002208 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002209 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2210 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002211 }
2212
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002213 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002214 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002215 public NetworkInfo getNetworkInfo(int networkType) {
2216 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002217 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002218 if (getVpnUnderlyingNetworks(uid) != null) {
2219 // A VPN is active, so we may need to return one of its underlying networks. This
2220 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002221 // getNetworkAgentInfoForUid.
2222 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2223 if (nai == null) return null;
2224 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2225 if (networkInfo.getType() == networkType) {
2226 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002227 }
2228 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002229 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002230 }
2231
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002232 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002233 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002234 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002235 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002236 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002237 if (nai == null) return null;
2238 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002239 }
2240
2241 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002242 public NetworkInfo[] getAllNetworkInfo() {
2243 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002244 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002245 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2246 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002247 NetworkInfo info = getNetworkInfo(networkType);
2248 if (info != null) {
2249 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002250 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002251 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002252 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002253 }
2254
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002255 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002256 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002257 public Network getNetworkForType(int networkType) {
2258 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002259 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2260 return null;
2261 }
2262 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2263 if (nai == null) {
2264 return null;
2265 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002266 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002267 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2268 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002269 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002270 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002271 }
2272
2273 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002274 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002275 public Network[] getAllNetworks() {
2276 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002277 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002278 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002279 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002280 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002281 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002282 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002283 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002284 }
2285
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002286 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002287 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002288 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002289 // The basic principle is: if an app's traffic could possibly go over a
2290 // network, without the app doing anything multinetwork-specific,
2291 // (hence, by "default"), then include that network's capabilities in
2292 // the array.
2293 //
2294 // In the normal case, app traffic only goes over the system's default
2295 // network connection, so that's the only network returned.
2296 //
2297 // With a VPN in force, some app traffic may go into the VPN, and thus
2298 // over whatever underlying networks the VPN specifies, while other app
2299 // traffic may go over the system default network (e.g.: a split-tunnel
2300 // VPN, or an app disallowed by the VPN), so the set of networks
2301 // returned includes the VPN's underlying networks and the system
2302 // default.
2303 enforceAccessPermission();
2304
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002305 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002306
James Mattis2516da32021-01-31 17:06:19 -08002307 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2308 if (!nri.isBeingSatisfied()) {
2309 continue;
2310 }
2311 final NetworkAgentInfo nai = nri.getSatisfier();
2312 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2313 if (null != nc
2314 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2315 && !result.containsKey(nai.network)) {
2316 result.put(
2317 nai.network,
2318 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002319 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002320 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2321 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002322 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002323 }
2324
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002325 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002326 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002327 if (null != networks) {
2328 for (final Network network : networks) {
2329 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2330 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002331 result.put(
2332 network,
2333 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002334 nc,
2335 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002336 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002337 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002338 }
2339 }
2340 }
2341
2342 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2343 out = result.values().toArray(out);
2344 return out;
2345 }
2346
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002347 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002348 public boolean isNetworkSupported(int networkType) {
2349 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002350 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002351 }
2352
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002353 /**
2354 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002355 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002356 * @return the ip properties for the active network, or {@code null} if
2357 * none is active
2358 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002359 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002360 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002361 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002362 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002363 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2364 if (nai == null) return null;
2365 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002366 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002367 }
2368
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002369 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002370 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002371 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002372 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002373 final LinkProperties lp = getLinkProperties(nai);
2374 if (lp == null) return null;
2375 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002376 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002377 }
2378
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002379 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002380 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002381 public LinkProperties getLinkProperties(Network network) {
2382 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002383 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2384 if (lp == null) return null;
2385 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002386 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002387 }
2388
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002389 @Nullable
2390 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002391 if (nai == null) {
2392 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002393 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002394 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002395 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002396 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002397 }
2398
lucaslinc582d502022-01-27 09:07:00 +08002399 @Override
2400 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002401 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002402 @NonNull String packageName, @Nullable String callingAttributionTag) {
2403 Objects.requireNonNull(packageName);
2404 Objects.requireNonNull(lp);
2405 enforceNetworkStackOrSettingsPermission();
2406 if (!checkAccessPermission(-1 /* pid */, uid)) {
2407 return null;
2408 }
2409 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2410 }
2411
Qingxi Lib2748102020-01-08 12:51:49 -08002412 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2413 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2414 }
2415
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002416 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002417 if (nai == null) return null;
2418 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002419 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002420 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002421 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002422 }
2423
2424 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002425 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2426 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002427 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002428 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002429 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002430 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002431 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002432 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002433 }
2434
lucaslinc582d502022-01-27 09:07:00 +08002435 @Override
lucaslind2b06132022-03-02 10:56:57 +08002436 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2437 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2438 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002439 Objects.requireNonNull(nc);
2440 Objects.requireNonNull(packageName);
2441 enforceNetworkStackOrSettingsPermission();
2442 if (!checkAccessPermission(-1 /* pid */, uid)) {
2443 return null;
2444 }
2445 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2446 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2447 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2448 callingAttributionTag);
2449 }
2450
lucaslin69e1aa92022-03-22 18:15:09 +08002451 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2452 if (nc.getUnderlyingNetworks() != null
2453 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2454 nc.setUnderlyingNetworks(null);
2455 }
2456 }
2457
Qingxi Libb8da982020-01-17 17:54:27 -08002458 @VisibleForTesting
2459 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002460 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002461 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2462 // this would be expensive (one more permission check every time any NC callback is
2463 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2464 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2465 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002466 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002467 if (!checkSettingsPermission(callerPid, callerUid)) {
2468 newNc.setUids(null);
2469 newNc.setSSID(null);
2470 }
Etan Cohen107ae952018-12-30 17:59:59 -08002471 if (newNc.getNetworkSpecifier() != null) {
2472 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2473 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002474 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2475 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002476 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2477 newNc.setAdministratorUids(new int[0]);
2478 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002479 if (!checkAnyPermissionOf(mContext,
Benedict Wong53de25f2021-03-24 14:01:51 -07002480 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002481 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002482 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002483 }
lucaslin69e1aa92022-03-22 18:15:09 +08002484 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002485
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002486 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002487 }
2488
Roshan Pius98f59ec2021-02-23 08:47:39 -08002489 /**
2490 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002491 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002492 * NetworkCapabilities.
2493 * Note: This wrapper does not support any sort of invalidation and thus must not be
2494 * persistent or long-lived. It may only be used for the time necessary to
2495 * compute the redactions required by one particular NetworkCallback or
2496 * synchronous call.
2497 */
2498 private class RedactionPermissionChecker {
2499 private final int mCallingPid;
2500 private final int mCallingUid;
2501 @NonNull private final String mCallingPackageName;
2502 @Nullable private final String mCallingAttributionTag;
2503
2504 private Boolean mHasLocationPermission = null;
2505 private Boolean mHasLocalMacAddressPermission = null;
2506 private Boolean mHasSettingsPermission = null;
2507
2508 RedactionPermissionChecker(int callingPid, int callingUid,
2509 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2510 mCallingPid = callingPid;
2511 mCallingUid = callingUid;
2512 mCallingPackageName = callingPackageName;
2513 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002514 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002515
2516 private boolean hasLocationPermissionInternal() {
2517 final long token = Binder.clearCallingIdentity();
2518 try {
2519 return mLocationPermissionChecker.checkLocationPermission(
2520 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2521 null /* message */);
2522 } finally {
2523 Binder.restoreCallingIdentity(token);
2524 }
2525 }
2526
2527 /**
2528 * Returns whether the app holds location permission or not (might return cached result
2529 * if the permission was already checked before).
2530 */
2531 public boolean hasLocationPermission() {
2532 if (mHasLocationPermission == null) {
2533 // If there is no cached result, perform the check now.
2534 mHasLocationPermission = hasLocationPermissionInternal();
2535 }
2536 return mHasLocationPermission;
2537 }
2538
2539 /**
2540 * Returns whether the app holds local mac address permission or not (might return cached
2541 * result if the permission was already checked before).
2542 */
2543 public boolean hasLocalMacAddressPermission() {
2544 if (mHasLocalMacAddressPermission == null) {
2545 // If there is no cached result, perform the check now.
2546 mHasLocalMacAddressPermission =
2547 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2548 }
2549 return mHasLocalMacAddressPermission;
2550 }
2551
2552 /**
2553 * Returns whether the app holds settings permission or not (might return cached
2554 * result if the permission was already checked before).
2555 */
2556 public boolean hasSettingsPermission() {
2557 if (mHasSettingsPermission == null) {
2558 // If there is no cached result, perform the check now.
2559 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2560 }
2561 return mHasSettingsPermission;
2562 }
2563 }
2564
2565 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2566 @NetworkCapabilities.NetCapability long redaction) {
2567 return (redactions & redaction) != 0;
2568 }
2569
2570 /**
2571 * Use the provided |applicableRedactions| to check the receiving app's
2572 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2573 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2574 * before being sent to the corresponding app.
2575 */
2576 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2577 @NetworkCapabilities.RedactionType long applicableRedactions,
2578 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2579 boolean includeLocationSensitiveInfo) {
2580 long redactions = applicableRedactions;
2581 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2582 if (includeLocationSensitiveInfo
2583 && redactionPermissionChecker.hasLocationPermission()) {
2584 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2585 }
2586 }
2587 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2588 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2589 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2590 }
2591 }
2592 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2593 if (redactionPermissionChecker.hasSettingsPermission()) {
2594 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2595 }
2596 }
2597 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002598 }
2599
Qingxi Lib2748102020-01-08 12:51:49 -08002600 @VisibleForTesting
2601 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002602 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002603 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002604 int callingPid, int callingUid, @NonNull String callingPkgName,
2605 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002606 if (nc == null) {
2607 return null;
2608 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002609 // Avoid doing location permission check if the transport info has no location sensitive
2610 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002611 final RedactionPermissionChecker redactionPermissionChecker =
2612 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2613 callingAttributionTag);
2614 final long redactions = retrieveRequiredRedactions(
2615 nc.getApplicableRedactions(), redactionPermissionChecker,
2616 includeLocationSensitiveInfo);
2617 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002618 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002619 // TODO : calling UID is redacted because apps should generally not know what UID is
2620 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002621 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002622 newNc.setOwnerUid(INVALID_UID);
2623 return newNc;
2624 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002625 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2626 if (nc.hasTransport(TRANSPORT_VPN)) {
2627 // Owner UIDs already checked above. No need to re-check.
2628 return newNc;
2629 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002630 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2631 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002632 // compatibility for older apps.
2633 if (!includeLocationSensitiveInfo
2634 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002635 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002636 newNc.setOwnerUid(INVALID_UID);
2637 return newNc;
2638 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002639 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002640 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002641 newNc.setOwnerUid(INVALID_UID);
2642 }
Qingxi Lib2748102020-01-08 12:51:49 -08002643 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002644 }
2645
lucaslinc582d502022-01-27 09:07:00 +08002646 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002647 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2648 LinkProperties lp, int callerPid, int callerUid) {
2649 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002650 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2651 // this would be expensive (one more permission check every time any LP callback is
2652 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2653 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2654 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002655
2656 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2657 final boolean needsSanitization =
2658 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2659 if (!needsSanitization) {
2660 return new LinkProperties(lp);
2661 }
2662
2663 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002664 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002665 }
2666
2667 final LinkProperties newLp = new LinkProperties(lp);
2668 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2669 // object gets parceled.
2670 newLp.setCaptivePortalApiUrl(null);
2671 newLp.setCaptivePortalData(null);
2672 return newLp;
2673 }
2674
Roshan Pius08c94fb2020-01-16 12:17:17 -08002675 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2676 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002677 // There is no need to track the effective UID of the request here. If the caller
2678 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002679 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002680 // Unprivileged apps can only pass in null or their own UID.
2681 if (nc.getUids() == null) {
2682 // If the caller passes in null, the callback will also match networks that do not
2683 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2684 // In this case, redact everything in the request immediately. This ensures that the
2685 // app is not able to get any redacted information by filing an unredacted request
2686 // and observing whether the request matches something.
2687 if (nc.getNetworkSpecifier() != null) {
2688 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2689 }
2690 } else {
2691 nc.setSingleUid(callerUid);
2692 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002693 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002694 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002695 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002696
2697 // Clear owner UID; this can never come from an app.
2698 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002699 }
2700
Chalard Jean38354d12018-03-20 19:13:57 +09002701 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002702 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002703 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2704 }
2705 }
2706
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002707 @Override
2708 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2709 enforceAccessPermission();
2710 final int callerUid = Binder.getCallingUid();
2711 final long token = Binder.clearCallingIdentity();
2712 try {
2713 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2714 } finally {
2715 Binder.restoreCallingIdentity(token);
2716 }
2717 }
2718
junyulaiebd15162021-03-03 12:09:05 +08002719 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002720 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002721 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002722 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002723 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002724
Serik Beketayev05130302021-01-15 16:47:25 -08002725 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002726 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002727 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2728 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002729 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002730 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002731 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002732 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2733 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002734 }
2735 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002736 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002737 }
2738
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002739 @Override
junyulaiebd15162021-03-03 12:09:05 +08002740 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002741 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002742 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002743 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002744
2745 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2746 for (Network network : getAllNetworks()) {
2747 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09002748 final boolean includeNetwork = (nai != null) && nai.isCreated();
2749 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002750 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2751 // NetworkCapabilities, which may contain UIDs of apps to which the
2752 // network applies. Should the UIDs be cleared so as not to leak or
2753 // interfere ?
2754 result.add(nai.getNetworkStateSnapshot());
2755 }
2756 }
2757 return result;
2758 }
2759
2760 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002761 public boolean isActiveNetworkMetered() {
2762 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002763
Qingxi Lib2748102020-01-08 12:51:49 -08002764 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002765 if (caps != null) {
2766 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2767 } else {
2768 // Always return the most conservative value
2769 return true;
2770 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002771 }
2772
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002773 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002774 * Ensures that the system cannot call a particular method.
2775 */
2776 private boolean disallowedBecauseSystemCaller() {
2777 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002778 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2779 // for devices launched with Q and above. However, existing devices upgrading to Q and
2780 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002781 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002782 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002783 log("This method exists only for app backwards compatibility"
2784 + " and must not be called by system services.");
2785 return true;
2786 }
2787 return false;
2788 }
2789
paulhub2c28682021-08-18 18:35:54 +08002790 private int getAppUid(final String app, final UserHandle user) {
2791 final PackageManager pm =
2792 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2793 final long token = Binder.clearCallingIdentity();
2794 try {
2795 return pm.getPackageUid(app, 0 /* flags */);
2796 } catch (PackageManager.NameNotFoundException e) {
2797 return -1;
2798 } finally {
2799 Binder.restoreCallingIdentity(token);
2800 }
2801 }
2802
2803 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2804 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2805 if (getAppUid(packageName, user) != callingUid) {
2806 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2807 }
2808 }
2809
Lorenzo Colitti23862912018-09-28 11:31:55 +09002810 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002811 * Ensure that a network route exists to deliver traffic to the specified
2812 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002813 * @param networkType the type of the network over which traffic to the
2814 * specified host is to be routed
2815 * @param hostAddress the IP address of the host to which the route is
2816 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002817 * @return {@code true} on success, {@code false} on failure
2818 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002819 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002820 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2821 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002822 if (disallowedBecauseSystemCaller()) {
2823 return false;
2824 }
paulhub2c28682021-08-18 18:35:54 +08002825 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002826 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002827 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002828 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002829 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002830
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002831 InetAddress addr;
2832 try {
2833 addr = InetAddress.getByAddress(hostAddress);
2834 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002835 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002836 return false;
2837 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002838
The Android Open Source Project28527d22009-03-03 19:31:44 -08002839 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002840 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002841 return false;
2842 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002843
2844 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2845 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002846 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002847 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2848 } else {
2849 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2850 }
2851 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002852 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002853
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002854 DetailedState netState;
2855 synchronized (nai) {
2856 netState = nai.networkInfo.getDetailedState();
2857 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002858
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002859 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002860 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002861 log("requestRouteToHostAddress on down network "
2862 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002863 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002864 }
2865 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002866 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002867
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002868 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002869 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002870 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002871 LinkProperties lp;
2872 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002873 synchronized (nai) {
2874 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002875 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002876 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002877 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002878 if (DBG) {
2879 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2880 }
Wink Saville32506bc2013-06-29 21:10:57 -07002881 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002882 } finally {
2883 Binder.restoreCallingIdentity(token);
2884 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002885 }
2886
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002887 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002888 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002889 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002890 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002891 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002892 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002893 if (bestRoute.getGateway().equals(addr)) {
2894 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002895 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002896 } else {
2897 // if we will connect to this through another route, add a direct route
2898 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002899 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002900 }
2901 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002902 if (DBG) log("Adding legacy route " + bestRoute +
2903 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002904
2905 final String dst = bestRoute.getDestinationLinkAddress().toString();
2906 final String nextHop = bestRoute.hasGateway()
2907 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002908 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002909 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2910 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002911 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002912 return false;
2913 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002914 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002915 }
2916
paulhu7c0a2e62021-01-08 00:51:49 +08002917 class DnsResolverUnsolicitedEventCallback extends
2918 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002919 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002920 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002921 try {
2922 mHandler.sendMessage(mHandler.obtainMessage(
2923 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002924 new PrivateDnsValidationUpdate(event.netId,
2925 InetAddresses.parseNumericAddress(event.ipAddress),
2926 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002927 } catch (IllegalArgumentException e) {
2928 loge("Error parsing ip address in validation event");
2929 }
2930 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002931
2932 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002933 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2934 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002935 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2936 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2937 // event callback for certain nai. e.g. cellular. Register here to pass to
2938 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002939 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002940 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2941 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002942 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002943 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002944 }
2945 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002946
2947 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002948 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2949 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2950 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002951 }
dalyk1720e542018-03-05 12:42:22 -05002952
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002953 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002954 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002955 return this.VERSION;
2956 }
2957
2958 @Override
2959 public String getInterfaceHash() {
2960 return this.HASH;
2961 }
paulhu7c0a2e62021-01-08 00:51:49 +08002962 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002963
2964 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002965 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2966 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002967
paulhu7c0a2e62021-01-08 00:51:49 +08002968 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002969 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002970 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002971 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002972 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002973 }
2974 }
2975
Sudheer Shanka9967d462021-03-18 19:09:25 +00002976 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002977 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002978 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002979 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2980 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002981 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002982 };
2983
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002984 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002985 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002986 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002987 }
2988
Mark Fasheh7c999d82023-05-04 20:23:11 +00002989 static final class UidFrozenStateChangedArgs {
2990 final int[] mUids;
2991 final int[] mFrozenStates;
2992
2993 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
2994 mUids = uids;
2995 mFrozenStates = frozenStates;
2996 }
2997 }
2998
Motomu Utsumi188bfd32023-05-30 14:38:04 +09002999 /**
3000 * Check if the cell network is idle.
3001 * @return true if the cell network state is idle
3002 * false if the cell network state is active or unknown
3003 */
3004 private boolean isCellNetworkIdle() {
3005 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3006 if (defaultNai == null
3007 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3008 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3009 // cell network is not the default network, cell network state is unknown.
3010 // TODO(b/279380356): Track cell network state when the cell is not the default network
3011 return false;
3012 }
3013
3014 return !mNetworkActivityTracker.isDefaultNetworkActive();
3015 }
3016
Mark Fasheh7c999d82023-05-04 20:23:11 +00003017 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003018 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003019
3020 for (int i = 0; i < uids.length; i++) {
3021 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003022 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003023 } else {
3024 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003025 }
3026 }
3027
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003028 if (ownerUids.isEmpty()) {
3029 return;
3030 }
3031
3032 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3033 // Delay closing sockets to avoid waking the cell modem up.
3034 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3035 // than waking cell modem up.
3036 mPendingFrozenUids.addAll(ownerUids);
3037 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003038 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003039 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003040 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003041 loge("Exception in socket destroy: " + e);
3042 }
3043 }
3044 }
3045
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003046 private void closePendingFrozenSockets() {
3047 ensureRunningOnConnectivityServiceThread();
3048
3049 try {
3050 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3051 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3052 loge("Failed to close pending frozen app sockets: " + e);
3053 }
3054 mPendingFrozenUids.clear();
3055 }
3056
3057 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3058 mNetworkActivityTracker.handleReportNetworkActivity(params);
3059
3060 if (mDelayDestroyFrozenSockets
3061 && params.isActive
3062 && params.label == TRANSPORT_CELLULAR
3063 && !mPendingFrozenUids.isEmpty()) {
3064 closePendingFrozenSockets();
3065 }
3066 }
3067
3068 /**
3069 * If the cellular network is no longer the default network, close pending frozen sockets.
3070 *
3071 * @param newNetwork new default network
3072 * @param oldNetwork old default network
3073 */
3074 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3075 NetworkAgentInfo oldNetwork) {
3076 final boolean isOldNetworkCellular = oldNetwork != null
3077 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3078 final boolean isNewNetworkCellular = newNetwork != null
3079 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3080
3081 if (isOldNetworkCellular
3082 && !isNewNetworkCellular
3083 && !mPendingFrozenUids.isEmpty()) {
3084 closePendingFrozenSockets();
3085 }
3086 }
3087
3088 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3089 pw.println("CloseFrozenAppSockets:");
3090 pw.increaseIndent();
3091 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3092 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3093 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3094 pw.decreaseIndent();
3095 }
3096
Mark Fasheh7c999d82023-05-04 20:23:11 +00003097 @VisibleForTesting
3098 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003099 @VisibleForTesting
3100 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3101 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003102
Paul Jensen83f5d572014-08-29 09:54:01 -04003103 private void enforceInternetPermission() {
3104 mContext.enforceCallingOrSelfPermission(
3105 android.Manifest.permission.INTERNET,
3106 "ConnectivityService");
3107 }
3108
The Android Open Source Project28527d22009-03-03 19:31:44 -08003109 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003110 mContext.enforceCallingOrSelfPermission(
3111 android.Manifest.permission.ACCESS_NETWORK_STATE,
3112 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003113 }
3114
lucaslinc582d502022-01-27 09:07:00 +08003115 private boolean checkAccessPermission(int pid, int uid) {
3116 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3117 == PERMISSION_GRANTED;
3118 }
3119
paulhua6ee2122021-02-22 15:40:43 +08003120 /**
3121 * Performs a strict and comprehensive check of whether a calling package is allowed to
3122 * change the state of network, as the condition differs for pre-M, M+, and
3123 * privileged/preinstalled apps. The caller is expected to have either the
3124 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3125 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3126 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3127 * permission and cannot be revoked. See http://b/23597341
3128 *
3129 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3130 * of this app will be updated to the current time.
3131 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003132 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003133 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3134 == PackageManager.PERMISSION_GRANTED) {
3135 return;
3136 }
3137
3138 if (callingPkg == null) {
3139 throw new SecurityException("Calling package name is null.");
3140 }
3141
3142 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3143 final int uid = mDeps.getCallingUid();
3144 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3145 callingPkg, callingAttributionTag, null /* message */);
3146
3147 if (mode == AppOpsManager.MODE_ALLOWED) {
3148 return;
3149 }
3150
3151 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3152 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3153 return;
3154 }
3155
3156 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3157 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3158 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003159 }
3160
Charles He9369e612017-05-15 17:07:18 +01003161 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003162 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003163 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003164 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003165 }
3166
Quang Luong98858d62023-02-11 00:25:24 +00003167 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003168 enforceAnyPermissionOf(mContext,
3169 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003170 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003171 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3172 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3173 }
3174
paulhu8e96a752019-08-12 16:25:11 +08003175 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003176 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003177 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003178 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003179 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003180 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003181 }
3182
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003183 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003184 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003185 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003186 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003187 android.Manifest.permission.NETWORK_SETTINGS,
3188 android.Manifest.permission.NETWORK_FACTORY,
3189 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3190 }
3191
3192 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003193 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003194 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003195 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003196 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3197 android.Manifest.permission.NETWORK_FACTORY,
3198 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3199 }
3200
lucaslin69e1aa92022-03-22 18:15:09 +08003201 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3202 return PERMISSION_GRANTED == mContext.checkPermission(
3203 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3204 || PERMISSION_GRANTED == mContext.checkPermission(
3205 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3206 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003207 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003208 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003209 }
3210
Chalard Jean9a396cc2018-02-21 18:43:54 +09003211 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003212 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003213 android.Manifest.permission.NETWORK_SETTINGS,
3214 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003215 }
3216
3217 private boolean checkSettingsPermission(int pid, int uid) {
3218 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003219 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3220 || PERMISSION_GRANTED == mContext.checkPermission(
3221 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003222 }
3223
paulhu8e96a752019-08-12 16:25:11 +08003224 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003225 enforceNetworkStackPermissionOr(mContext,
3226 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003227 }
3228
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003229 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003230 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003231 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003232 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003233 }
3234
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003235 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003236 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003237 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3238 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003239 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003240 }
3241
James Mattis8378aec2021-01-26 14:05:36 -08003242 private void enforceOemNetworkPreferencesPermission() {
3243 mContext.enforceCallingOrSelfPermission(
3244 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3245 "ConnectivityService");
3246 }
3247
James Mattisfa270db2021-05-31 17:11:10 -07003248 private void enforceManageTestNetworksPermission() {
3249 mContext.enforceCallingOrSelfPermission(
3250 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3251 "ConnectivityService");
3252 }
3253
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003254 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003255 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003256 android.Manifest.permission.NETWORK_STACK,
3257 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003258 }
3259
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003260 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003261 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003262 android.Manifest.permission.NETWORK_STACK,
3263 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3264 }
3265
paulhu1a407652019-03-22 16:35:06 +08003266 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003267 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003268 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003269 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3270 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003271 }
3272
Paul Hu8fc2a552022-05-04 18:44:42 +08003273 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3274 boolean checkUidsAllowedList) {
3275 if (PermissionUtils.checkAnyPermissionOf(mContext,
3276 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3277 return true;
3278 }
3279
3280 // fallback to ConnectivityInternalPermission
3281 // TODO: Remove this fallback check after all apps have declared
3282 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3283 if (PermissionUtils.checkAnyPermissionOf(mContext,
3284 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3285 return true;
3286 }
3287
3288 // Check whether uid is in allowed on restricted networks list.
3289 if (checkUidsAllowedList
3290 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3291 return true;
3292 }
3293 return false;
3294 }
3295
3296 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3297 final int callingUid = mDeps.getCallingUid();
3298 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3299 throw new SecurityException("ConnectivityService: user " + callingUid
3300 + " has no permission to access restricted network.");
3301 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003302 }
3303
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003304 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003305 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003306 }
3307
Roshan Pius98f59ec2021-02-23 08:47:39 -08003308 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3309 return PERMISSION_GRANTED == mContext.checkPermission(
3310 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3311 }
3312
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003313 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003314 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003315 }
3316
3317 private void sendInetConditionBroadcast(NetworkInfo info) {
3318 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3319 }
3320
Wink Saville4f0de1e2011-08-04 15:01:58 -07003321 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003322 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003323 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003324 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003325 if (info.isFailover()) {
3326 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3327 info.setFailover(false);
3328 }
3329 if (info.getReason() != null) {
3330 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3331 }
3332 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003333 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3334 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003335 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003336 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003337 return intent;
3338 }
3339
3340 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3341 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3342 }
3343
Michael Groover73f69482023-01-27 11:01:25 -06003344 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3345 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003346 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3347 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003348 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003349 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003350 if (!mSystemReady
3351 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003352 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003353 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003354 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003355 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003356 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003357 }
3358
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003359 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003360 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003361 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003362 final NetworkInfo ni = intent.getParcelableExtra(
3363 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003364 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3365 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003366 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003367 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003368 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003369 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003370 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003371 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003372 } finally {
3373 Binder.restoreCallingIdentity(ident);
3374 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003375 }
3376 }
3377
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003378 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3379 NetworkInfo info) {
3380 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003381 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003382
3383 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3384 try {
3385 // This allows us to discard older broadcasts still waiting to be delivered
3386 // which have the same namespace and key.
3387 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3388 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3389 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003390 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003391 } catch (UnsupportedApiLevelException e) {
3392 Log.wtf(TAG, "Using unsupported API" + e);
3393 }
3394 }
3395
3396 @VisibleForTesting
3397 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3398 final StringBuilder sb = new StringBuilder();
3399 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3400 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3401 sb.append(info.getExtraInfo());
3402 return sb.toString();
3403 }
3404
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003405 /**
Aaron Huang96011892020-06-27 07:18:23 +08003406 * Called by SystemServer through ConnectivityManager when the system is ready.
3407 */
3408 @Override
3409 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003410 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003411 throw new SecurityException("Calling Uid is not system uid.");
3412 }
3413 systemReadyInternal();
3414 }
3415
3416 /**
3417 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003418 */
3419 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003420 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003421 // Load flags after PackageManager is ready to query module version
3422 mFlags.loadFlags(mDeps, mContext);
3423
Aaron Huang9a57acf2020-12-08 10:03:29 +08003424 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3425 // listening network request which is sent by MultipathPolicyTracker won't be added
3426 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3427 // be called after PermissionMonitor#startMonitoring().
3428 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3429 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3430 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003431 final ConditionVariable startMonitoringDone = new ConditionVariable();
3432 mHandler.post(() -> {
3433 mPermissionMonitor.startMonitoring();
3434 startMonitoringDone.open();
3435 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003436 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003437 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003438
Hugo Benichie5220992017-04-26 14:53:28 +09003439 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003440 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003441 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003442 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003443 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003444 }
3445 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003446
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003447 // Create network requests for always-on networks.
3448 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003449
3450 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003451 // Note that updating can be skipped here if the list is empty only because no uid
3452 // rules are applied before system ready. Normally, the empty uid list means to clear
3453 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003454 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3455 updateMobileDataPreferredUids();
3456 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003457
3458 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003459 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003460 mBpfNetMaps.setPullAtomCallback(mContext);
3461 }
Paul Hu3c8c8102022-08-25 07:06:16 +00003462 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3463 // have permission problem. While CV#block() is unbounded in time and can in principle block
3464 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3465 // could have blocked forever too.
3466 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003467 }
3468
The Android Open Source Project28527d22009-03-03 19:31:44 -08003469 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003470 * Start listening for default data network activity state changes.
3471 */
3472 @Override
3473 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003474 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003475 }
3476
3477 /**
3478 * Stop listening for default data network activity state changes.
3479 */
3480 @Override
3481 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003482 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003483 }
3484
3485 /**
3486 * Check whether the default network radio is currently active.
3487 */
3488 @Override
3489 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003490 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003491 }
3492
3493 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003494 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003495 * and set it on it's iface.
3496 */
Junyu Lai970963e2022-10-25 15:46:47 +08003497 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003498 final String iface = newLp.getInterfaceName();
3499 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003500 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003501 // Silently ignore unset MTU value.
3502 return;
3503 }
Hansen Kurli04252032022-12-07 11:21:49 +00003504 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3505 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3506 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003507 return;
3508 }
Hansen Kurli04252032022-12-07 11:21:49 +00003509 // Cannot set MTU without interface name
3510 if (TextUtils.isEmpty(iface)) {
3511 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003512 return;
3513 }
sy.yun4aa73922013-09-02 05:24:09 +09003514
Hansen Kurli04252032022-12-07 11:21:49 +00003515 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3516 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003517 return;
3518 }
3519
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003520 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003521 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003522 mNetd.interfaceSetMtu(iface, mtu);
3523 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003524 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003525 }
3526 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003527
Chenbo Feng15416292018-11-08 17:36:21 -08003528 @VisibleForTesting
3529 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003530
Junyu Lai970963e2022-10-25 15:46:47 +08003531 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003532 String[] values = null;
3533 if (tcpBufferSizes != null) {
3534 values = tcpBufferSizes.split(",");
3535 }
3536
3537 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003538 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003539 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3540 values = tcpBufferSizes.split(",");
3541 }
3542
3543 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3544
3545 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003546 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003547
Chenbo Feng15416292018-11-08 17:36:21 -08003548 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3549 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3550 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003551 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003552 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003553 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003554 }
3555 }
3556
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003557 @Override
3558 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003559 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003560 NETWORK_RESTORE_DELAY_PROP_NAME);
3561 if(restoreDefaultNetworkDelayStr != null &&
3562 restoreDefaultNetworkDelayStr.length() != 0) {
3563 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003564 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003565 } catch (NumberFormatException e) {
3566 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003567 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003568 // if the system property isn't set, use the value for the apn type
3569 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3570
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003571 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3572 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003573 }
3574 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003575 }
3576
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003577 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003578 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003579 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003580 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003581 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003582 // Start gathering diagnostic information.
3583 netDiags.add(new NetworkDiagnostics(
3584 nai.network,
3585 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003586 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003587 DIAG_TIME_MS));
3588 }
3589
3590 for (NetworkDiagnostics netDiag : netDiags) {
3591 pw.println();
3592 netDiag.waitForMeasurements();
3593 netDiag.dump(pw);
3594 }
3595 }
3596
The Android Open Source Project28527d22009-03-03 19:31:44 -08003597 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003598 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3599 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003600 if (!checkDumpPermission(mContext, TAG, writer)) return;
3601
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003602 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003603 }
3604
lucaslin99473f62020-12-10 15:10:54 +08003605 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3606 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3607 != PackageManager.PERMISSION_GRANTED) {
3608 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003609 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003610 + " due to missing android.permission.DUMP permission");
3611 return false;
3612 } else {
3613 return true;
3614 }
3615 }
3616
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003617 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003618 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003619
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003620 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003621 dumpNetworkDiagnostics(pw);
3622 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003623 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003624 dumpNetworks(pw);
3625 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003626 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003627 dumpNetworkRequests(pw);
3628 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003629 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3630 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3631 dumpTrafficController(pw, fd, verbose);
3632 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003633 }
Erik Kline9647f382015-06-05 17:47:34 +09003634
Junyu Lai0da479b2022-04-20 15:06:29 +08003635 pw.println("NetworkProviders for:");
3636 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003637 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003638 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003639 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003640 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003641 pw.println();
3642
Chalard Jean5b409c72021-02-04 13:12:59 +09003643 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003644 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003645 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003646 pw.println("none");
3647 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003648 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003649 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003650 pw.println();
3651
James Mattis8b298a02021-06-01 22:34:04 -07003652 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003653 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003654 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003655 pw.decreaseIndent();
3656 pw.println();
3657
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003658 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003659 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003660 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003661 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003662 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003663
junyulaif2c67e42018-08-07 19:50:45 +08003664 pw.println("Status for known UIDs:");
3665 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003666 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003667 for (int i = 0; i < size; i++) {
3668 // Don't crash if the array is modified while dumping in bugreports.
3669 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003670 final int uid = mUidBlockedReasons.keyAt(i);
3671 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3672 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003673 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003674 } catch (ArrayIndexOutOfBoundsException e) {
3675 pw.println(" ArrayIndexOutOfBoundsException");
3676 } catch (ConcurrentModificationException e) {
3677 pw.println(" ConcurrentModificationException");
3678 }
3679 }
3680 pw.println();
3681 pw.decreaseIndent();
3682
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003683 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003684 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003685 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003686 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003687 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003688
Junyu Lai0da479b2022-04-20 15:06:29 +08003689 pw.println("Network Offers:");
3690 pw.increaseIndent();
3691 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3692 pw.println(offerInfo.offer);
3693 }
3694 pw.decreaseIndent();
3695 pw.println();
3696
Robert Greenwalt94e22142014-07-30 16:31:24 -07003697 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003698
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003699 pw.println();
markchien5e866652019-09-30 14:40:57 +08003700 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003701
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003702 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003703 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003704
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003705 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003706 dumpCloseFrozenAppSockets(pw);
3707
3708 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003709
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003710 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003711 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003712 pw.println("mNetworkRequestInfoLogs (most recent first):");
3713 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003714 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003715 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003716
3717 pw.println();
3718 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3719 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003720 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003721 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003722
3723 pw.println();
3724 pw.println("NetTransition WakeLock activity (most recent first):");
3725 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003726 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3727 pw.println("total releases: " + mTotalWakelockReleases);
3728 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3729 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3730 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3731 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3732 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3733 }
James Mattiscb1e0362021-04-06 17:07:42 -07003734 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003735
3736 pw.println();
3737 pw.println("bandwidth update requests (by uid):");
3738 pw.increaseIndent();
3739 synchronized (mBandwidthRequests) {
3740 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3741 pw.println("[" + mBandwidthRequests.keyAt(i)
3742 + "]: " + mBandwidthRequests.valueAt(i));
3743 }
3744 }
3745 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003746 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003747
James Mattiscb1e0362021-04-06 17:07:42 -07003748 pw.println();
3749 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3750 pw.increaseIndent();
3751 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003752 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003753 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003754
3755 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003756
3757 pw.println();
3758 pw.println("Permission Monitor:");
3759 pw.increaseIndent();
3760 mPermissionMonitor.dump(pw);
3761 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003762
3763 pw.println();
3764 pw.println("Legacy network activity:");
3765 pw.increaseIndent();
3766 mNetworkActivityTracker.dump(pw);
3767 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003768 }
3769
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003770 private void dumpNetworks(IndentingPrintWriter pw) {
3771 for (NetworkAgentInfo nai : networksSortedById()) {
3772 pw.println(nai.toString());
3773 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003774 pw.println("Nat464Xlat:");
3775 pw.increaseIndent();
3776 nai.dumpNat464Xlat(pw);
3777 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003778 pw.println(String.format(
3779 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3780 nai.numForegroundNetworkRequests(),
3781 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3782 nai.numBackgroundNetworkRequests(),
3783 nai.numNetworkRequests()));
3784 pw.increaseIndent();
3785 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3786 pw.println(nai.requestAt(i).toString());
3787 }
3788 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003789 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003790 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003791 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003792 pw.decreaseIndent();
3793 pw.decreaseIndent();
3794 }
3795 }
3796
James Mattis8b298a02021-06-01 22:34:04 -07003797 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3798 if (!mProfileNetworkPreferences.isEmpty()) {
3799 pw.println("Profile preferences:");
3800 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09003801 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07003802 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003803 }
James Mattis8b298a02021-06-01 22:34:04 -07003804 if (!mOemNetworkPreferences.isEmpty()) {
3805 pw.println("OEM preferences:");
3806 pw.increaseIndent();
3807 pw.println(mOemNetworkPreferences);
3808 pw.decreaseIndent();
3809 }
3810 if (!mMobileDataPreferredUids.isEmpty()) {
3811 pw.println("Mobile data preferred UIDs:");
3812 pw.increaseIndent();
3813 pw.println(mMobileDataPreferredUids);
3814 pw.decreaseIndent();
3815 }
James Mattis45d81842021-01-10 14:24:24 -08003816
James Mattis8b298a02021-06-01 22:34:04 -07003817 pw.println("Default requests:");
3818 pw.increaseIndent();
3819 dumpPerAppDefaultRequests(pw);
3820 pw.decreaseIndent();
3821 }
3822
3823 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003824 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3825 if (mDefaultRequest == defaultRequest) {
3826 continue;
3827 }
3828
James Mattis8b298a02021-06-01 22:34:04 -07003829 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3830 final String networkOutput;
3831 if (null == satisfier) {
3832 networkOutput = "null";
3833 } else if (mNoServiceNetwork.equals(satisfier)) {
3834 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003835 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003836 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003837 }
James Mattis8b298a02021-06-01 22:34:04 -07003838 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3839 ? "" : " asUid: " + defaultRequest.mAsUid;
3840 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3841 + defaultRequest.mPid + asUidString + "]";
3842 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3843 + " Preference order: " + defaultRequest.mPreferenceOrder
3844 + " Tracked UIDs: " + defaultRequest.getUids();
3845 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003846 }
3847 }
3848
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003849 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003850 NetworkRequestInfo[] infos = null;
3851 while (infos == null) {
3852 try {
3853 infos = requestsSortedById();
3854 } catch (ConcurrentModificationException e) {
3855 // mNetworkRequests should only be accessed from handler thread, except dump().
3856 // As dump() is never called in normal usage, it would be needlessly expensive
3857 // to lock the collection only for its benefit. Instead, retry getting the
3858 // requests if ConcurrentModificationException is thrown during dump().
3859 }
3860 }
3861 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003862 pw.println(nri.toString());
3863 }
3864 }
3865
Ken Chene6d511f2022-01-25 11:10:42 +08003866 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
3867 boolean verbose) {
3868 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09003869 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08003870 } catch (ServiceSpecificException e) {
3871 pw.println(e.getMessage());
3872 } catch (IOException e) {
3873 loge("Dump BPF maps failed, " + e);
3874 }
3875 }
3876
Chalard Jean524f0b12021-10-25 21:11:56 +09003877 private void dumpAllRequestInfoLogsToLogcat() {
3878 try (PrintWriter logPw = new PrintWriter(new Writer() {
3879 @Override
3880 public void write(final char[] cbuf, final int off, final int len) {
3881 // This method is called with 0-length and 1-length arrays for empty strings
3882 // or strings containing only the DEL character.
3883 if (len <= 1) return;
3884 Log.e(TAG, new String(cbuf, off, len));
3885 }
3886 @Override public void flush() {}
3887 @Override public void close() {}
3888 })) {
3889 mNetworkRequestInfoLogs.dump(logPw);
3890 }
3891 }
3892
Hugo Benichia480ba52018-09-03 08:19:02 +09003893 /**
3894 * Return an array of all current NetworkAgentInfos sorted by network id.
3895 */
3896 private NetworkAgentInfo[] networksSortedById() {
3897 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003898 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003899 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003900 return networks;
3901 }
3902
3903 /**
3904 * Return an array of all current NetworkRequest sorted by request id.
3905 */
James Mattis258ea3c2020-11-15 15:04:40 -08003906 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003907 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003908 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003909 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003910 // Sort the array based off the NRI containing the min requestId in its requests.
3911 Arrays.sort(requests,
3912 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3913 Comparator.comparingInt(req -> req.requestId)).requestId
3914 )
3915 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003916 return requests;
3917 }
3918
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003919 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003920 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003921 if (officialNai != null && officialNai.equals(nai)) return true;
3922 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003923 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003924 " - " + nai);
3925 }
3926 return false;
3927 }
3928
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003929 private boolean isDisconnectRequest(Message msg) {
3930 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
3931 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
3932 return info.getState() == NetworkInfo.State.DISCONNECTED;
3933 }
3934
Robert Greenwalt2034b912009-08-12 16:08:25 -07003935 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003936 private class NetworkStateTrackerHandler extends Handler {
3937 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003938 super(looper);
3939 }
3940
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003941 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003942 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3943 final NetworkAgentInfo nai = arg.first;
3944 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003945 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003946 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003947 }
3948 return;
3949 }
3950
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003951 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003952 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003953 return;
3954 }
3955
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003956 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003957 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09003958 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
3959 final NetworkCapabilities sanitized =
3960 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09003961 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003962 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003963 break;
3964 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003965 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003966 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003967 processLinkPropertiesFromAgent(nai, newLp);
3968 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003969 break;
3970 }
3971 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003972 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003973 updateNetworkInfo(nai, info);
3974 break;
3975 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003976 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003977 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003978 break;
3979 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003980 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09003981 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003982 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003983 // Note that if the NAI had been connected, this would affect the
3984 // score, and therefore would require re-mixing the score and performing
3985 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003986 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003987 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3988 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003989 // Mark the network as temporarily accepting partial connectivity so that it
3990 // will be validated (and possibly become default) even if it only provides
3991 // partial internet access. Note that if user connects to partial connectivity
3992 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3993 // out of wifi coverage) and if the same wifi is available again, the device
3994 // will auto connect to this wifi even though the wifi has "no internet".
3995 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003996 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003997 break;
3998 }
junyulai011b1f12019-01-03 18:50:15 +08003999 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004000 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004001 break;
4002 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004003 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004004 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004005 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004006
4007 if (isLegacyLockdownNai(nai)
4008 && (underlying == null || underlying.size() != 1)) {
4009 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4010 + " must have exactly one underlying network: " + underlying);
4011 }
4012
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004013 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4014 nai.declaredUnderlyingNetworks = (underlying != null)
4015 ? underlying.toArray(new Network[0]) : null;
4016
4017 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4018 if (DBG) {
4019 log(nai.toShortString() + " changed underlying networks to "
4020 + Arrays.toString(nai.declaredUnderlyingNetworks));
4021 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004022 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004023 notifyIfacesChangedForNetworkStats();
4024 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004025 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004026 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004027 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4028 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4029 nai.teardownDelayMs = msg.arg1;
4030 } else {
4031 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4032 }
Chalard Jean550b5212021-03-05 23:07:53 +09004033 break;
4034 }
4035 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4036 nai.setLingerDuration((int) arg.second);
4037 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004038 }
Tyler Wear72388212021-09-09 14:49:02 -07004039 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4040 DscpPolicy policy = (DscpPolicy) arg.second;
4041 if (mDscpPolicyTracker != null) {
4042 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4043 }
4044 break;
4045 }
4046 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4047 if (mDscpPolicyTracker != null) {
4048 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4049 }
4050 break;
4051 }
4052 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4053 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004054 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004055 }
4056 break;
4057 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004058 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004059 if (!nai.everConnected()) {
4060 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4061 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004062 teardownUnneededNetwork(nai);
4063 break;
4064 }
4065
4066 if (nai.isDestroyed()) {
4067 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4068 + ", ignoring");
4069 break;
4070 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004071
4072 final int timeoutMs = (int) arg.second;
4073 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4074 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4075 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4076 }
4077
4078 // Marking a network awaiting replacement is used to ensure that any requests
4079 // satisfied by the network do not switch to another network until a
4080 // replacement is available or the wait for a replacement times out.
4081 // If the network is inactive (i.e., nascent or lingering), then there are no
4082 // such requests, and there is no point keeping it. Just tear it down.
4083 // Note that setLingerDuration(0) cannot be used to do this because the network
4084 // could be nascent.
4085 nai.clearInactivityState();
4086 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4087 Log.d(TAG, nai.toShortString()
4088 + " marked awaiting replacement is unneeded, tearing down instead");
4089 teardownUnneededNetwork(nai);
4090 break;
4091 }
4092
4093 Log.d(TAG, "Marking " + nai.toShortString()
4094 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4095 destroyNativeNetwork(nai);
4096
4097 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4098 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4099 // consider the fact that the network could already have disconnected or been
4100 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4101 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4102 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4103 mKeepaliveTracker.handleStopAllKeepalives(nai,
4104 SocketKeepalive.ERROR_INVALID_NETWORK);
4105
4106 nai.updateScoreForNetworkAgentUpdate();
4107 // This rematch is almost certainly not going to result in any changes, because
4108 // the destroyed flag is only just above the "current satisfier wins"
4109 // tie-breaker. But technically anything that affects scoring should rematch.
4110 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004111 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004112 break;
4113 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004114 }
4115 }
4116
4117 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004118 final int netId = msg.arg2;
4119 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004120 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004121 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004122 switch (msg.what) {
4123 default:
4124 return false;
lucasline117e2e2019-10-22 18:27:33 +08004125 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004126 if (nai == null) {
4127 break;
4128 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004129 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4130 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004131 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004132 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004133 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004134 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004135 if (probePrivateDnsCompleted) {
4136 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4137 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004138 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004139 }
4140 // Only show the notification when the private DNS is broken and the
4141 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004142 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004143 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4144 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004145 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004146 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4147 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4148 // private DNS is broken, it means this network is being reevaluated.
4149 // Either probing private DNS is not necessary any more or it hasn't been
4150 // done yet. In either case, the networkCapabilities should be updated to
4151 // reflect the new status.
4152 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004153 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004154 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004155 }
4156 break;
4157 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004158 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004159 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4160
Erik Kline31b4a9e2018-01-11 21:07:29 +09004161 if (nai == null) break;
4162
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004163 handleNetworkTested(nai, results.mTestResult,
4164 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004165 break;
4166 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004167 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004168 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004169 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004170 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004171 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004172 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004173 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4174 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004175 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004176 if (nai == null) {
4177 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4178 break;
4179 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004180 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004181 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004182 (PendingIntent) msg.obj,
4183 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004184 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004185 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004186 break;
4187 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004188 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004189 if (nai == null) break;
4190
Erik Kline9a62f012018-03-21 07:18:33 -07004191 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004192 break;
4193 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004194 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004195 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004196 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004197 break;
4198 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004199 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004200 return true;
4201 }
4202
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004203 private void handleNetworkTested(
4204 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004205 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4206 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004207 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004208
4209 // If there is any kind of working networking, then the NAI has been evaluated
4210 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4211 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004212 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004213 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004214 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4215 // any callback that receives onAvailable for that rematch receives an extra caps
4216 // callback. To prevent that, update the score in the agent so the updates below won't
4217 // see an update to both caps and score at the same time.
4218 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004219 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4220
he_won.hwang881307a2022-03-15 21:23:52 +09004221 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4222 // Assume the validation failure is due to a temporary failure after roaming
4223 // and ignore it. NetworkMonitor will continue to retry validation. If it
4224 // continues to fail after the block timeout expires, the network will be
4225 // marked unvalidated. If it succeeds, then validation state will not change.
4226 return;
4227 }
4228
Chalard Jean254bd162022-08-25 13:04:51 +09004229 final boolean wasValidated = nai.isValidated();
4230 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004231 final boolean wasPortal = nai.captivePortalDetected();
4232 nai.setPartialConnectivity(partial);
4233 nai.setCaptivePortalDetected(portal);
4234 nai.updateScoreForNetworkAgentUpdate();
4235 final boolean partialConnectivityChanged = (wasPartial != partial);
4236 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004237
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004238 if (DBG) {
4239 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4240 ? " with redirect to " + redirectUrl
4241 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004242 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004243 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004244 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004245 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004246 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004247 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004248 if (valid) {
4249 handleFreshlyValidatedNetwork(nai);
4250 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4251 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004252 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004253 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004254 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004255 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004256 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004257 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004258 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004259 NotificationType.PRIVATE_DNS_BROKEN);
4260 // If network becomes valid, the hasShownBroken should be reset for
4261 // that network so that the notification will be fired when the private
4262 // DNS is broken again.
4263 nai.networkAgentConfig.hasShownBroken = false;
4264 }
4265 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004266 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004267 } else if (portalChanged) {
4268 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
4269 == getCaptivePortalMode()) {
4270 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4271 nai.onPreventAutomaticReconnect();
4272 teardownUnneededNetwork(nai);
4273 return;
4274 } else {
4275 updateCapabilitiesForNetwork(nai);
4276 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004277 } else if (becameEvaluated) {
4278 // If valid or partial connectivity changed, updateCapabilities* has
4279 // done the rematch.
4280 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004281 }
4282 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004283
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004284 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004285 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004286 nai.onValidationStatusChanged(
4287 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4288 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004289
4290 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004291 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004292 // immediately. Re-notify partial connectivity silently if no internet
4293 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004294 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004295 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004296 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4297 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004298 }
4299
Chalard Jean254bd162022-08-25 13:04:51 +09004300 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004301 handleNetworkUnvalidated(nai);
4302 }
4303 }
4304
Calvin Ondada1452016-10-11 15:10:46 -07004305 private int getCaptivePortalMode() {
4306 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004307 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4308 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004309 }
4310
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004311 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4312 switch (msg.what) {
4313 default:
4314 return false;
4315 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4316 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4317 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4318 handleLingerComplete(nai);
4319 }
4320 break;
4321 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004322 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4323 handleNetworkAgentRegistered(msg);
4324 break;
4325 }
4326 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4327 handleNetworkAgentDisconnected(msg);
4328 break;
4329 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004330 }
4331 return true;
4332 }
4333
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004334 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004335 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004336 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004337 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004338 maybeHandleNetworkAgentMessage(msg);
4339 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004340 }
4341 }
4342
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004343 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004344 private final int mNetId;
4345 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004346
4347 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004348 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004349 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004350 }
4351
4352 @Override
4353 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4354 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004355 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004356 }
4357
4358 @Override
4359 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004360 // Legacy version of notifyNetworkTestedWithExtras.
4361 // Would only be called if the system has a NetworkStack module older than the
4362 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004363 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004364 }
4365
4366 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004367 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004368 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4369 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004370 final Message msg = mTrackerHandler.obtainMessage(
4371 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004372 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004373 new NetworkTestedResults(
4374 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004375 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004376
4377 // Invoke ConnectivityReport generation for this Network test event.
4378 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4379 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004380
Cody Kestingf1120be2020-08-03 18:01:40 -07004381 // NetworkMonitor reports the network validation result as a bitmask while
4382 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4383 // logical value for ConnectivityDiagnostics.
4384 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4385 p.result);
4386
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004387 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004388 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004389 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4390 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4391
Aaron Huang959d3642021-01-21 15:47:41 +08004392 ConnectivityReportEvent reportEvent =
4393 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4394 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004395 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004396 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004397 }
4398
4399 @Override
4400 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4401 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4402 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004403 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004404 }
4405
4406 @Override
lucasline117e2e2019-10-22 18:27:33 +08004407 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4408 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4409 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004410 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004411 }
4412
4413 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004414 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4415 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4416 EVENT_CAPPORT_DATA_CHANGED,
4417 0, mNetId, data));
4418 }
4419
4420 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004421 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004422 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004423 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004424
4425 final PendingIntent pendingIntent;
4426 // Only the system server can register notifications with package "android"
4427 final long token = Binder.clearCallingIdentity();
4428 try {
paulhu7746e4e2020-06-09 19:07:03 +08004429 pendingIntent = PendingIntent.getBroadcast(
4430 mContext,
4431 0 /* requestCode */,
4432 intent,
4433 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004434 } finally {
4435 Binder.restoreCallingIdentity(token);
4436 }
4437 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4438 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004439 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004440 }
4441
4442 @Override
4443 public void hideProvisioningNotification() {
4444 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004445 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004446 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004447
4448 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004449 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004450 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004451 }
4452
4453 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004454 public int getInterfaceVersion() {
4455 return this.VERSION;
4456 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004457
4458 @Override
4459 public String getInterfaceHash() {
4460 return this.HASH;
4461 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004462 }
4463
Cody Kestingf1120be2020-08-03 18:01:40 -07004464 /**
4465 * Converts the given NetworkMonitor-specific validation result bitmask to a
4466 * ConnectivityDiagnostics-specific validation result int.
4467 */
4468 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4469 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4470 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4471 }
4472 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4473 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4474 }
4475 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4476 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4477 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4478 }
4479
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004480 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004481 log("Data stall detected with methods: " + p.detectionMethod);
4482
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004483 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004484 int detectionMethod = 0;
4485 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4486 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4487 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4488 }
4489 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4490 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4491 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4492 p.tcpMetricsCollectionPeriodMillis);
4493 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004494 }
4495
Cody Kestingf53a0752020-04-15 12:33:28 -07004496 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004497 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004498 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004499
4500 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4501 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4502 // the cost of going through two handlers.
4503 mConnectivityDiagnosticsHandler.sendMessage(msg);
4504 }
4505
Cody Kestingb37958e2020-05-15 10:36:01 -07004506 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4507 return (p.detectionMethod & detectionMethod) != 0;
4508 }
4509
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004510 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4511 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004512 }
4513
Erik Klinea73af002018-06-26 18:53:43 +09004514 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4515 if (nai == null) return;
4516 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4517 // in order to restart a validation pass from within netd.
4518 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4519 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004520 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004521 }
4522 }
4523
Erik Kline31b4a9e2018-01-11 21:07:29 +09004524 private void handlePrivateDnsSettingsChanged() {
4525 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4526
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004527 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004528 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004529 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004530 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4531 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004532 }
4533 }
4534
Erik Kline9a62f012018-03-21 07:18:33 -07004535 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4536 // Private DNS only ever applies to networks that might provide
4537 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004538 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004539
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004540 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004541 // schedule DNS resolutions. If a DNS resolution is required the
4542 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004543 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004544
4545 // With Private DNS bypass support, we can proceed to update the
4546 // Private DNS config immediately, even if we're in strict mode
4547 // and have not yet resolved the provider name into a set of IPs.
4548 updatePrivateDns(nai, cfg);
4549 }
4550
4551 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4552 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004553 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004554 }
4555
dalyk1720e542018-03-05 12:42:22 -05004556 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4557 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4558 if (nai == null) {
4559 return;
4560 }
4561 mDnsManager.updatePrivateDnsValidation(update);
4562 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4563 }
4564
paulhu7c0a2e62021-01-08 00:51:49 +08004565 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004566 int prefixLength) {
4567 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4568 if (nai == null) return;
4569
paulhu7c0a2e62021-01-08 00:51:49 +08004570 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4571 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004572
4573 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004574 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004575 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004576 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004577 prefixLength);
4578 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004579 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004580 return;
4581 }
4582 }
4583
Lorenzo Colittid523d142020-04-01 20:16:30 +09004584 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004585 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4586 }
4587
Hai Shalome58bdc62021-01-11 18:45:34 -08004588 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004589 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004590 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004591 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4592 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4593 }
4594
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004595 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004596 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004597 * @param nai the agent info to update
4598 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004599 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004600 */
junyulai2b6f0c22021-02-03 20:15:30 +08004601 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4602 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4603 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004604 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004605 // one lingered request, set inactive.
4606 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004607 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004608 if (DBG) log("Unsetting inactive " + nai.toShortString());
4609 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004610 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004611 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004612 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004613 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4614 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004615 }
junyulai2b6f0c22021-02-03 20:15:30 +08004616 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004617 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004618 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004619 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004620 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004621 }
4622
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004623 private void handleNetworkAgentRegistered(Message msg) {
4624 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4625 if (!mNetworkAgentInfos.contains(nai)) {
4626 return;
4627 }
4628
4629 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4630 if (VDBG) log("NetworkAgent registered");
4631 } else {
4632 loge("Error connecting NetworkAgent");
4633 mNetworkAgentInfos.remove(nai);
4634 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004635 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004636 synchronized (mNetworkForNetId) {
4637 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004638 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004639 mNetIdManager.releaseNetId(nai.network.getNetId());
4640 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004641 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004642 }
4643 }
4644 }
Paul Jensend5f53392014-11-25 15:26:53 -05004645
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004646 @VisibleForTesting
4647 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09004648 // The feature of creating the networks immediately was slated for U, but race conditions
4649 // detected late required this was flagged off.
4650 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
4651 // in NetworkAgentTest.
4652 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004653 }
4654
4655 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4656 @NonNull NetworkInfo.State state) {
4657 if (nai.isCreated()) return false;
4658 if (state == NetworkInfo.State.CONNECTED) return true;
4659 if (state != NetworkInfo.State.CONNECTING) {
4660 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09004661 if (shouldCreateNetworksImmediately()) {
4662 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4663 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004664 return false;
4665 }
4666 return nai.isVPN() || shouldCreateNetworksImmediately();
4667 }
4668
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004669 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004670 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004671 }
4672
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004673 @VisibleForTesting
4674 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004675 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09004676 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004677
4678 // If the network never roamed, return false. The check below is not sufficient if time
4679 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4680 if (nai.lastRoamTime == 0) return false;
4681
he_won.hwang881307a2022-03-15 21:23:52 +09004682 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4683 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004684 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004685 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004686 final long currentTimeMs = SystemClock.elapsedRealtime();
4687 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004688 if (timeSinceLastRoam <= blockTimeOut) {
4689 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4690 return true;
4691 }
4692 }
4693 return false;
4694 }
4695
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004696 private void handleNetworkAgentDisconnected(Message msg) {
4697 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004698 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004699 }
4700
Chalard Jeand9fffc32018-05-11 20:19:20 +09004701 // Destroys a network, remove references to it from the internal state managed by
4702 // ConnectivityService, free its interfaces and clean up.
4703 // Must be called on the Handler thread.
4704 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004705 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004706
4707 if (!mNetworkAgentInfos.contains(nai)) return;
4708
Chalard Jeand9fffc32018-05-11 20:19:20 +09004709 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004710 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004711 }
lucaslinb25c9a62019-02-12 15:30:13 +08004712 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004713 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004714 // A network agent has disconnected.
4715 // TODO - if we move the logic to the network agent (have them disconnect
4716 // because they lost all their requests or because their score isn't good)
4717 // then they would disconnect organically, report their new state and then
4718 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08004719 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004720 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4721 null, null);
4722 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004723 final boolean wasDefault = isDefaultNetwork(nai);
4724 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004725 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004726 }
4727 notifyIfacesChangedForNetworkStats();
4728 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4729 // by other networks that are already connected. Perhaps that can be done by
4730 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4731 // of rematchAllNetworksAndRequests
4732 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004733 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004734
4735 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004736 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4737 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08004738 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004739 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004740 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004741 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004742 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004743 synchronized (mNetworkForNetId) {
4744 // Remove the NetworkAgent, but don't mark the netId as
4745 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004746 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004747 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004748 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08004749 // Update allowed network lists in netd. This should be called after removing nai
4750 // from mNetworkAgentInfos.
4751 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004752 // Remove all previously satisfied requests.
4753 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004754 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004755 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004756 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004757 if (currentNetwork != null
4758 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004759 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004760 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4761 // rematch not to keep disconnected agents instead of setting it here ; this
4762 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004763 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004764 for (final NetworkOfferInfo noi : mNetworkOffers) {
4765 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004766 }
James Mattise3ef1912020-12-20 11:09:58 -08004767
Chalard Jean5b409c72021-02-04 13:12:59 +09004768 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004769 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004770 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004771 // network, because while incorrect this is the closest to the old (also
4772 // incorrect) behavior.
4773 mNetworkActivityTracker.updateDataActivityTracking(
4774 null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004775 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004776 ensureNetworkTransitionWakelock(nai.toShortString());
4777 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004778 }
4779 }
junyulai2b6f0c22021-02-03 20:15:30 +08004780 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004781 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004782 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004783 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004784 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004785 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004786 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004787
Aaron Huang9fe47be2021-06-08 13:11:45 +08004788 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
4789 // The obvious place to do this would be in makeDefault(), however makeDefault() is
4790 // not called by the rematch in this case. This is because the code above unset
4791 // this network from the default request's satisfier, and that is what the rematch
4792 // is using as its source data to know what the old satisfier was. So as far as the
4793 // rematch above is concerned, the old default network was null.
4794 // Therefore if there is no new default, the default network was null and is still
4795 // null, thus there was no change so makeDefault() is not called. So if the old
4796 // network had a proxy and there is no new default, the proxy tracker should be told
4797 // that there is no longer a default proxy.
4798 // Strictly speaking this is not essential because having a proxy setting when
4799 // there is no network is harmless, but it's still counter-intuitive so reset to null.
4800 mProxyTracker.setDefaultProxy(null);
4801 }
4802
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004803 // Immediate teardown.
4804 if (nai.teardownDelayMs == 0) {
4805 destroyNetwork(nai);
4806 return;
4807 }
4808
4809 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004810 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304811 try {
4812 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4813 } catch (RemoteException e) {
4814 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4815 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004816 }
4817 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4818 }
4819
4820 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004821 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004822 // Tell netd to clean up the configuration for this network
4823 // (routing rules, DNS, etc).
4824 // This may be slow as it requires a lot of netd shelling out to ip and
4825 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004826 // after we've rematched networks with requests (which might change the default
4827 // network or service a new request from an app), so network traffic isn't interrupted
4828 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004829 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004830 }
Chalard Jeandf29a852023-05-29 17:02:43 +09004831 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004832 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4833 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4834 // false if the network was never created.
4835 // TODO: delete when S is no longer supported.
4836 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004837 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004838 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004839 }
4840
Ken Chen6df7a902021-04-09 15:08:42 +08004841 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004842 try {
4843 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004844 final NativeNetworkConfig config;
4845 if (nai.isVPN()) {
4846 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004847 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004848 return false;
4849 }
4850 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4851 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004852 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08004853 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004854 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004855 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004856 getNetworkPermission(nai.networkCapabilities),
4857 false /* secure */,
4858 VpnManager.TYPE_VPN_NONE,
4859 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08004860 }
Ken Chen6df7a902021-04-09 15:08:42 +08004861 mNetd.networkCreate(config);
4862 mDnsResolver.createNetworkCache(nai.network.getNetId());
4863 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4864 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004865 return true;
4866 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004867 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004868 return false;
4869 }
4870 }
4871
Ken Chen6df7a902021-04-09 15:08:42 +08004872 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004873 if (mDscpPolicyTracker != null) {
4874 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
4875 }
Luke Huangfdd11f82019-04-09 18:41:49 +08004876 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004877 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004878 } catch (RemoteException | ServiceSpecificException e) {
4879 loge("Exception destroying network(networkDestroy): " + e);
4880 }
4881 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004882 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004883 } catch (RemoteException | ServiceSpecificException e) {
4884 loge("Exception destroying network: " + e);
4885 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004886 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
4887 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
4888 // gets created, could add data to DnsManager data structures that will never get deleted.
4889 mDnsManager.removeNetwork(nai.network);
4890
4891 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09004892 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004893 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
4894 }
4895
Chalard Jean254bd162022-08-25 13:04:51 +09004896 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004897 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08004898 }
4899
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004900 // If this method proves to be too slow then we can maintain a separate
4901 // pendingIntent => NetworkRequestInfo map.
4902 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4903 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004904 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4905 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4906 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004907 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004908 return entry.getValue();
4909 }
4910 }
4911 return null;
4912 }
4913
Chalard Jean524f0b12021-10-25 21:11:56 +09004914 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09004915 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09004916 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4917 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4918 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4919 // bug is fixed.
4920 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004921 throw new IllegalStateException("This NRI is already registered. New : " + nri
4922 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004923 }
4924 }
4925 }
4926 }
4927
Chalard Jeanac9ace02022-01-26 16:54:05 +09004928 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4929 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08004930 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004931 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4932 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004933 }
4934 return false;
4935 }
4936
James Mattisf7027322020-12-13 16:28:14 -08004937 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004938 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004939 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4940 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4941 final NetworkRequestInfo existingRequest =
4942 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004943 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004944 if (DBG) {
4945 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4946 + nri.mRequests.get(0) + " because their intents matched.");
4947 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004948 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004949 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004950 }
Erik Kline05f2b402015-04-30 12:58:40 +09004951 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004952 }
4953
James Mattisf7027322020-12-13 16:28:14 -08004954 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004955 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004956 }
4957
James Mattis3ce3d3c2021-02-09 18:18:28 -08004958 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004959 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004960 for (final NetworkRequestInfo nri : nris) {
4961 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004962 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004963 for (final NetworkRequest req : nri.mRequests) {
4964 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004965 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004966 if (req.isListen()) {
4967 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4968 if (req.networkCapabilities.hasSignalStrength()
4969 && network.satisfiesImmutableCapabilitiesOf(req)) {
4970 updateSignalStrengthThresholds(network, "REGISTER", req);
4971 }
James Mattisf7027322020-12-13 16:28:14 -08004972 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004973 }
4974 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004975
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004976 // If this NRI has a satisfier already, it is replacing an older request that
4977 // has been removed. Track it.
4978 final NetworkRequest activeRequest = nri.getActiveRequest();
4979 if (null != activeRequest) {
4980 // If there is an active request, then for sure there is a satisfier.
4981 nri.getSatisfier().addRequest(activeRequest);
4982 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004983 }
James Mattisf7027322020-12-13 16:28:14 -08004984
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004985 if (mFlags.noRematchAllRequestsOnRegister()) {
4986 rematchNetworksAndRequests(nris);
4987 } else {
4988 rematchAllNetworksAndRequests();
4989 }
James Mattis45d81842021-01-10 14:24:24 -08004990
Chalard Jean0354d8c2021-01-12 10:58:56 +09004991 // Requests that have not been matched to a network will not have been sent to the
4992 // providers, because the old satisfier and the new satisfier are the same (null in this
4993 // case). Send these requests to the providers.
4994 for (final NetworkRequestInfo nri : nris) {
4995 for (final NetworkOfferInfo noi : mNetworkOffers) {
4996 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004997 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004998 }
4999 }
5000
James Mattisf7027322020-12-13 16:28:14 -08005001 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5002 final int callingUid) {
5003 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005004 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005005 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5006 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5007 handleReleaseNetworkRequest(
5008 nri.mRequests.get(0),
5009 callingUid,
5010 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005011 }
5012 }
5013
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005014 // Determines whether the network is the best (or could become the best, if it validated), for
5015 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5016 // on the value of reason:
5017 //
5018 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5019 // then it should be torn down.
5020 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5021 // then it should be lingered.
5022 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005023 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005024
Chalard Jean254bd162022-08-25 13:04:51 +09005025 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005026 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5027 return false;
5028 }
5029
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005030 final int numRequests;
5031 switch (reason) {
5032 case TEARDOWN:
5033 numRequests = nai.numRequestNetworkRequests();
5034 break;
5035 case LINGER:
5036 numRequests = nai.numForegroundNetworkRequests();
5037 break;
5038 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005039 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005040 return true;
5041 }
5042
Chalard Jean947acd42021-03-08 22:29:27 +09005043 if (numRequests > 0) return false;
5044
Paul Jensende49eb12015-06-25 15:30:08 -04005045 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005046 if (reason == UnneededFor.LINGER
5047 && !nri.isMultilayerRequest()
5048 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005049 // Background requests don't affect lingering.
5050 continue;
5051 }
5052
James Mattis3d229892020-11-16 16:46:28 -08005053 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005054 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005055 }
5056 }
Paul Jensende49eb12015-06-25 15:30:08 -04005057 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005058 }
5059
James Mattis3d229892020-11-16 16:46:28 -08005060 private boolean isNetworkPotentialSatisfier(
5061 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
5062 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005063 // request, return immediately. For multilayer requests, check to see if any of the
5064 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005065 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5066 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005067 return false;
5068 }
5069 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005070 // This multilayer listen request is satisfied therefore no further requests need to be
5071 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005072 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005073 return false;
5074 }
James Mattis3d229892020-11-16 16:46:28 -08005075 // As non-multilayer listen requests have already returned, the below would only happen
5076 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005077 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005078 continue;
5079 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09005080 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08005081 // there is hope for it to become one if it validated, then it is needed.
5082 if (candidate.satisfies(req)) {
5083 // As soon as a network is found that satisfies a request, return. Specifically for
5084 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5085 // is important so as to not evaluate lower priority requests further in
5086 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005087 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5088 ? nri.getSatisfier() : null;
5089 // Note that this catches two important cases:
5090 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5091 // is currently satisfying the request. This is desirable when
5092 // cellular ends up validating but WiFi does not.
5093 // 2. Unvalidated WiFi will not be reaped when validated cellular
5094 // is currently satisfying the request. This is desirable when
5095 // WiFi ends up validating and out scoring cellular.
5096 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005097 }
5098 }
5099
5100 return false;
5101 }
5102
Erik Kline0c04b742016-07-07 16:50:58 +09005103 private NetworkRequestInfo getNriForAppRequest(
5104 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005105 // Looking up the app passed param request in mRequests isn't possible since it may return
5106 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5107 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005108 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5109 // to avoid potential race conditions when validating a package->uid mapping when sending
5110 // the callback on the very low-chance that an application shuts down prior to the callback
5111 // being sent.
5112 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5113 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005114
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005115 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005116 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005117 log(String.format("UID %d attempted to %s for unowned request %s",
5118 callingUid, requestedOperation, nri));
5119 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005120 }
Erik Kline0c04b742016-07-07 16:50:58 +09005121 }
5122
5123 return nri;
5124 }
5125
James Mattisf7027322020-12-13 16:28:14 -08005126 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5127 final String callingMethod) {
5128 if (nri.isMultilayerRequest()) {
5129 throw new IllegalStateException(
5130 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005131 }
5132 }
5133
James Mattisf7027322020-12-13 16:28:14 -08005134 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005135 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005136 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5137 // single NetworkRequest and thus does not apply to multilayer requests.
5138 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5139 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005140 return;
5141 }
James Mattis2516da32021-01-31 17:06:19 -08005142 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005143 return;
5144 }
James Mattisf7027322020-12-13 16:28:14 -08005145 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5146 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005147 }
5148 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005149 callCallbackForRequest(
5150 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005151 }
5152
James Mattisf7027322020-12-13 16:28:14 -08005153 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5154 final int callingUid,
5155 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005156 final NetworkRequestInfo nri =
5157 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5158 if (nri == null) {
5159 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005160 }
James Mattisf7027322020-12-13 16:28:14 -08005161 if (VDBG || (DBG && request.isRequest())) {
5162 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005163 }
5164 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005165 if (callOnUnavailable) {
5166 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5167 }
Erik Kline155a59a2015-11-25 12:49:38 +09005168 }
Erik Kline0c04b742016-07-07 16:50:58 +09005169
James Mattisa076c532020-12-02 14:12:41 -08005170 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005171 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005172 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005173 if (null == mNetworkRequests.remove(req)) {
5174 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5175 continue;
5176 }
James Mattisa076c532020-12-02 14:12:41 -08005177 if (req.isListen()) {
5178 removeListenRequestFromNetworks(req);
5179 }
5180 }
James Mattis8f036802021-06-20 16:26:01 -07005181 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005182 if (mDefaultNetworkRequests.remove(nri)) {
5183 // If this request was one of the defaults, then the UID rules need to be updated
5184 // WARNING : if the app(s) for which this network request is the default are doing
5185 // traffic, this will kill their connected sockets, even if an equivalent request
5186 // is going to be reinstated right away ; unconnected traffic will go on the default
5187 // until the new default is set, which will happen very soon.
5188 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5189 // remove ranges for those requests that won't have a replacement
5190 final NetworkAgentInfo satisfier = nri.getSatisfier();
5191 if (null != satisfier) {
5192 try {
paulhu0e79d952021-06-09 16:11:35 +08005193 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5194 satisfier.network.getNetId(),
5195 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005196 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005197 } catch (RemoteException e) {
5198 loge("Exception setting network preference default network", e);
5199 }
5200 }
5201 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005202
Junyu Lai00d92df2022-07-05 11:01:52 +08005203 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005204 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005205 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005206
5207 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005208 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005209 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005210 }
5211 }
5212
Chalard Jean0354d8c2021-01-12 10:58:56 +09005213 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5214 // needed for this offer.
5215 for (final NetworkOfferInfo noi : mNetworkOffers) {
5216 for (final NetworkRequest req : nri.mRequests) {
5217 if (req.isRequest() && noi.offer.neededFor(req)) {
5218 noi.offer.onNetworkUnneeded(req);
5219 }
5220 }
5221 }
James Mattisa076c532020-12-02 14:12:41 -08005222 }
5223
James Mattis3ce3d3c2021-02-09 18:18:28 -08005224 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5225 for (final NetworkRequestInfo nri : nris) {
5226 if (mDefaultRequest == nri) {
5227 // Make sure we never remove the default request.
5228 continue;
5229 }
5230 handleRemoveNetworkRequest(nri);
5231 }
5232 }
5233
James Mattisa076c532020-12-02 14:12:41 -08005234 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5235 // listens don't have a singular affected Network. Check all networks to see
5236 // if this listen request applies and remove it.
5237 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5238 nai.removeRequest(req.requestId);
5239 if (req.networkCapabilities.hasSignalStrength()
5240 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5241 updateSignalStrengthThresholds(nai, "RELEASE", req);
5242 }
5243 }
5244 }
5245
5246 /**
5247 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5248 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5249 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5250 */
5251 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5252 boolean wasKept = false;
5253 final NetworkAgentInfo nai = nri.getSatisfier();
5254 if (nai != null) {
5255 final int requestLegacyType = nri.getActiveRequest().legacyType;
5256 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5257 nai.removeRequest(nri.getActiveRequest().requestId);
5258 if (VDBG || DDBG) {
5259 log(" Removing from current network " + nai.toShortString()
5260 + ", leaving " + nai.numNetworkRequests() + " requests.");
5261 }
5262 // If there are still lingered requests on this network, don't tear it down,
5263 // but resume lingering instead.
5264 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005265 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005266 notifyNetworkLosing(nai, now);
5267 }
5268 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5269 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5270 teardownUnneededNetwork(nai);
5271 } else {
5272 wasKept = true;
5273 }
James Mattisa076c532020-12-02 14:12:41 -08005274 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5275 // Went from foreground to background.
5276 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005277 }
5278
Erik Kline0c04b742016-07-07 16:50:58 +09005279 // Maintain the illusion. When this request arrived, we might have pretended
5280 // that a network connected to serve it, even though the network was already
5281 // connected. Now that this request has gone away, we might have to pretend
5282 // that the network disconnected. LegacyTypeTracker will generate that
5283 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005284 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005285 boolean doRemove = true;
5286 if (wasKept) {
5287 // check if any of the remaining requests for this network are for the
5288 // same legacy type - if so, don't remove the nai
5289 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5290 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005291 if (otherRequest.legacyType == requestLegacyType
5292 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005293 if (DBG) log(" still have other legacy request - leaving");
5294 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005295 }
5296 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005297 }
5298
Erik Kline0c04b742016-07-07 16:50:58 +09005299 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005300 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005301 }
5302 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005303 }
5304 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005305
Junyu Lai00d92df2022-07-05 11:01:52 +08005306 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005307 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005308 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5309 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5310 }
5311
Lorenzo Colittid6459092016-07-04 12:55:44 +09005312 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005313 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005314 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005315 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005316 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005317 }
5318
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005319 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005320 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5321 enforceNetworkStackSettingsOrSetup();
5322 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5323 encodeBool(accept), encodeBool(always), network));
5324 }
5325
5326 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005327 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005328 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005329 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5330 }
5331
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005332 @Override
5333 public void setTestAllowBadWifiUntil(long timeMs) {
5334 enforceSettingsPermission();
5335 if (!Build.isDebuggable()) {
5336 throw new IllegalStateException("Does not support in non-debuggable build");
5337 }
5338
5339 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5340 throw new IllegalArgumentException("It should not exceed "
5341 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5342 }
5343
5344 mHandler.sendMessage(
5345 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5346 }
5347
chiachangwange0192a72023-02-06 13:25:01 +00005348 @Override
5349 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5350 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005351
5352 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5353 throw new IllegalArgumentException("Argument should not exceed "
5354 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5355 }
5356
5357 mHandler.sendMessage(
5358 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5359 }
5360
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005361 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5362 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5363 " accept=" + accept + " always=" + always);
5364
5365 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5366 if (nai == null) {
5367 // Nothing to do.
5368 return;
5369 }
5370
Chalard Jean254bd162022-08-25 13:04:51 +09005371 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005372 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005373 return;
5374 }
5375
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005376 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005377 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005378 }
5379
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005380 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5381 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005382 // If network becomes partial connectivity and user already accepted to use this
5383 // network, we should respect the user's option and don't need to popup the
5384 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005385 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005386 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005387 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005388 }
5389
5390 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005391 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005392 }
5393
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005394 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005395 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005396 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005397 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005398 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005399 }
5400
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005401 }
5402
lucaslin2240ef62019-03-12 13:08:03 +08005403 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5404 boolean always) {
5405 if (DBG) {
5406 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5407 + " always=" + always);
5408 }
5409
5410 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5411 if (nai == null) {
5412 // Nothing to do.
5413 return;
5414 }
5415
Chalard Jean254bd162022-08-25 13:04:51 +09005416 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005417 // The network validated while the dialog box was up. Take no action.
5418 return;
5419 }
5420
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005421 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5422 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005423 }
5424
5425 // TODO: Use the current design or save the user choice into IpMemoryStore.
5426 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005427 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005428 }
5429
5430 if (!accept) {
5431 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005432 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005433 // Tear down the network.
5434 teardownUnneededNetwork(nai);
5435 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005436 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5437 // result in a partial connectivity result which will be processed by
5438 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005439 //
5440 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5441 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005442 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005443 }
5444 }
5445
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005446 private void handleSetAvoidUnvalidated(Network network) {
5447 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005448 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005449 // Nothing to do. The network either disconnected or revalidated.
5450 return;
5451 }
Chalard Jean254bd162022-08-25 13:04:51 +09005452 if (0L == nai.getAvoidUnvalidated()) {
5453 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005454 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005455 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005456 }
5457 }
5458
Chalard Jean5fb43c72022-09-08 19:03:14 +09005459 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005460 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005461 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005462 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005463 }
5464
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005465 @Override
5466 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005467 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005468 mHandler.post(() -> {
5469 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5470 if (nai == null) return;
5471 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005472 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005473 });
5474 }
5475
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005476 /**
5477 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5478 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005479 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005480 * @param appExtras Bundle to use as intent extras for the captive portal application.
5481 * Must be treated as opaque to avoid preventing the captive portal app to
5482 * update its arguments.
5483 */
5484 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005485 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005486 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5487 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005488
5489 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5490 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005491 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5492 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005493 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5494
lucaslin75ff7022020-12-17 04:14:35 +08005495 final long token = Binder.clearCallingIdentity();
5496 try {
5497 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5498 } finally {
5499 Binder.restoreCallingIdentity(token);
5500 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005501 }
5502
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005503 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5504 private final Network mNetwork;
5505
5506 private CaptivePortalImpl(Network network) {
5507 mNetwork = network;
5508 }
5509
5510 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005511 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005512 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5513 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005514 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5515 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5516 // Since the network will be disconnected, skip notifying NetworkMonitor
5517 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005518 }
5519
Chiachang Wang938bfba2020-01-09 13:50:55 +08005520 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005521 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005522 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005523 }
5524
5525 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005526 public void appRequest(final int request) {
5527 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5528 if (nm == null) return;
5529
5530 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005531 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005532 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005533 }
5534 }
5535
5536 @Nullable
5537 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5538 // getNetworkAgentInfoForNetwork is thread-safe
5539 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5540 if (nai == null) return null;
5541
5542 // nai.networkMonitor() is thread-safe
5543 return nai.networkMonitor();
5544 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005545 }
5546
Hugo Benichic9048bc2016-09-14 23:23:08 +00005547 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005548 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005549 }
5550
Chalard Jean020b93a2022-09-01 13:20:14 +09005551 private boolean activelyPreferBadWifi() {
5552 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5553 }
5554
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005555 /**
5556 * Return whether the device should maintain continuous, working connectivity by switching away
5557 * from WiFi networks having no connectivity.
5558 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5559 */
5560 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005561 if (!checkNetworkStackPermission()) {
5562 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5563 }
5564 return avoidBadWifi();
5565 }
5566
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005567 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005568 ensureRunningOnConnectivityServiceThread();
5569 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005570 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005571 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005572 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005573 if (avoidBadWifi) {
5574 // If the device is now avoiding bad wifi, remove notifications that might have
5575 // been put up when the device didn't.
5576 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5577 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005578 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005579 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5580 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5581 for (final NetworkOfferInfo noi : offersToUpdate) {
5582 updateOfferScore(noi.offer);
5583 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005584 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005585 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005586 }
5587
Erik Kline95ecfee2016-10-02 18:02:14 +09005588 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005589 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005590 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005591 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005592 if (!configRestrict) {
5593 pw.println("Bad Wi-Fi avoidance: unrestricted");
5594 return;
5595 }
5596
5597 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5598 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005599 pw.println("Config restrict: " + configRestrict);
5600 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005601
Chalard Jeane0fdea32022-09-14 21:44:22 +09005602 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005603 String description;
5604 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005605 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005606 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005607 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005608 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005609 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005610 description = "avoid";
5611 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005612 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005613 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005614 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005615
5616 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5617 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005618 if (null == configValue) {
5619 description = "unset";
5620 } else if (configValue) {
5621 description = "force true";
5622 } else {
5623 description = "force false";
5624 }
5625 pw.println("Actively prefer bad wifi conf: " + description);
5626 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005627 pw.println("Network overrides:");
5628 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005629 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005630 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005631 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005632 }
5633 }
5634 pw.decreaseIndent();
5635 pw.decreaseIndent();
5636 }
5637
paulhu7746e4e2020-06-09 19:07:03 +08005638 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5639 // unify the method.
5640 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5641 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5642 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5643 return settingsComponent != null
5644 ? settingsComponent.getPackageName() : "com.android.settings";
5645 }
5646
lucaslinb1e8e382019-01-24 15:55:30 +08005647 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005648 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005649 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005650 switch (type) {
5651 case NO_INTERNET:
5652 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005653 // High priority because it is only displayed for explicitly selected networks.
5654 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005655 break;
lucasline117e2e2019-10-22 18:27:33 +08005656 case PRIVATE_DNS_BROKEN:
5657 action = Settings.ACTION_WIRELESS_SETTINGS;
5658 // High priority because we should let user know why there is no internet.
5659 highPriority = true;
5660 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005661 case LOST_INTERNET:
5662 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005663 // High priority because it could help the user avoid unexpected data usage.
5664 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005665 break;
lucaslin2240ef62019-03-12 13:08:03 +08005666 case PARTIAL_CONNECTIVITY:
5667 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005668 // Don't bother the user with a high-priority notification if the network was not
5669 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005670 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005671 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005672 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005673 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005674 return;
5675 }
5676
5677 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005678 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005679 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005680 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005681 // Some OEMs have their own Settings package. Thus, need to get the current using
5682 // Settings package name instead of just use default name "com.android.settings".
5683 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5684 intent.setClassName(settingsPkgName,
5685 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005686 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005687
paulhu2af50222020-10-11 22:52:27 +08005688 PendingIntent pendingIntent = PendingIntent.getActivity(
5689 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005690 0 /* requestCode */,
5691 intent,
paulhu2af50222020-10-11 22:52:27 +08005692 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005693
Serik Beketayevec8ad212020-12-07 22:43:07 -08005694 mNotifier.showNotification(
5695 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005696 }
5697
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005698 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5699 // Don't prompt if the network is validated, and don't prompt on captive portals
5700 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005701 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005702 return false;
5703 }
5704
5705 // If a network has partial connectivity, always prompt unless the user has already accepted
5706 // partial connectivity and selected don't ask again. This ensures that if the device
5707 // automatically connects to a network that has partial Internet access, the user will
5708 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005709 // because we have prompted them.
5710 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005711 return true;
5712 }
5713
5714 // If a network has no Internet access, only prompt if the network was explicitly selected
5715 // and if the user has not already told us to use the network regardless of whether it
5716 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005717 if (nai.networkAgentConfig.explicitlySelected
5718 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005719 return true;
5720 }
5721
5722 return false;
5723 }
5724
Chalard Jean5fb43c72022-09-08 19:03:14 +09005725 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5726 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005727
Chalard Jean5fb43c72022-09-08 19:03:14 +09005728 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5729 if (null == nai) return;
5730
5731 if (nai.setEvaluated()) {
5732 // If setEvaluated() returned true, the network never had any form of connectivity.
5733 // This may have an impact on request matching if bad WiFi avoidance is off and the
5734 // network was found not to have Internet access.
5735 nai.updateScoreForNetworkAgentUpdate();
5736 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005737
5738 // Also, if this is WiFi and it should be preferred actively, now is the time to
5739 // prompt the user that they walked past and connected to a bad WiFi.
5740 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5741 && !avoidBadWifi()
5742 && activelyPreferBadWifi()) {
5743 // The notification will be removed if the network validates or disconnects.
5744 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5745 return;
5746 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005747 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005748
Chalard Jean5fb43c72022-09-08 19:03:14 +09005749 if (!shouldPromptUnvalidated(nai)) return;
5750
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005751 // Stop automatically reconnecting to this network in the future. Automatically connecting
5752 // to a network that provides no or limited connectivity is not useful, because the user
5753 // cannot use that network except through the notification shown by this method, and the
5754 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005755 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005756
Chalard Jean254bd162022-08-25 13:04:51 +09005757 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005758 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005759 } else {
5760 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5761 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005762 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005763
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005764 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5765 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005766 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005767
lucaslin2240ef62019-03-12 13:08:03 +08005768 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5769 return;
5770 }
5771
5772 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005773 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005774 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005775 }
5776
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005777 @Override
5778 public int getMultipathPreference(Network network) {
5779 enforceAccessPermission();
5780
5781 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005782 if (nai != null && nai.networkCapabilities
5783 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005784 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5785 }
5786
Aaron Huang9a57acf2020-12-08 10:03:29 +08005787 final NetworkPolicyManager netPolicyManager =
5788 mContext.getSystemService(NetworkPolicyManager.class);
5789
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005790 final long token = Binder.clearCallingIdentity();
5791 final int networkPreference;
5792 try {
5793 networkPreference = netPolicyManager.getMultipathPreference(network);
5794 } finally {
5795 Binder.restoreCallingIdentity(token);
5796 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005797 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005798 return networkPreference;
5799 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005800 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5801 }
5802
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005803 @Override
5804 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005805 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005806 }
5807
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005808 private class InternalHandler extends Handler {
5809 public InternalHandler(Looper looper) {
5810 super(looper);
5811 }
5812
5813 @Override
5814 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005815 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005816 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005817 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005818 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005819 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005820 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005821 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005822 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005823 break;
5824 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08005825 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005826 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08005827 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005828 break;
5829 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005830 case EVENT_REGISTER_NETWORK_PROVIDER: {
5831 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005832 break;
5833 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005834 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5835 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005836 break;
5837 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005838 case EVENT_REGISTER_NETWORK_OFFER: {
5839 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5840 break;
5841 }
5842 case EVENT_UNREGISTER_NETWORK_OFFER: {
5843 final NetworkOfferInfo offer =
5844 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5845 if (null != offer) {
5846 handleUnregisterNetworkOffer(offer);
5847 }
5848 break;
5849 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005850 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005851 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5852 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5853 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005854 break;
5855 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005856 case EVENT_REGISTER_NETWORK_REQUEST:
5857 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005858 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005859 break;
5860 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005861 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5862 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005863 handleRegisterNetworkRequestWithIntent(msg);
5864 break;
5865 }
Erik Kline155a59a2015-11-25 12:49:38 +09005866 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5867 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5868 handleTimedOutNetworkRequest(nri);
5869 break;
5870 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005871 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5872 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5873 break;
5874 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005875 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005876 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5877 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005878 break;
5879 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005880 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005881 Network network = (Network) msg.obj;
5882 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005883 break;
5884 }
lucaslin2240ef62019-03-12 13:08:03 +08005885 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5886 Network network = (Network) msg.obj;
5887 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5888 toBool(msg.arg2));
5889 break;
5890 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005891 case EVENT_SET_AVOID_UNVALIDATED: {
5892 handleSetAvoidUnvalidated((Network) msg.obj);
5893 break;
5894 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09005895 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
5896 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005897 break;
5898 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005899 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5900 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005901 break;
5902 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00005903 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
5904 // handler thread.
5905 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005906 mKeepaliveTracker.handleStartKeepalive(msg);
5907 break;
5908 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00005909 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09005910 final AutomaticOnOffKeepalive ki =
5911 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
5912 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005913
chiachangwang676c84e2023-02-14 09:22:05 +00005914 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005915 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005916 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00005917 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005918 for (NetworkAgentInfo n : mNetworkAgentInfos) {
5919 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00005920 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
5921 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005922 }
5923 }
5924
5925 // If the network no longer exists, then the keepalive should have been
5926 // cleaned up already. There is no point trying to resume keepalives.
5927 if (!networkFound) return;
5928
chiachangwang676c84e2023-02-14 09:22:05 +00005929 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005930 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang676c84e2023-02-14 09:22:05 +00005931 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005932 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00005933 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005934 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005935 }
5936 break;
5937 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005938 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005939 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09005940 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
5941 (IBinder) msg.obj);
5942 if (ki == null) {
5943 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00005944 return;
5945 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09005946 final int reason = msg.arg2;
5947 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005948 break;
5949 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005950 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5951 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5952 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005953 break;
5954 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005955 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5956 handlePrivateDnsSettingsChanged();
5957 break;
dalyk1720e542018-03-05 12:42:22 -05005958 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5959 handlePrivateDnsValidationUpdate(
5960 (PrivateDnsValidationUpdate) msg.obj);
5961 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005962 case EVENT_UID_BLOCKED_REASON_CHANGED:
5963 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005964 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005965 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5966 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5967 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005968 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005969 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5970 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005971 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005972 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005973 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005974 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09005975 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
5976 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005977 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005978 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005979 }
lucaslin1193a5d2021-01-21 02:04:15 +08005980 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09005981 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09005982 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08005983 break;
paulhu51f77dc2021-06-07 02:34:20 +00005984 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5985 handleMobileDataPreferredUidsChanged();
5986 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005987 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5988 final long timeMs = ((Long) msg.obj).longValue();
5989 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5990 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005991 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5992 handleIngressRateLimitChanged();
5993 break;
Hansen Kurli55396972022-10-28 03:31:17 +00005994 case EVENT_USER_DOES_NOT_WANT:
5995 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5996 if (nai == null) break;
5997 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00005998 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00005999 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006000 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6001 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6002 break;
chiachangwange0192a72023-02-06 13:25:01 +00006003 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6004 final long time = ((Long) msg.obj).longValue();
6005 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6006 break;
6007 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006008 case EVENT_UID_FROZEN_STATE_CHANGED:
6009 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6010 handleFrozenUids(args.mUids, args.mFrozenStates);
6011 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006012 }
6013 }
6014 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006015
Lorenzo Colittid6459092016-07-04 12:55:44 +09006016 @Override
markchien5776f962019-12-16 20:15:20 +08006017 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006018 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006019 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006020 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6021 Context.TETHERING_SERVICE);
6022 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006023 }
6024
Lorenzo Colittid6459092016-07-04 12:55:44 +09006025 @Override
markchien5776f962019-12-16 20:15:20 +08006026 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006027 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006028 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006029 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6030 Context.TETHERING_SERVICE);
6031 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006032 }
6033
Lorenzo Colittid6459092016-07-04 12:55:44 +09006034 @Override
markchien5776f962019-12-16 20:15:20 +08006035 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006036 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006037 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006038 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6039 Context.TETHERING_SERVICE);
6040 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006041 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006042
markchien5776f962019-12-16 20:15:20 +08006043
Lorenzo Colittid6459092016-07-04 12:55:44 +09006044 @Override
markchien5776f962019-12-16 20:15:20 +08006045 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006046 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006047 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006048 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6049 Context.TETHERING_SERVICE);
6050
6051 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006052 }
6053
Lorenzo Colittid6459092016-07-04 12:55:44 +09006054 @Override
markchien5776f962019-12-16 20:15:20 +08006055 @Deprecated
6056 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006057 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006058 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6059 Context.TETHERING_SERVICE);
6060
6061 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006062 }
6063
Udam Saini8f7d6a72017-06-07 12:06:28 -07006064 @Override
markchien5776f962019-12-16 20:15:20 +08006065 @Deprecated
6066 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006067 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006068 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6069 Context.TETHERING_SERVICE);
6070 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006071 }
6072
Robert Greenwalte0b00512014-07-02 09:59:16 -07006073 // Called when we lose the default network and have no replacement yet.
6074 // This will automatically be cleared after X seconds or a new default network
6075 // becomes CONNECTED, whichever happens first. The timer is started by the
6076 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006077 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006078 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006079 if (mNetTransitionWakeLock.isHeld()) {
6080 return;
6081 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006082 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006083 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6084 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006085 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006086 mWakelockLogs.log("ACQUIRE for " + forWhom);
6087 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006088 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006089 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006090 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006091 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006092
Hugo Benichi471b62a2017-03-30 23:18:10 +09006093 // Called when we gain a new default network to release the network transition wakelock in a
6094 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6095 // message is cancelled.
6096 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006097 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006098 if (!mNetTransitionWakeLock.isHeld()) {
6099 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006100 }
6101 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006102 // Cancel self timeout on wakelock hold.
6103 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6104 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6105 mHandler.sendMessageDelayed(msg, 1000);
6106 }
6107
6108 // Called when either message of ensureNetworkTransitionWakelock or
6109 // scheduleReleaseNetworkTransitionWakelock is processed.
6110 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6111 String event = eventName(eventId);
6112 synchronized (this) {
6113 if (!mNetTransitionWakeLock.isHeld()) {
6114 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006115 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006116 return;
6117 }
6118 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006119 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6120 mTotalWakelockDurationMs += lockDuration;
6121 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6122 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006123 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006124 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006125 }
6126
Robert Greenwalt986c7412010-09-08 15:24:47 -07006127 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006128 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006129 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006130 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006131 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006132 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006133 }
6134
Lorenzo Colittid6459092016-07-04 12:55:44 +09006135 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006136 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006137 enforceAccessPermission();
6138 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006139 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006140 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006141
6142 final NetworkAgentInfo nai;
6143 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006144 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006145 } else {
6146 nai = getNetworkAgentInfoForNetwork(network);
6147 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006148
6149 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006150 mHandler.obtainMessage(
6151 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006152 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006153
Hugo Benichid6b510a2017-04-06 17:22:18 +09006154 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006155 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006156 if (nai == null
6157 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006158 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006159 return;
6160 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006161 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006162 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006163 mConnectivityDiagnosticsHandler.sendMessage(
6164 mConnectivityDiagnosticsHandler.obtainMessage(
6165 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6166 new ReportedNetworkConnectivityInfo(
6167 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006168 return;
6169 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006170 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006171 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006172 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006173 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006174 // Validating a network that has not yet connected could result in a call to
6175 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006176 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006177 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006178 }
paulhu7aeba372020-12-30 00:42:19 +08006179 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6180 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006181 return;
6182 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006183
6184 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6185 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6186 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6187 // completed.
6188 mConnectivityDiagnosticsHandler.sendMessage(
6189 mConnectivityDiagnosticsHandler.obtainMessage(
6190 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6191 new ReportedNetworkConnectivityInfo(
6192 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006193 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006194 }
6195
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006196 // TODO: call into netd.
6197 private boolean queryUserAccess(int uid, Network network) {
6198 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6199 if (nai == null) return false;
6200
6201 // Any UID can use its default network.
6202 if (nai == getDefaultNetworkForUid(uid)) return true;
6203
6204 // Privileged apps can use any network.
6205 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6206 return true;
6207 }
6208
6209 // An unprivileged UID can use a VPN iff the VPN applies to it.
6210 if (nai.isVPN()) {
6211 return nai.networkCapabilities.appliesToUid(uid);
6212 }
6213
6214 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6215 // sockets, i.e., if it is the owner.
6216 final NetworkAgentInfo vpn = getVpnForUid(uid);
6217 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6218 && uid != vpn.networkCapabilities.getOwnerUid()) {
6219 return false;
6220 }
6221
6222 // The UID's permission must be at least sufficient for the network. Since the restricted
6223 // permission was already checked above, that just leaves background networks.
6224 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6225 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6226 }
6227
6228 // Unrestricted network. Anyone gets to use it.
6229 return true;
6230 }
6231
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006232 /**
6233 * Returns information about the proxy a certain network is using. If given a null network, it
6234 * it will return the proxy for the bound network for the caller app or the default proxy if
6235 * none.
6236 *
6237 * @param network the network we want to get the proxy information for.
6238 * @return Proxy information if a network has a proxy configured, or otherwise null.
6239 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006240 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006241 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006242 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006243 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006244 if (network == null) {
6245 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006246 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006247 true);
6248 if (activeNetwork == null) {
6249 return null;
6250 }
6251 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006252 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006253 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6254 // caller may not have.
6255 return getLinkPropertiesProxyInfo(network);
6256 }
6257 // No proxy info available if the calling UID does not have network access.
6258 return null;
6259 }
6260
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006261
6262 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006263 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6264 if (nai == null) return null;
6265 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006266 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6267 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006268 }
6269 }
6270
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006271 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006272 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006273 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006274 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006275 }
6276
Chalard Jean777e2e52018-06-07 18:02:37 +09006277 @Override
6278 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006279 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006280 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006281 }
6282
Aaron Huang9fe47be2021-06-08 13:11:45 +08006283 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006284 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006285 final NetworkAgentInfo nai = getDefaultNetwork();
6286 // TODO : this method should check that net == nai.network, unfortunately at this point
6287 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6288 // is only ever installed on the default network so in practice this is okay.
6289 if (null == nai) return;
6290 // PAC proxies only work on the default network. Therefore, only the default network
6291 // should have its link properties fixed up for PAC proxies.
6292 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6293 if (nai.everConnected()) {
6294 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6295 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006296 }
6297
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006298 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6299 // when any network changes proxy.
6300 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6301 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006302 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6303 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006304 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6305
Chalard Jean7d97afc2018-06-07 17:41:29 +09006306 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006307 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006308 }
6309 }
6310
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006311 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006312 final private HashMap<Uri, Integer> mUriEventMap;
6313 final private Context mContext;
6314 final private Handler mHandler;
6315
6316 SettingsObserver(Context context, Handler handler) {
6317 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006318 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006319 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006320 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006321 }
6322
Erik Kline05f2b402015-04-30 12:58:40 +09006323 void observe(Uri uri, int what) {
6324 mUriEventMap.put(uri, what);
6325 final ContentResolver resolver = mContext.getContentResolver();
6326 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006327 }
6328
6329 @Override
6330 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006331 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006332 }
6333
6334 @Override
6335 public void onChange(boolean selfChange, Uri uri) {
6336 final Integer what = mUriEventMap.get(uri);
6337 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006338 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006339 } else {
6340 loge("No matching event to send for URI=" + uri);
6341 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006342 }
6343 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006344
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006345 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006346 Log.d(TAG, s);
6347 }
6348
6349 private static void logw(String s) {
6350 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006351 }
6352
Daniel Brightf9e945b2020-06-15 16:10:01 -07006353 private static void logwtf(String s) {
6354 Log.wtf(TAG, s);
6355 }
6356
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006357 private static void logwtf(String s, Throwable t) {
6358 Log.wtf(TAG, s, t);
6359 }
6360
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006361 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006362 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006363 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006364
Hugo Benichi39621362017-02-11 17:04:43 +09006365 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006366 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006367 }
6368
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006369 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006370 * Return the information of all ongoing VPNs.
6371 *
6372 * <p>This method is used to update NetworkStatsService.
6373 *
6374 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006375 */
junyulai2050bed2021-01-23 09:46:34 +08006376 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006377 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006378 if (mLockdownEnabled) {
6379 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006380 }
junyulai2050bed2021-01-23 09:46:34 +08006381 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006382 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006383 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006384 if (info != null) {
6385 infoList.add(info);
6386 }
6387 }
junyulai2050bed2021-01-23 09:46:34 +08006388 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006389 }
6390
6391 /**
6392 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006393 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006394 */
junyulai2050bed2021-01-23 09:46:34 +08006395 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006396 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006397 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6398 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006399 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6400 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6401 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006402 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6403 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006404 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006405 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006406 }
6407 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006408
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006409 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006410
6411 List<String> interfaces = new ArrayList<>();
6412 for (Network network : underlyingNetworks) {
6413 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6414 if (underlyingNai == null) continue;
6415 LinkProperties lp = underlyingNai.linkProperties;
6416 for (String iface : lp.getAllInterfaceNames()) {
6417 if (!TextUtils.isEmpty(iface)) {
6418 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006419 }
6420 }
Benedict Wong34857f82019-06-12 17:46:15 +00006421 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006422
6423 if (interfaces.isEmpty()) return null;
6424
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006425 // Must be non-null or NetworkStatsService will crash.
6426 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6427 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006428 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006429 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006430
junyulai2050bed2021-01-23 09:46:34 +08006431 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6432 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006433 }
6434
James Mattisd31bdfa2020-12-23 16:37:26 -08006435 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006436 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6437 Network[] underlyingNetworks) {
6438 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006439 if (underlyingNetworks == null && defaultNetwork != null) {
6440 // null underlying networks means to track the default.
6441 underlyingNetworks = new Network[] { defaultNetwork };
6442 }
6443 return underlyingNetworks;
6444 }
6445
6446 // Returns true iff |network| is an underlying network of |nai|.
6447 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6448 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6449 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006450 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006451 final Network[] underlying = underlyingNetworksOrDefault(
6452 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006453 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006454 }
6455
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006456 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006457 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006458 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006459 * When underlying networks change, such networks may have to update capabilities to reflect
6460 * things like the metered bit, their transports, and so on. The capabilities are calculated
6461 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006462 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006463 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006464 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006465 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006466 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006467 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006468 }
6469 }
6470 }
6471
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006472 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6473 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6474 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6475 // a VPN is not up.
6476 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6477 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6478 for (UidRange range : blockedUidRanges) {
6479 if (range.contains(uid)) return true;
6480 }
6481 return false;
6482 }
6483
6484 @Override
6485 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006486 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006487 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6488 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6489 }
6490
6491 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6492 if (DBG) {
6493 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6494 + Arrays.toString(ranges));
6495 }
6496 // Cannot use a Set since the list of UID ranges might contain duplicates.
6497 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6498 for (int i = 0; i < ranges.length; i++) {
6499 if (requireVpn) {
6500 newVpnBlockedUidRanges.add(ranges[i]);
6501 } else {
6502 newVpnBlockedUidRanges.remove(ranges[i]);
6503 }
6504 }
6505
6506 try {
6507 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6508 } catch (RemoteException | ServiceSpecificException e) {
6509 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6510 + Arrays.toString(ranges) + "): netd command failed: " + e);
6511 }
6512
Chalard Jeandf29a852023-05-29 17:02:43 +09006513 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006514 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6515 }
6516
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006517 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6518 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006519 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6520 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006521 }
6522
6523 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6524 }
6525
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006526 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006527 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006528 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006529 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006530 }
6531
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006532 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6533 return mLockdownEnabled
6534 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6535 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006536 }
6537
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006538 private NetworkAgentInfo getLegacyLockdownNai() {
6539 if (!mLockdownEnabled) {
6540 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006541 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006542 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006543 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6544 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006545
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006546 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006547 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6548 // a local variable. There is no need to make a copy because its contents cannot change.
6549 final Network[] underlying = nai.declaredUnderlyingNetworks;
6550 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006551 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006552 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006553
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006554 // The legacy lockdown VPN always uses the default network.
6555 // If the VPN's underlying network is no longer the current default network, it means that
6556 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006557 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6558 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006559 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006560 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006561 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006562 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006563
6564 return nai;
6565 };
6566
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006567 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6568 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6569 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006570 private DetailedState getLegacyLockdownState(DetailedState origState) {
6571 if (origState != DetailedState.CONNECTED) {
6572 return origState;
6573 }
6574 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6575 ? DetailedState.CONNECTING
6576 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006577 }
6578
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006579 private void filterForLegacyLockdown(NetworkInfo ni) {
6580 if (!mLockdownEnabled || !ni.isConnected()) return;
6581 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6582 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6583 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6584 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6585 // network, this time with a state of CONNECTED.
6586 //
6587 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6588 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6589 // is not too far off the truth, since an always-on VPN, when not connected, is always
6590 // trying to reconnect.
6591 if (getLegacyLockdownNai() == null) {
6592 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6593 }
6594 }
6595
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006596 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006597 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006598 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006599 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006600 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6601 return;
6602 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006603 final long ident = Binder.clearCallingIdentity();
6604 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006605 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006606 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006607 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006608 } finally {
6609 Binder.restoreCallingIdentity(ident);
6610 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006611 }
Wink Savillecb117d32013-08-29 14:57:08 -07006612
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006613 @Override
6614 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006615 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006616 final long ident = Binder.clearCallingIdentity();
6617 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006618 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006619 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006620 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6621 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006622 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006623 } finally {
6624 Binder.restoreCallingIdentity(ident);
6625 }
6626 }
6627
James Mattis02220e22021-03-13 19:27:21 -08006628 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006629 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6630 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6631 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006632 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006633 }
6634
James Mattis02220e22021-03-13 19:27:21 -08006635 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006636 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006637 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006638 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6639 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006640 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006641 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6642 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6643 }
junyulaid91e7052020-08-28 13:44:33 +08006644 }
6645
James Mattis02220e22021-03-13 19:27:21 -08006646 private void onPackageChanged(@NonNull final String packageName) {
6647 // This is necessary in case a package is added or removed, but also when it's replaced to
6648 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6649 // as one in the preferences, then it should follow the same routing as that other package,
6650 // which means updating the rules is never to be needed in this case (whether it joins or
6651 // leaves a UID with a preference).
6652 if (isMappedInOemNetworkPreference(packageName)) {
6653 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6654 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006655
6656 // Invalidates cache entry when the package is updated.
6657 synchronized (mSelfCertifiedCapabilityCache) {
6658 mSelfCertifiedCapabilityCache.remove(packageName);
6659 }
James Mattis02220e22021-03-13 19:27:21 -08006660 }
6661
6662 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006663 @Override
6664 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006665 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006666 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006667 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006668
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006669 // User should be filled for below intents, check the existence.
6670 if (user == null) {
6671 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6672 return;
6673 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006674
Lorenzo Colitticd675292021-02-04 17:32:07 +09006675 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006676 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006677 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006678 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006679 } else {
junyulaid91e7052020-08-28 13:44:33 +08006680 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006681 }
6682 }
6683 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006684
James Mattis02220e22021-03-13 19:27:21 -08006685 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6686 @Override
6687 public void onReceive(Context context, Intent intent) {
6688 ensureRunningOnConnectivityServiceThread();
6689 switch (intent.getAction()) {
6690 case Intent.ACTION_PACKAGE_ADDED:
6691 case Intent.ACTION_PACKAGE_REMOVED:
6692 case Intent.ACTION_PACKAGE_REPLACED:
6693 onPackageChanged(intent.getData().getSchemeSpecificPart());
6694 break;
6695 default:
6696 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6697 }
6698 }
6699 };
6700
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006701 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006702 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006703
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006704 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006705 public final String name;
6706 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006707 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006708 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006709
lifraf3a3492021-03-10 13:58:14 +08006710 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6711 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006712 this.name = name;
6713 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006714 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006715 mDeathRecipient = deathRecipient;
6716
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006717 if (mDeathRecipient == null) {
6718 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006719 }
6720 }
6721
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006722 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006723 try {
6724 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6725 } catch (RemoteException e) {
6726 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006727 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006728 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006729 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006730
James Mattis4fce5d12020-11-12 15:53:42 -08006731 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6732 for (int i = 0; i < requests.size(); i++) {
6733 ensureNetworkRequestHasType(requests.get(i));
6734 }
6735 }
6736
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006737 private void ensureNetworkRequestHasType(NetworkRequest request) {
6738 if (request.type == NetworkRequest.Type.NONE) {
6739 throw new IllegalArgumentException(
6740 "All NetworkRequests in ConnectivityService must have a type");
6741 }
6742 }
6743
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006744 /**
6745 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006746 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006747 */
James Mattis258ea3c2020-11-15 15:04:40 -08006748 @VisibleForTesting
6749 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006750 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6751 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006752 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006753
James Mattisa076c532020-12-02 14:12:41 -08006754 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6755 void setSatisfier(
6756 @Nullable final NetworkAgentInfo satisfier,
6757 @Nullable final NetworkRequest activeRequest) {
6758 mSatisfier = satisfier;
6759 mActiveRequest = activeRequest;
6760 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006761
James Mattisd31bdfa2020-12-23 16:37:26 -08006762 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006763 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006764 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006765 private NetworkAgentInfo mSatisfier;
6766 NetworkAgentInfo getSatisfier() {
6767 return mSatisfier;
6768 }
6769
6770 // The request in mRequests assigned to a network agent. This is null if none of the
6771 // requests in mRequests can be satisfied. This member has the constraint of only being
6772 // accessible on the handler thread.
6773 @Nullable
6774 private NetworkRequest mActiveRequest;
6775 NetworkRequest getActiveRequest() {
6776 return mActiveRequest;
6777 }
6778
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006779 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006780 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006781 @Nullable
6782 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006783
6784 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006785 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006786 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006787 final int mPid;
6788 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006789 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006790 @Nullable
6791 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006792
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006793 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006794 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006795
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006796 // Effective UID of this request. This is different from mUid when a privileged process
6797 // files a request on behalf of another UID. This UID is used to determine blocked status,
6798 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6799 // maximum limit of registered callbacks per UID.
6800 final int mAsUid;
6801
paulhu48291862021-07-14 14:53:57 +08006802 // Preference order of this request.
6803 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006804
James Mattis3ce3d3c2021-02-09 18:18:28 -08006805 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6806 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6807 // maintained for keying off of. This is only a concern when the original nri
6808 // mNetworkRequests changes which happens currently for apps that register callbacks to
6809 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6810 // that match the per-app default nri that currently tracks the calling app's uid so that
6811 // callbacks are fired at the appropriate time. When the callbacks fire,
6812 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6813 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6814 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6815 @NonNull
6816 private final NetworkRequest mNetworkRequestForCallback;
6817 NetworkRequest getNetworkRequestForCallback() {
6818 return mNetworkRequestForCallback;
6819 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006820
James Mattisd31bdfa2020-12-23 16:37:26 -08006821 /**
6822 * Get the list of UIDs this nri applies to.
6823 */
6824 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006825 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006826 // networkCapabilities.getUids() returns a defensive copy.
6827 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006828 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6829 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006830 }
6831
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006832 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6833 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006834 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006835 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006836 }
6837
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006838 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006839 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006840 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006841 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006842 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006843 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006844 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006845 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006846 mBinder = null;
6847 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006848 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006849 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006850 mPerUidCounter = getRequestCounter(this);
6851 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006852 /**
6853 * Location sensitive data not included in pending intent. Only included in
6854 * {@link NetworkCallback}.
6855 */
6856 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006857 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006858 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006859 }
6860
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006861 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006862 @Nullable final IBinder binder,
6863 @NetworkCallback.Flag int callbackFlags,
6864 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006865 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6866 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006867 }
6868
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006869 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006870 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006871 @Nullable final IBinder binder,
6872 @NetworkCallback.Flag int callbackFlags,
6873 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006874 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006875 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006876 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006877 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006878 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006879 mBinder = binder;
6880 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006881 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006882 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006883 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006884 mPerUidCounter = getRequestCounter(this);
6885 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006886 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006887 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006888 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006889 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006890 }
6891
James Mattis3ce3d3c2021-02-09 18:18:28 -08006892 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6893 @NonNull final List<NetworkRequest> r) {
6894 super();
6895 ensureAllNetworkRequestsHaveType(r);
6896 mRequests = initializeRequests(r);
6897 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006898 final NetworkAgentInfo satisfier = nri.getSatisfier();
6899 if (null != satisfier) {
6900 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6901 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09006902 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006903 // As this code creates a new NRI with a new set of requests, figure out which of
6904 // the list of requests should be the active request. It is always the first
6905 // request of the list that can be satisfied by the satisfier since the order of
6906 // requests is a priority order.
6907 // Note even in the presence of a satisfier there may not be an active request,
6908 // when the satisfier is the no-service network.
6909 NetworkRequest activeRequest = null;
6910 for (final NetworkRequest candidate : r) {
6911 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6912 activeRequest = candidate;
6913 break;
6914 }
6915 }
6916 setSatisfier(satisfier, activeRequest);
6917 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006918 mMessenger = nri.mMessenger;
6919 mBinder = nri.mBinder;
6920 mPid = nri.mPid;
6921 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006922 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006923 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006924 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006925 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006926 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006927 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006928 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006929 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006930 }
6931
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006932 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006933 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006934 }
6935
paulhue9913722021-05-26 15:19:20 +08006936 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006937 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006938 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006939 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006940 }
6941
James Mattis2516da32021-01-31 17:06:19 -08006942 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6943 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6944 // false.
6945 boolean isBeingSatisfied() {
6946 return (null != mSatisfier && null != mActiveRequest);
6947 }
6948
James Mattis3d229892020-11-16 16:46:28 -08006949 boolean isMultilayerRequest() {
6950 return mRequests.size() > 1;
6951 }
6952
James Mattis45d81842021-01-10 14:24:24 -08006953 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6954 // Creating a defensive copy to prevent the sender from modifying the list being
6955 // reflected in the return value of this method.
6956 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006957 return Collections.unmodifiableList(tempRequests);
6958 }
6959
James Mattisb1392002021-03-31 13:57:52 -07006960 void linkDeathRecipient() {
6961 if (null != mBinder) {
6962 try {
6963 mBinder.linkToDeath(this, 0);
6964 } catch (RemoteException e) {
6965 binderDied();
6966 }
6967 }
6968 }
6969
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006970 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006971 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006972 try {
6973 mBinder.unlinkToDeath(this, 0);
6974 } catch (NoSuchElementException e) {
6975 // Temporary workaround for b/194394697 pending analysis of additional logs
6976 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6977 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006978 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006979 }
6980
paulhu48291862021-07-14 14:53:57 +08006981 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6982 // Compare two preference orders.
6983 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006984 }
6985
paulhu48291862021-07-14 14:53:57 +08006986 int getPreferenceOrderForNetd() {
6987 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6988 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6989 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006990 }
paulhu48291862021-07-14 14:53:57 +08006991 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006992 }
6993
James Mattis4fce5d12020-11-12 15:53:42 -08006994 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006995 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09006996 // As an immutable collection, mRequests cannot change by the time the
6997 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6998 // is acceptable. Use handleReleaseNetworkRequest and not directly
6999 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7000 // the app already unregistered the request.
7001 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7002 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007003 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007004
James Mattis4fce5d12020-11-12 15:53:42 -08007005 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007006 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007007 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7008 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007009 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007010 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007011 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007012 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007013 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007014 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007015 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007016 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007017 }
7018
Junyu Lai00d92df2022-07-05 11:01:52 +08007019 // Keep backward compatibility since the ServiceSpecificException is used by
7020 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7021 public static class RequestInfoPerUidCounter extends PerUidCounter {
7022 RequestInfoPerUidCounter(int maxCountPerUid) {
7023 super(maxCountPerUid);
7024 }
7025
7026 @Override
7027 public synchronized void incrementCountOrThrow(int uid) {
7028 try {
7029 super.incrementCountOrThrow(uid);
7030 } catch (IllegalStateException e) {
7031 throw new ServiceSpecificException(
7032 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7033 "Uid " + uid + " exceeded its allotted requests limit");
7034 }
7035 }
7036
7037 @Override
7038 public synchronized void decrementCountOrThrow(int uid) {
7039 throw new UnsupportedOperationException("Use decrementCount instead.");
7040 }
7041
7042 public synchronized void decrementCount(int uid) {
7043 try {
7044 super.decrementCountOrThrow(uid);
7045 } catch (IllegalStateException e) {
7046 logwtf("Exception when decrement per uid request count: ", e);
7047 }
7048 }
7049 }
7050
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007051 // This checks that the passed capabilities either do not request a
7052 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007053 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007054 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007055 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007056 throw new SecurityException("Insufficient permissions to request a specific SSID");
7057 }
paulhu1a407652019-03-22 16:35:06 +08007058
7059 if (nc.hasSignalStrength()
7060 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7061 throw new SecurityException(
7062 "Insufficient permissions to request a specific signal strength");
7063 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007064 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007065
junyulai2217bec2021-04-14 23:33:31 +08007066 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007067 enforceNetworkFactoryPermission();
7068 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007069 }
7070
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007071 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007072 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007073 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007074 // mNetworkRequests may contain the same value multiple times in case of
7075 // multilayer requests. It won't matter in this case because the thresholds
7076 // will then be the same and be deduplicated as they enter the `thresholds` set.
7077 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007078 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7079 for (final NetworkRequest req : nri.mRequests) {
7080 if (req.networkCapabilities.hasSignalStrength()
7081 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7082 thresholds.add(req.networkCapabilities.getSignalStrength());
7083 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007084 }
7085 }
7086 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007087 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007088 }
7089
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007090 private void updateSignalStrengthThresholds(
7091 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007092 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007093
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007094 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007095 String detail;
7096 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7097 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7098 } else {
7099 detail = reason;
7100 }
7101 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007102 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007103 }
7104
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007105 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007106 }
7107
Chalard Jeandd421992021-12-16 23:16:02 +09007108 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007109 if (nc == null) {
7110 return;
7111 }
7112 NetworkSpecifier ns = nc.getNetworkSpecifier();
7113 if (ns == null) {
7114 return;
7115 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007116 if (ns instanceof MatchAllNetworkSpecifier) {
7117 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7118 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007119 }
7120
Chalard Jeandd421992021-12-16 23:16:02 +09007121 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007122 ensureValidNetworkSpecifier(nc);
7123 if (nc.isPrivateDnsBroken()) {
7124 throw new IllegalArgumentException("Can't request broken private DNS");
7125 }
Chalard Jeande665262022-02-25 16:12:12 +09007126 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007127 throw new IllegalArgumentException("Can't request access UIDs");
7128 }
lucasline117e2e2019-10-22 18:27:33 +08007129 }
7130
Chalard Jeandd421992021-12-16 23:16:02 +09007131 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7132 ensureListenableCapabilities(nc);
7133 final String badCapability = nc.describeFirstNonRequestableCapability();
7134 if (badCapability != null) {
7135 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7136 }
7137 }
7138
Chiachang Wang3bc52762021-11-25 14:17:57 +08007139 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7140 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007141 private boolean isTargetSdkAtleast(int version, int callingUid,
7142 @NonNull String callingPackageName) {
7143 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007144 final PackageManager pm =
7145 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007146 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007147 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007148 if (callingVersion < version) return false;
7149 } catch (PackageManager.NameNotFoundException e) { }
7150 return true;
7151 }
7152
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007153 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007154 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007155 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007156 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007157 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007158 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007159 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7160 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007161 throw new SecurityException("Insufficient permissions to specify legacy type");
7162 }
markchienfac84a22020-03-18 21:16:15 +08007163 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007164 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007165 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007166 // Privileged callers can track the default network of another UID by passing in a UID.
7167 if (asUid != Process.INVALID_UID) {
7168 enforceSettingsPermission();
7169 } else {
7170 asUid = callingUid;
7171 }
junyulaiad010792021-01-11 16:53:38 +08007172 final NetworkRequest.Type reqType;
7173 try {
7174 reqType = NetworkRequest.Type.values()[reqTypeInt];
7175 } catch (ArrayIndexOutOfBoundsException e) {
7176 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7177 }
7178 switch (reqType) {
7179 case TRACK_DEFAULT:
7180 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007181 // is unused and will be replaced by ones appropriate for the UID (usually, the
7182 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007183 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007184 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007185 enforceAccessPermission();
7186 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007187 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007188 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007189 networkCapabilities = new NetworkCapabilities(defaultNc);
7190 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007191 case BACKGROUND_REQUEST:
7192 enforceNetworkStackOrSettingsPermission();
7193 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007194 case REQUEST:
7195 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7196 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007197 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007198 // TODO: this is incorrect. We mark the request as metered or not depending on
7199 // the state of the app when the request is filed, but we never change the
7200 // request if the app changes network state. http://b/29964605
7201 enforceMeteredApnPolicy(networkCapabilities);
7202 break;
junyulai1b1c8742021-03-12 20:05:08 +08007203 case LISTEN_FOR_BEST:
7204 enforceAccessPermission();
7205 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7206 break;
junyulaiad010792021-01-11 16:53:38 +08007207 default:
7208 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007209 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007210 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007211 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007212 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007213
junyulai1b1c8742021-03-12 20:05:08 +08007214 // Enforce FOREGROUND if the caller does not have permission to use background network.
7215 if (reqType == LISTEN_FOR_BEST) {
7216 restrictBackgroundRequestForCaller(networkCapabilities);
7217 }
7218
7219 // Set the UID range for this request to the single UID of the requester, unless the
7220 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007221 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7222 // are no visible methods to set the UIDs, an app could use reflection to try and get
7223 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007224 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007225 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7226 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007227
Etan Cohen85000162017-02-05 10:42:27 -08007228 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007229 throw new IllegalArgumentException("Bad timeout specified");
7230 }
Etan Cohen9786d922015-11-18 10:56:15 -08007231
James Mattis3ce3d3c2021-02-09 18:18:28 -08007232 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007233 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007234 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007235 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007236 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007237 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007238
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007239 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7240 // copied from the default request above. (This is necessary to ensure, for example, that
7241 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7242 // changes don't alter request matching.
7243 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7244 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007245 throw new IllegalStateException(
7246 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007247 + networkCapabilities + " vs. " + defaultNc);
7248 }
7249
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007250 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007251 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007252 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007253 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007254 }
7255 return networkRequest;
7256 }
7257
James Mattis3ce3d3c2021-02-09 18:18:28 -08007258 /**
7259 * Return the nri to be used when registering a network request. Specifically, this is used with
7260 * requests registered to track the default request. If there is currently a per-app default
7261 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7262 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007263 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7264 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007265 * @param nr the network request for the nri.
7266 * @param msgr the messenger for the nri.
7267 * @param binder the binder for the nri.
7268 * @param callingAttributionTag the calling attribution tag for the nri.
7269 * @return the nri to register.
7270 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007271 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007272 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007273 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007274 @Nullable String callingAttributionTag) {
7275 final List<NetworkRequest> requests;
7276 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7277 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007278 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007279 } else {
7280 requests = Collections.singletonList(nr);
7281 }
Roshan Pius951c0032020-12-22 15:10:42 -08007282 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007283 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007284 }
7285
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007286 private boolean shouldCheckCapabilitiesDeclaration(
7287 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7288 @NonNull final String callingPackageName) {
7289 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7290 // Only run the check if the change is enabled.
7291 if (!mDeps.isChangeEnabled(
7292 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7293 callingPackageName, user)) {
7294 return false;
7295 }
7296
7297 return networkCapabilities.hasCapability(
7298 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7299 || networkCapabilities.hasCapability(
7300 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7301 }
7302
7303 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
7304 @NonNull final NetworkCapabilities networkCapabilities) {
7305 // This check is added to fix the linter error for "current min is 30", which is not going
7306 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007307 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007308 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7309 return;
7310 }
7311 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007312 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007313 try {
7314 synchronized (mSelfCertifiedCapabilityCache) {
7315 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7316 callerPackageName);
7317 if (applicationNetworkCapabilities == null) {
7318 final PackageManager packageManager = mContext.getPackageManager();
7319 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7320 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7321 callerPackageName
7322 );
7323 final XmlResourceParser parser = packageManager
7324 .getResourcesForApplication(callerPackageName)
7325 .getXml(networkSliceProperty.getResourceId());
7326 applicationNetworkCapabilities =
7327 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7328 mSelfCertifiedCapabilityCache.put(callerPackageName,
7329 applicationNetworkCapabilities);
7330 }
7331
7332 }
7333 } catch (PackageManager.NameNotFoundException ne) {
7334 throw new SecurityException(
7335 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7336 + " property");
7337 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7338 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007339 } finally {
7340 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007341 }
7342
7343 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7344 networkCapabilities);
7345 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007346 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007347 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007348 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7349 callingPackageName)) {
7350 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7351 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007352 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007353 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7354 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7355 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7356 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007357 }
junyulai96bd9fe2022-03-08 17:36:42 +08007358 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007359 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007360 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007361 }
7362 }
7363
fenglu3f357402015-03-20 11:29:56 -07007364 @Override
fenglub00f4882015-04-21 17:12:05 -07007365 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007366 enforceAccessPermission();
7367 NetworkAgentInfo nai = null;
7368 if (network == null) {
7369 return false;
7370 }
7371 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007372 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007373 }
7374 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007375 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007376 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007377 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007378 Integer uidReqs = mBandwidthRequests.get(uid);
7379 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007380 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007381 }
7382 mBandwidthRequests.put(uid, ++uidReqs);
7383 }
fenglu3f357402015-03-20 11:29:56 -07007384 return true;
7385 }
7386 return false;
7387 }
7388
Felipe Leme0a5ae422016-06-20 16:36:29 -07007389 private boolean isSystem(int uid) {
7390 return uid < Process.FIRST_APPLICATION_UID;
7391 }
fenglu3f357402015-03-20 11:29:56 -07007392
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007393 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007394 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007395 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007396 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007397 return;
7398 }
Hugo Benichi39621362017-02-11 17:04:43 +09007399 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7400 // Policy already enforced.
7401 return;
7402 }
paulhuaf50d7d2020-12-24 19:47:34 +08007403 final long ident = Binder.clearCallingIdentity();
7404 try {
7405 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7406 // If UID is restricted, don't allow them to bring up metered APNs.
7407 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7408 }
7409 } finally {
7410 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007411 }
7412 }
7413
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007414 @Override
7415 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007416 PendingIntent operation, @NonNull String callingPackageName,
7417 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007418 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007419 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007420 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007421 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007422 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007423 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007424 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007425 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007426 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007427 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7428 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007429
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007430 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007431 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007432 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7433 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007434 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007435 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7436 nri));
7437 return networkRequest;
7438 }
7439
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007440 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7441 mHandler.sendMessageDelayed(
7442 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007443 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007444 }
7445
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007446 @Override
7447 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007448 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007449 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007450 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007451 }
7452
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007453 // In order to implement the compatibility measure for pre-M apps that call
7454 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7455 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7456 // This ensures it has permission to do so.
7457 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7458 if (nc == null) {
7459 return false;
7460 }
7461 int[] transportTypes = nc.getTransportTypes();
7462 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7463 return false;
7464 }
7465 try {
7466 mContext.enforceCallingOrSelfPermission(
7467 android.Manifest.permission.ACCESS_WIFI_STATE,
7468 "ConnectivityService");
7469 } catch (SecurityException e) {
7470 return false;
7471 }
7472 return true;
7473 }
7474
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007475 @Override
7476 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007477 Messenger messenger, IBinder binder,
7478 @NetworkCallback.Flag int callbackFlags,
7479 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007480 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007481 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7482 enforceAccessPermission();
7483 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007484
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007485 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007486 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007487 Binder.getCallingPid(), callingUid, callingPackageName);
7488 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007489 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7490 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7491 // onLost and onAvailable callbacks when networks move in and out of the background.
7492 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7493 // can't request networks.
7494 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007495 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007496
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007497 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007498 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007499 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007500 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007501 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007502 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007503
7504 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7505 return networkRequest;
7506 }
7507
7508 @Override
7509 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007510 PendingIntent operation, @NonNull String callingPackageName,
7511 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007512 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007513 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007514 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7515 enforceAccessPermission();
7516 }
Chalard Jeandd421992021-12-16 23:16:02 +09007517 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007518 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007519 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007520 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007521 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007522
7523 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007524 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007525 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7526 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007527 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007528
WeiZhang1cc3f172021-06-03 19:02:04 -05007529 mHandler.sendMessage(mHandler.obtainMessage(
7530 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007531 }
7532
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007533 /** Returns the next Network provider ID. */
7534 public final int nextNetworkProviderId() {
7535 return mNextNetworkProviderId.getAndIncrement();
7536 }
7537
Erik Kline0c04b742016-07-07 16:50:58 +09007538 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007539 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007540 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007541 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007542 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007543 }
7544
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007545 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7546 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007547 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7548 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7549 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007550 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007551 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007552 return;
7553 }
7554
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007555 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7556 mNetworkProviderInfos.put(npi.messenger, npi);
7557 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007558 }
7559
7560 @Override
7561 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007562 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007563 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007564 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007565 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007566 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7567 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007568 }
7569
7570 @Override
7571 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007572 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007573 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007574 }
7575
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007576 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007577 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007578 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7579 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007580 Objects.requireNonNull(score);
7581 Objects.requireNonNull(caps);
7582 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007583 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007584 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007585 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7586 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007587 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7588 }
7589
Chalard Jeanbb902a52021-08-18 01:35:19 +09007590 private void updateOfferScore(final NetworkOffer offer) {
7591 final boolean yieldToBadWiFi =
7592 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7593 final NetworkOffer newOffer = new NetworkOffer(
7594 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7595 offer.caps, offer.callback, offer.providerId);
7596 if (offer.equals(newOffer)) return;
7597 handleRegisterNetworkOffer(newOffer);
7598 }
7599
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007600 @Override
7601 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007602 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007603 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7604 }
7605
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007606 private void handleUnregisterNetworkProvider(Messenger messenger) {
7607 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7608 if (npi == null) {
7609 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007610 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007611 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007612 // Unregister all the offers from this provider
7613 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7614 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007615 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007616 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7617 toRemove.add(noi);
7618 }
7619 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007620 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007621 handleUnregisterNetworkOffer(noi);
7622 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007623 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007624 }
7625
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007626 @Override
James Mattisf7027322020-12-13 16:28:14 -08007627 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007628 if (request.hasTransport(TRANSPORT_TEST)) {
7629 enforceNetworkFactoryOrTestNetworksPermission();
7630 } else {
7631 enforceNetworkFactoryPermission();
7632 }
James Mattisf7027322020-12-13 16:28:14 -08007633 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7634 if (nri != null) {
7635 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7636 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7637 mHandler.post(() -> handleReleaseNetworkRequest(
7638 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7639 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007640 }
7641
Paul Jensen1f567382015-02-13 14:18:39 -05007642 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7643 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007644 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007645 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007646 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007647 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007648 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007649
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007650 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007651 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007652 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007653
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007654 // UID ranges for users that are currently blocked by VPNs.
7655 // This array is accessed and iterated on multiple threads without holding locks, so its
7656 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7657 // (on the handler thread).
7658 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7659
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007660 // Must only be accessed on the handler thread
7661 @NonNull
7662 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7663
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007664 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007665 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007666
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007667 // Current OEM network preferences. This object must only be written to on the handler thread.
7668 // Since it is immutable and always non-null, other threads may read it if they only care
7669 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007670 @NonNull
7671 private OemNetworkPreferences mOemNetworkPreferences =
7672 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007673 // Current per-profile network preferences. This object follows the same threading rules as
7674 // the OEM network preferences above.
7675 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007676 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7677 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007678
lucaslin3ba7cc22022-12-19 02:35:33 +00007679 // Current VPN network preferences. This object follows the same threading rules as the OEM
7680 // network preferences above.
7681 @NonNull
7682 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7683 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7684
paulhu51f77dc2021-06-07 02:34:20 +00007685 // A set of UIDs that should use mobile data preferentially if available. This object follows
7686 // the same threading rules as the OEM network preferences above.
7687 @NonNull
7688 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7689
James Mattiscb1e0362021-04-06 17:07:42 -07007690 // OemNetworkPreferences activity String log entries.
7691 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7692 @NonNull
7693 private final LocalLog mOemNetworkPreferencesLogs =
7694 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7695
James Mattis02220e22021-03-13 19:27:21 -08007696 /**
7697 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7698 * @param packageName the package name to check existence of a mapping for.
7699 * @return true if a mapping exists, false otherwise
7700 */
7701 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7702 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7703 }
7704
James Mattise3ef1912020-12-20 11:09:58 -08007705 // The always-on request for an Internet-capable network that apps without a specific default
7706 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007707 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007708 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007709 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007710 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007711 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007712 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007713 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007714
James Mattisd31bdfa2020-12-23 16:37:26 -08007715 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7716 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7717 }
7718
7719 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007720 * Return the default network request currently tracking the given uid.
7721 * @param uid the uid to check.
7722 * @return the NetworkRequestInfo tracking the given uid.
7723 */
7724 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007725 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007726 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007727 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007728 // Checking the first request is sufficient as only multilayer requests will have more
7729 // than one request and for multilayer, all requests will track the same uids.
7730 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007731 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007732 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007733 highestPriorityNri = nri;
7734 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007735 }
7736 }
paulhuaa0743d2021-05-26 21:56:03 +08007737 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007738 }
7739
7740 /**
7741 * Get a copy of the network requests of the default request that is currently tracking the
7742 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007743 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7744 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007745 * @param requestorUid the uid to check the default for.
7746 * @param requestorPackageName the requestor's package name.
7747 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7748 */
7749 @NonNull
7750 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007751 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007752 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007753 getDefaultRequestTrackingUid(asUid).mRequests,
7754 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007755 }
7756
7757 /**
7758 * Copy the given nri's NetworkRequest collection.
7759 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007760 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7761 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007762 * @param requestorUid the uid to set on the copied collection.
7763 * @param requestorPackageName the package name to set on the copied collection.
7764 * @return the copied NetworkRequest collection.
7765 */
7766 @NonNull
7767 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007768 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7769 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007770 final List<NetworkRequest> requests = new ArrayList<>();
7771 for (final NetworkRequest nr : requestsToCopy) {
7772 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007773 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007774 nr.legacyType, nextNetworkRequestId(), nr.type));
7775 }
7776 return requests;
7777 }
7778
7779 @NonNull
7780 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007781 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7782 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007783 // These capabilities are for a TRACK_DEFAULT callback, so:
7784 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7785 // mDefaultRequest and a per-UID default request.
7786 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007787 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007788 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007789 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7790 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007791 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007792 restrictRequestUidsForCallerAndSetRequestorInfo(
7793 netCap, requestorUid, requestorPackageName);
7794 return netCap;
7795 }
7796
7797 /**
7798 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7799 * @param nr the network request to check for equality against.
7800 * @return the nri if one exists, null otherwise.
7801 */
7802 @Nullable
7803 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7804 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7805 if (nri.getNetworkRequestForCallback().equals(nr)) {
7806 return nri;
7807 }
7808 }
7809 return null;
7810 }
7811
7812 /**
7813 * Check if an nri is currently being managed by per-app default networking.
7814 * @param nri the nri to check.
7815 * @return true if this nri is currently being managed by per-app default networking.
7816 */
7817 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7818 // nri.mRequests.get(0) is only different from the original request filed in
7819 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7820 // functionality therefore if these two don't match, it means this particular nri is
7821 // currently being managed by a per-app default.
7822 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7823 }
7824
7825 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007826 * Determine if an nri is a managed default request that disallows default networking.
7827 * @param nri the request to evaluate
7828 * @return true if device-default networking is disallowed
7829 */
7830 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7831 // Check if this nri is a managed default that supports the default network at its
7832 // lowest priority request.
7833 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7834 final NetworkCapabilities lowestPriorityNetCap =
7835 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7836 return isPerAppDefaultRequest(nri)
7837 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7838 lowestPriorityNetCap));
7839 }
7840
Erik Kline05f2b402015-04-30 12:58:40 +09007841 // Request used to optionally keep mobile data active even when higher
7842 // priority networks like Wi-Fi are active.
7843 private final NetworkRequest mDefaultMobileDataRequest;
7844
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007845 // Request used to optionally keep wifi data active even when higher
7846 // priority networks like ethernet are active.
7847 private final NetworkRequest mDefaultWifiRequest;
7848
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007849 // Request used to optionally keep vehicle internal network always active
7850 private final NetworkRequest mDefaultVehicleRequest;
7851
James Mattisd31bdfa2020-12-23 16:37:26 -08007852 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7853 // network with no service. This NAI should never be matched against, nor should any public API
7854 // ever return the associated network. For this reason, this NAI is not in the list of available
7855 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7856 // default requests that don't support using the device default network which will ultimately
7857 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7858 @VisibleForTesting
7859 final NetworkAgentInfo mNoServiceNetwork;
7860
Chalard Jean5b409c72021-02-04 13:12:59 +09007861 // The NetworkAgentInfo currently satisfying the default request, if any.
7862 private NetworkAgentInfo getDefaultNetwork() {
7863 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007864 }
7865
James Mattis2516da32021-01-31 17:06:19 -08007866 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007867 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007868 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7869 // Currently, all network requests will have the same uids therefore checking the first
7870 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007871 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007872 if (null == uids) {
7873 continue;
7874 }
7875 for (final UidRange range : uids) {
7876 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007877 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007878 highestPriorityNri = nri;
7879 }
James Mattis2516da32021-01-31 17:06:19 -08007880 }
7881 }
7882 }
paulhuaa0743d2021-05-26 21:56:03 +08007883 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007884 }
7885
Varun Ananddf569952019-02-06 10:13:38 -08007886 @Nullable
7887 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7888 return nai != null ? nai.network : null;
7889 }
7890
7891 private void ensureRunningOnConnectivityServiceThread() {
7892 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7893 throw new IllegalStateException(
7894 "Not running on ConnectivityService thread: "
7895 + Thread.currentThread().getName());
7896 }
7897 }
7898
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007899 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007900 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7901 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007902 }
7903
Chalard Jean29d06db2018-05-02 21:14:54 +09007904 /**
7905 * Register a new agent with ConnectivityService to handle a network.
7906 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007907 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007908 * @param networkInfo the initial info associated with this network. It can be updated later :
7909 * see {@link #updateNetworkInfo}.
7910 * @param linkProperties the initial link properties of this network. They can be updated
7911 * later : see {@link #updateLinkProperties}.
7912 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007913 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007914 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007915 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007916 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007917 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007918 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007919 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007920 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007921 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7922 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007923 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7924 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7925 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007926 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007927 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007928 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08007929 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007930 } else {
7931 enforceNetworkFactoryPermission();
7932 }
7933
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007934 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007935 final long token = Binder.clearCallingIdentity();
7936 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007937 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007938 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007939 } finally {
7940 Binder.restoreCallingIdentity(token);
7941 }
7942 }
7943
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007944 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007945 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007946 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7947 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007948
Chalard Jeandbc46952022-02-02 00:14:18 +09007949 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
7950 // and mutate them at any time.
7951 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
7952 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
7953 final LinkProperties lpCopy = new LinkProperties(linkProperties);
7954
Chalard Jean366c5252022-01-25 18:27:53 +09007955 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09007956 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09007957 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7958 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007959 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09007960 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007961 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007962 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7963 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007964
Chalard Jeandbc46952022-02-02 00:14:18 +09007965 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09007966 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007967 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007968 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007969 mDeps.getNetworkStack().makeNetworkMonitor(
7970 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007971 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7972 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007973 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007974 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007975 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007976 }
7977
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007978 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007979 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007980 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09007981 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007982 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09007983 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
7984 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
7985 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09007986
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007987 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007988
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007989 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007990 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007991 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007992 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007993
7994 try {
7995 networkMonitor.start();
7996 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007997 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007998 }
Chalard Jean366c5252022-01-25 18:27:53 +09007999
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008000 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008001 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008002 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008003 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008004 }
8005
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008006 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8007 @NonNull public final NetworkOffer offer;
8008
8009 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8010 this.offer = offer;
8011 }
8012
8013 @Override
8014 public void binderDied() {
8015 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8016 }
8017 }
8018
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008019 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8020 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8021 if (npi.providerId == providerId) return true;
8022 }
8023 return false;
8024 }
8025
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008026 /**
8027 * Register or update a network offer.
8028 * @param newOffer The new offer. If the callback member is the same as an existing
8029 * offer, it is an update of that offer.
8030 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008031 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008032 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8033 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008034 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008035 // This may actually happen if a provider updates its score or registers and then
8036 // immediately unregisters. The offer would still be in the handler queue, but the
8037 // provider would have been removed.
8038 if (DBG) log("Received offer from an unregistered provider");
8039 return;
8040 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008041 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8042 if (null != existingOffer) {
8043 handleUnregisterNetworkOffer(existingOffer);
8044 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008045 if (DBG) {
8046 // handleUnregisterNetworkOffer has already logged the old offer
8047 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8048 }
8049 } else {
8050 if (DBG) {
8051 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8052 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008053 }
8054 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8055 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008056 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008057 } catch (RemoteException e) {
8058 noi.binderDied();
8059 return;
8060 }
8061 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008062 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008063 }
8064
8065 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8066 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008067 if (DBG) {
8068 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8069 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008070
8071 // If the provider removes the offer and dies immediately afterwards this
8072 // function may be called twice in a row, but the array will no longer contain
8073 // the offer.
8074 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008075 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008076 }
8077
8078 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8079 @NonNull final INetworkOfferCallback callback) {
8080 ensureRunningOnConnectivityServiceThread();
8081 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008082 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008083 }
8084 return null;
8085 }
8086
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008087 /**
8088 * Called when receiving LinkProperties directly from a NetworkAgent.
8089 * Stores into |nai| any data coming from the agent that might also be written to the network's
8090 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8091 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008092 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008093 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008094 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8095 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008096 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008097 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008098 }
8099
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008100 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008101 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008102 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008103
Lorenzo Colittid523d142020-04-01 20:16:30 +09008104 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8105 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8106 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008107 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008108
Suprabh Shukla1e312032023-01-24 03:36:37 -08008109 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008110
8111 // update filtering rules, need to happen after the interface update so netd knows about the
8112 // new interface (the interface name -> index map becomes initialized)
8113 updateVpnFiltering(newLp, oldLp, networkAgent);
8114
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008115 updateMtu(newLp, oldLp);
8116 // TODO - figure out what to do for clat
8117// for (LinkProperties lp : newLp.getStackedLinks()) {
8118// updateMtu(lp, null);
8119// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008120 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008121 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008122 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8123 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008124
Erik Klineb9888902016-04-05 13:30:49 +09008125 updateRoutes(newLp, oldLp, netId);
8126 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008127 // Make sure LinkProperties represents the latest private DNS status.
8128 // This does not need to be done before updateDnses because the
8129 // LinkProperties are not the source of the private DNS configuration.
8130 // updateDnses will fetch the private DNS configuration from DnsManager.
8131 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008132
Chalard Jean5b409c72021-02-04 13:12:59 +09008133 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008134 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008135 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008136 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008137 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008138
8139 updateWakeOnLan(newLp);
8140
Hai Shalome58bdc62021-01-11 18:45:34 -08008141 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8142 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8143 // does, it needs to be merged here.
8144 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8145 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008146
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008147 // TODO - move this check to cover the whole function
8148 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008149 synchronized (networkAgent) {
8150 networkAgent.linkProperties = newLp;
8151 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008152 // Start or stop DNS64 detection and 464xlat according to network state.
8153 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008154 // Notify NSS when relevant events happened. Currently, NSS only cares about
8155 // interface changed to update clat interfaces accounting.
8156 final boolean interfacesChanged = oldLp == null
8157 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8158 if (interfacesChanged) {
8159 notifyIfacesChangedForNetworkStats();
8160 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008161 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8162 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008163 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008164 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008165
8166 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008167 }
8168
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008169 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8170 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8171 }
8172
Hai Shalome58bdc62021-01-11 18:45:34 -08008173 /**
8174 * @param naData captive portal data from NetworkAgent
8175 * @param apiData captive portal data from capport API
8176 */
8177 @Nullable
8178 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8179 CaptivePortalData apiData) {
8180 if (naData == null || apiData == null) {
8181 return naData == null ? apiData : naData;
8182 }
8183 final CaptivePortalData.Builder captivePortalBuilder =
8184 new CaptivePortalData.Builder(naData);
8185
8186 if (apiData.isCaptive()) {
8187 captivePortalBuilder.setCaptive(true);
8188 }
8189 if (apiData.isSessionExtendable()) {
8190 captivePortalBuilder.setSessionExtendable(true);
8191 }
8192 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8193 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8194 // otherwise data would be inconsistent. Prefer the capport API info if present,
8195 // as it can generally be refreshed more often.
8196 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8197 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8198 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8199 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8200 // No source has time / bytes remaining information: surface the newest refresh time
8201 // for other fields
8202 captivePortalBuilder.setRefreshTime(
8203 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8204 }
8205
Hai Shalom7c6ab402021-02-04 19:34:06 -08008206 // Prioritize the user portal URL from the network agent if the source is authenticated.
8207 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8208 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8209 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8210 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008211 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008212 // Prioritize the venue information URL from the network agent if the source is
8213 // authenticated.
8214 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8215 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8216 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8217 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008218 }
8219 return captivePortalBuilder.build();
8220 }
8221
Suprabh Shukla53e16392023-04-26 18:47:36 -07008222 @VisibleForTesting
8223 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008224 // This needs to be kept in sync and backwards compatible with the decoding logic in
8225 // NetdEventListenerService, which is non-mainline code.
8226 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8227 }
8228
Suprabh Shukla75642282023-04-25 23:15:43 -07008229 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8230 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8231 return true;
8232 }
8233 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8234 return true;
8235 }
8236 return false;
8237 }
8238
Suprabh Shukla1e312032023-01-24 03:36:37 -08008239 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008240 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008241 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008242 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008243 return;
8244 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008245
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008246 // Mask/mark of zero will not detect anything interesting.
8247 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008248 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008249 return;
8250 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008251
Suprabh Shukla1e312032023-01-24 03:36:37 -08008252 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008253 try {
8254 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008255 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008256 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008257 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008258 }
8259 } catch (Exception e) {
8260 loge("Exception modifying wakeup packet monitoring: " + e);
8261 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008262 }
8263
Junyu Lai970963e2022-10-25 15:46:47 +08008264 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008265 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008266 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008267 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008268 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008269 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008270 for (final String iface : interfaceDiff.added) {
8271 try {
8272 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008273 mNetd.networkAddInterface(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008274 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008275 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008276 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008277 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008278 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008279 }
Paul Jensenbff73492014-04-28 10:33:11 -04008280 }
8281 }
Chalard Jean9589e722019-11-19 19:03:53 +09008282 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008283 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008284 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008285 wakeupModifyInterface(iface, nai, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008286 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008287 } catch (Exception e) {
8288 loge("Exception removing interface: " + e);
8289 }
8290 }
8291 }
8292
Tyler Weare4314862019-12-05 14:55:30 -08008293 // TODO: move to frameworks/libs/net.
8294 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
8295 final String nextHop;
8296
8297 switch (route.getType()) {
8298 case RouteInfo.RTN_UNICAST:
8299 if (route.hasGateway()) {
8300 nextHop = route.getGateway().getHostAddress();
8301 } else {
8302 nextHop = INetd.NEXTHOP_NONE;
8303 }
8304 break;
8305 case RouteInfo.RTN_UNREACHABLE:
8306 nextHop = INetd.NEXTHOP_UNREACHABLE;
8307 break;
8308 case RouteInfo.RTN_THROW:
8309 nextHop = INetd.NEXTHOP_THROW;
8310 break;
8311 default:
8312 nextHop = INetd.NEXTHOP_NONE;
8313 break;
8314 }
8315
8316 final RouteInfoParcel rip = new RouteInfoParcel();
8317 rip.ifName = route.getInterface();
8318 rip.destination = route.getDestination().toString();
8319 rip.nextHop = nextHop;
8320 rip.mtu = route.getMtu();
8321
8322 return rip;
8323 }
8324
Paul Jensene0fd4a82014-08-06 15:51:33 -04008325 /**
8326 * Have netd update routes from oldLp to newLp.
8327 * @return true if routes changed between oldLp and newLp
8328 */
Junyu Lai970963e2022-10-25 15:46:47 +08008329 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8330 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008331 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008332 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8333 new CompareOrUpdateResult<>(
8334 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008335 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008336 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008337
8338 // add routes before removing old in case it helps with continuous connectivity
8339
Chalard Jean9dd11612018-06-04 16:52:49 +09008340 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008341 for (RouteInfo route : routeDiff.added) {
8342 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008343 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008344 try {
Tyler Weare4314862019-12-05 14:55:30 -08008345 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008346 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008347 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008348 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008349 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008350 }
8351 }
8352 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008353 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008354 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008355 try {
Tyler Weare4314862019-12-05 14:55:30 -08008356 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008357 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008358 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008359 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008360 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008361 }
8362 }
8363
8364 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008365 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008366 try {
Tyler Weare4314862019-12-05 14:55:30 -08008367 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008368 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08008369 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008370 }
8371 }
Tyler Weare4314862019-12-05 14:55:30 -08008372
8373 for (RouteInfo route : routeDiff.updated) {
8374 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8375 try {
8376 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
8377 } catch (Exception e) {
8378 loge("Exception in networkUpdateRouteParcel: " + e);
8379 }
8380 }
8381 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8382 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008383 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008384
Junyu Lai970963e2022-10-25 15:46:47 +08008385 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8386 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008387 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8388 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008389 }
Erik Klineb9888902016-04-05 13:30:49 +09008390
Erik Kline31b4a9e2018-01-11 21:07:29 +09008391 if (DBG) {
8392 final Collection<InetAddress> dnses = newLp.getDnsServers();
8393 log("Setting DNS servers for network " + netId + " to " + dnses);
8394 }
Erik Klineb9888902016-04-05 13:30:49 +09008395 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008396 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008397 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008398 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008399 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008400 }
Erik Kline54e35c02017-04-07 15:29:29 +09008401 }
8402
Junyu Lai970963e2022-10-25 15:46:47 +08008403 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8404 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008405 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8406 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008407 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8408 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008409
8410 if (!wasFiltering && !needsFiltering) {
8411 // Nothing to do.
8412 return;
8413 }
8414
8415 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8416 // Nothing changed.
8417 return;
8418 }
8419
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008420 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008421 if (ranges == null || ranges.isEmpty()) {
8422 return;
8423 }
8424
Qingxi Libb8da982020-01-17 17:54:27 -08008425 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008426 // TODO: this create a window of opportunity for apps to receive traffic between the time
8427 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008428 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008429 // old rules are being removed.
8430 if (wasFiltering) {
8431 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8432 }
8433 if (needsFiltering) {
8434 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8435 }
8436 }
8437
Valentin Iftime9fa35092019-09-24 13:32:13 +02008438 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008439 if (mWolSupportedInterfaces == null) {
8440 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008441 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008442 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008443 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8444 }
8445
Luke Huangb913c812018-08-24 20:33:16 +08008446 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008447 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008448 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008449 }
8450 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008451 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008452 }
Luke Huangb913c812018-08-24 20:33:16 +08008453 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008454 }
8455
Chalard Jean62edfd82019-12-02 18:39:29 +09008456 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8457 @NonNull final NetworkCapabilities newNc) {
8458 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8459 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008460 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008461 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008462 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008463 } catch (RemoteException | ServiceSpecificException e) {
8464 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008465 }
8466 }
8467 }
8468
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008469 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008470 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008471 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008472 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008473 underlyingNetworks = underlyingNetworksOrDefault(
8474 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008475 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008476 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8477 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008478 // metered if any underlying is metered, or originally declared metered by the agent.
8479 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008480 boolean roaming = false; // roaming if any underlying is roaming
8481 boolean congested = false; // congested if any underlying is congested
8482 boolean suspended = true; // suspended if all underlying are suspended
8483
8484 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008485 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008486 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008487 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008488 for (Network underlyingNetwork : underlyingNetworks) {
8489 final NetworkAgentInfo underlying =
8490 getNetworkAgentInfoForNetwork(underlyingNetwork);
8491 if (underlying == null) continue;
8492
8493 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8494 hadUnderlyingNetworks = true;
8495 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008496 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008497 }
8498
8499 // Merge capabilities of this underlying network. For bandwidth, assume the
8500 // worst case.
8501 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8502 underlyingCaps.getLinkDownstreamBandwidthKbps());
8503 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8504 underlyingCaps.getLinkUpstreamBandwidthKbps());
8505 // If this underlying network is metered, the VPN is metered (it may cost money
8506 // to send packets on this network).
8507 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8508 // If this underlying network is roaming, the VPN is roaming (the billing structure
8509 // is different than the usual, local one).
8510 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8511 // If this underlying network is congested, the VPN is congested (the current
8512 // condition of the network affects the performance of this network).
8513 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8514 // If this network is not suspended, the VPN is not suspended (the VPN
8515 // is able to transfer some data).
8516 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008517 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008518 }
8519 }
8520 if (!hadUnderlyingNetworks) {
8521 // No idea what the underlying networks are; assume reasonable defaults
8522 metered = true;
8523 roaming = false;
8524 congested = false;
8525 suspended = false;
8526 }
8527
Chalard Jean1d420b32022-10-12 16:39:37 +09008528 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008529 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8530 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8531 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8532 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8533 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8534 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008535 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008536 }
8537
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008538 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008539 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8540 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8541 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008542 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008543 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008544 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008545 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008546 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8547 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008548 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008549 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008550 if (nai.everConnected()
8551 && !nai.isVPN()
8552 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008553 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008554 // does not cause any request (that is not a listen) currently matching that agent to
8555 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008556 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008557 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008558 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008559 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008560 }
8561
Paul Jensen53f08952015-06-16 14:27:36 -04008562 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008563 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008564 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008565 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008566 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008567 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008568 }
Chalard Jean254bd162022-08-25 13:04:51 +09008569 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008570 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008571 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008572 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008573 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008574 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008575 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008576 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008577 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008578 }
Chalard Jean254bd162022-08-25 13:04:51 +09008579 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008580 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8581 } else {
8582 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8583 }
lucasline117e2e2019-10-22 18:27:33 +08008584 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008585
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008586 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008587 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8588 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008589 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008590 }
8591
Lorenzo Colittibd079452021-07-02 11:47:57 +09008592 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008593 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008594 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008595 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008596 }
8597
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008598 return newNc;
8599 }
8600
Lorenzo Colitti44840702021-01-11 22:27:57 +09008601 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8602 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8603 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8604 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8605 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8606 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8607 if (prevSuspended != suspended) {
8608 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8609 // onResumed have been removed.
8610 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8611 : ConnectivityManager.CALLBACK_RESUMED);
8612 }
8613 if (prevSuspended != suspended || prevRoaming != roaming) {
8614 // updateNetworkInfo will mix in the suspended info from the capabilities and
8615 // take appropriate action for the network having possibly changed state.
8616 updateNetworkInfo(nai, nai.networkInfo);
8617 }
8618 }
8619
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008620 /**
8621 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8622 *
8623 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8624 * capabilities we manage and store in {@code nai}, such as validated status and captive
8625 * portal status)
8626 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8627 * potentially triggers rematches.
8628 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8629 * change.)
8630 *
8631 * @param oldScore score of the network before any of the changes that prompted us
8632 * to call this function.
8633 * @param nai the network having its capabilities updated.
8634 * @param nc the new network capabilities.
8635 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008636 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008637 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008638 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008639 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008640 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8641 if (null != differences) {
8642 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8643 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008644 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008645 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008646
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008647 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008648 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008649 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008650
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008651 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008652 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8653 // the change we're processing can't affect any requests, it can only affect the listens
8654 // on this network. We might have been called by rematchNetworkAndRequests when a
8655 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008656 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008657 } else {
8658 // If the requestable capabilities have changed or the score changed, we can't have been
8659 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008660 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008661 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008662 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008663 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008664
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008665 final boolean oldMetered = prevNc.isMetered();
8666 final boolean newMetered = newNc.isMetered();
8667 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008668
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008669 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008670 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8671 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008672 }
junyulaif2c67e42018-08-07 19:50:45 +08008673
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008674 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8675 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008676
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008677 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008678 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008679 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008680 }
8681
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008682 // This network might have been underlying another network. Propagate its capabilities.
8683 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008684
8685 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008686 mDnsManager.updateTransportsForNetwork(
8687 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008688 }
lucaslin53e8a262021-06-08 01:43:59 +08008689
8690 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008691 }
8692
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008693 /** Convenience method to update the capabilities for a given network. */
8694 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008695 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008696 }
8697
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008698 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008699 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008700 *
8701 * Ingress interface filtering enforces that all apps under the given network can only receive
8702 * packets from the network's interface (and loopback). This is important for VPNs because
8703 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8704 * non-VPN interfaces.
8705 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008706 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008707 * 1. the network is an app VPN (not legacy VPN)
8708 * 2. the VPN does not allow bypass
8709 * 3. the VPN is fully-routed
8710 * 4. the VPN interface is non-null
8711 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008712 * @see INetd#firewallAddUidInterfaceRules
8713 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008714 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008715 @Nullable
8716 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008717 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008718 if (nc == null || lp == null) return null;
8719 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008720 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008721 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008722 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008723 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008724 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008725 && !lp.hasExcludeRoute()) {
8726 return lp.getInterfaceName();
8727 }
8728 return null;
8729 }
8730
8731 /**
8732 * Returns whether we need to set interface filtering rule or not
8733 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008734 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008735 String isolationIface) {
8736 // Allow rules are always needed if VPN isolation is enabled.
8737 if (isolationIface != null) return true;
8738
8739 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8740 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8741 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09008742 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008743 }
8744
Chiachang Wang28afaff2020-12-10 22:24:47 +08008745 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8746 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8747 int index = 0;
8748 for (UidRange range : ranges) {
8749 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8750 index++;
8751 }
8752 return stableRanges;
8753 }
8754
Chalard Jeane6c95272022-01-25 21:04:21 +09008755 private static UidRangeParcel[] intsToUidRangeStableParcels(
8756 final @NonNull ArraySet<Integer> uids) {
8757 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8758 int index = 0;
8759 for (int uid : uids) {
8760 stableRanges[index] = new UidRangeParcel(uid, uid);
8761 index++;
8762 }
8763 return stableRanges;
8764 }
8765
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008766 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8767 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8768 for (int i = 0; i < ranges.length; i++) {
8769 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8770 }
8771 return stableRanges;
8772 }
8773
Motomu Utsumi93a22182023-03-16 17:04:21 +09008774 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09008775 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08008776 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8777 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09008778 if (mDeps.isAtLeastU()) {
8779 final Set<Integer> exemptUidSet = new ArraySet<>();
8780 for (final int uid: exemptUids) {
8781 exemptUidSet.add(uid);
8782 }
8783 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
8784 } else {
8785 mNetd.socketDestroy(uidRangeParcels, exemptUids);
8786 }
Ken Chen5e65a852020-12-24 12:59:10 +08008787 } catch (Exception e) {
8788 loge("Exception in socket destroy: ", e);
8789 }
8790 }
8791 }
8792
paulhuaa0743d2021-05-26 21:56:03 +08008793 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09008794 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08008795 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8796 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8797 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09008798 exemptUids[0] = VPN_UID;
8799 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08008800 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8801
Motomu Utsumi6345e462023-03-13 13:24:50 +09008802 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09008803 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008804 try {
8805 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008806 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008807 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008808 } else {
paulhu0e79d952021-06-09 16:11:35 +08008809 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008810 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008811 }
8812 } catch (Exception e) {
8813 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8814 " on netId " + nai.network.netId + ". " + e);
8815 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09008816 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09008817 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008818 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008819
lucaslin53e8a262021-06-08 01:43:59 +08008820 private boolean isProxySetOnAnyDefaultNetwork() {
8821 ensureRunningOnConnectivityServiceThread();
8822 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8823 final NetworkAgentInfo nai = nri.getSatisfier();
8824 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8825 return true;
8826 }
8827 }
8828 return false;
8829 }
8830
8831 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8832 NetworkCapabilities newNc) {
8833 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8834 // the proxy might be changed since the default network satisfied by the apps might also
8835 // changed.
8836 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8837 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008838 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8839 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008840 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008841 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8842 mProxyTracker.sendProxyBroadcast();
8843 }
8844 }
8845
Chalard Jeane6c95272022-01-25 21:04:21 +09008846 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8847 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008848 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8849 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008850 if (null == prevRanges) prevRanges = new ArraySet<>();
8851 if (null == newRanges) newRanges = new ArraySet<>();
8852 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8853
8854 prevRanges.removeAll(newRanges);
8855 newRanges.removeAll(prevRangesCopy);
8856
8857 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008858 // When updating the VPN uid routing rules, add the new range first then remove the old
8859 // range. If old range were removed first, there would be a window between the old
8860 // range being removed and the new range being added, during which UIDs contained
8861 // in both ranges are not subject to any VPN routing rules. Adding new range before
8862 // removing old range works because, unlike the filtering rules below, it's possible to
8863 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008864 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8865 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8866 // [1-5] & [1-2],[4-5] == [3]
8867 // Then we can do:
8868 // maybeCloseSockets([3])
8869 // mNetd.networkAddUidRanges([1-2],[4-5])
8870 // mNetd.networkRemoveUidRanges([1-5])
8871 // maybeCloseSockets([3])
8872 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8873 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008874 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008875 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008876 }
8877 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008878 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008879 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00008880 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
8881 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008882 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
8883 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008884 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008885 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008886 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8887 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8888 // were added first and then newRanges got removed later, there would be only one uid
8889 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8890 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8891 // Note that this is in contrast with the (more robust) update of VPN routing rules
8892 // above, where the addition of new ranges happens before the removal of old ranges.
8893 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8894 // to be removed will never overlap with the new range to be added.
8895 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008896 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
8897 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008898 }
8899 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008900 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008901 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008902 } catch (Exception e) {
8903 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008904 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008905 }
8906 }
8907
Chalard Jeande665262022-02-25 16:12:12 +09008908 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09008909 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8910 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09008911 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
8912 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09008913 if (prevEmpty && newEmpty) return;
8914
8915 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09008916 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008917 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09008918 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008919
8920 if (prevUids.equals(newUids)) return;
8921
8922 // This implementation is very simple and vastly faster for sets of Integers than
8923 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8924 // a key computed from the value and has storage for that.
8925 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8926 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8927 toRemove.removeAll(newUids);
8928 toAdd.removeAll(prevUids);
8929
8930 try {
8931 if (!toAdd.isEmpty()) {
8932 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8933 nai.network.netId,
8934 intsToUidRangeStableParcels(toAdd),
8935 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8936 }
8937 if (!toRemove.isEmpty()) {
8938 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8939 nai.network.netId,
8940 intsToUidRangeStableParcels(toRemove),
8941 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8942 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008943 } catch (ServiceSpecificException e) {
8944 // Has the interface disappeared since the network was built ?
8945 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008946 } catch (RemoteException e) {
8947 // Netd died. This usually causes a runtime restart anyway.
8948 }
8949 }
8950
Junyu Lai2ed7d412022-10-07 16:52:21 +08008951 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
8952 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008953 ensureRunningOnConnectivityServiceThread();
8954
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008955 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008956 // Ignore updates for disconnected networks
8957 return;
8958 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008959 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008960 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09008961 + "; created=" + nai.getCreatedTime()
8962 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00008963 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008964 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8965 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008966 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008967 }
8968
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008969 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8970 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008971 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008972 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008973 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008974 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8975 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8976 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008977 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8978 // need to be sent as a separate extra.
8979 final NetworkRequest req = nri.isMultilayerRequest()
8980 ? nri.getActiveRequest()
8981 // Non-multilayer listen requests do not have an active request
8982 : nri.mRequests.get(0);
8983 if (req == null) {
8984 Log.wtf(TAG, "No request in NRI " + nri);
8985 }
8986 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008987 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008988 sendIntent(nri.mPendingIntent, intent);
8989 }
8990 // else not handled
8991 }
8992
Michael Groover73f69482023-01-27 11:01:25 -06008993 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
8994 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008995 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8996 mPendingIntentWakeLock.acquire();
8997 try {
8998 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00008999 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009000 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009001 // Explicitly disallow the receiver from starting activities, to prevent apps from
9002 // utilizing the PendingIntent as a backdoor to do this.
9003 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9004 }
9005 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9006 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009007 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009008 } catch (PendingIntent.CanceledException e) {
9009 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9010 mPendingIntentWakeLock.release();
9011 releasePendingNetworkRequest(pendingIntent);
9012 }
9013 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9014 }
9015
9016 @Override
9017 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9018 String resultData, Bundle resultExtras) {
9019 if (DBG) log("Finished sending " + pendingIntent);
9020 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009021 // Release with a delay so the receiving client has an opportunity to put in its
9022 // own request.
9023 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009024 }
9025
Chalard Jean46bfbf02022-02-02 00:56:25 +09009026 // networkAgent is only allowed to be null if notificationType is
9027 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9028 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009029 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009030 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009031 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009032 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009033 // Default request has no msgr. Also prevents callbacks from being invoked for
9034 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9035 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9036 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009037 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009038 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009039 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009040 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009041 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009042 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009043 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009044 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9045 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009046 }
Roshan Pius951c0032020-12-22 15:10:42 -08009047 final boolean includeLocationSensitiveInfo =
9048 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009049 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009050 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009051 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009052 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009053 networkCapabilitiesRestrictedForCallerPermissions(
9054 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9055 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009056 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009057 nri.mCallingAttributionTag);
9058 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009059 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9060 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08009061 // For this notification, arg1 contains the blocked status.
9062 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009063 break;
9064 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009065 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009066 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009067 break;
9068 }
9069 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009070 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009071 final NetworkCapabilities netCap =
9072 networkCapabilitiesRestrictedForCallerPermissions(
9073 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9074 putParcelable(
9075 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009076 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009077 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009078 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009079 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009080 break;
9081 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009082 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009083 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9084 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009085 break;
9086 }
junyulaif2c67e42018-08-07 19:50:45 +08009087 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009088 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009089 msg.arg1 = arg1;
9090 break;
9091 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009092 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009093 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009094 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009095 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009096 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009097 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009098 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009099 }
James Mattis45d81842021-01-10 14:24:24 -08009100 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009101 } catch (RemoteException e) {
9102 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009103 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009104 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009105 }
9106
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009107 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9108 bundle.putParcelable(t.getClass().getSimpleName(), t);
9109 }
9110
Chalard Jean0702f982021-09-16 21:50:07 +09009111 /**
9112 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9113 *
9114 * When a request should be assigned to a new network, it is normally lingered to give
9115 * time for apps to gracefully migrate their connections. When both networks are on the same
9116 * radio, but that radio can't do time-sharing efficiently, this may end up being
9117 * counter-productive because any traffic on the old network may drastically reduce the
9118 * performance of the new network.
9119 * The stack supports a configuration to let modem vendors state that their radio can't
9120 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9121 * from one cell network to another can't be done gracefully.
9122 *
9123 * @param oldNai the old network serving the request
9124 * @param newNai the new network serving the request
9125 * @return whether the switch can be graceful
9126 */
9127 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9128 @NonNull final NetworkAgentInfo newSatisfier) {
9129 if (mCellularRadioTimesharingCapable) return true;
9130 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9131 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9132 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9133 }
9134
Paul Jensenaf94b982014-09-30 15:37:41 -04009135 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009136 if (nai.numRequestNetworkRequests() != 0) {
9137 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9138 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009139 // Ignore listening and track default requests.
9140 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009141 loge("Dead network still had at least " + nr);
9142 break;
9143 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009144 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009145 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009146 }
9147
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009148 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9149 if (oldNetwork == null) {
9150 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9151 return;
9152 }
Chalard Jean49707572019-12-10 21:07:02 +09009153 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009154
9155 // If we get here it means that the last linger timeout for this network expired. So there
9156 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009157 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009158
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009159 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009160 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009161 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009162 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009163 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009164 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009165 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009166 }
9167
James Mattise3ef1912020-12-20 11:09:58 -08009168 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9169 boolean isDefaultChanged = false;
9170 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9171 final NetworkReassignment.RequestReassignment reassignment =
9172 changes.getReassignment(defaultRequestInfo);
9173 if (null == reassignment) {
9174 continue;
9175 }
9176 // reassignment only contains those instances where the satisfying network changed.
9177 isDefaultChanged = true;
9178 // Notify system services of the new default.
9179 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9180 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009181
James Mattise3ef1912020-12-20 11:09:58 -08009182 if (isDefaultChanged) {
9183 // Hold a wakelock for a short time to help apps in migrating to a new default.
9184 scheduleReleaseNetworkTransitionWakelock();
9185 }
9186 }
9187
Aaron Huang9fe47be2021-06-08 13:11:45 +08009188 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9189 if (null == oldDefaultNetwork) return;
9190 // The network stopped being the default. If it was using a PAC proxy, then the
9191 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9192 // to the local proxy server, which would forward them over the newly default network.
9193 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9194 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9195 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9196 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9197 }
9198
James Mattise3ef1912020-12-20 11:09:58 -08009199 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9200 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9201 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9202 if (DBG) {
9203 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9204 }
Chalard Jean8e382112019-12-03 20:45:30 +09009205
James Mattisd31bdfa2020-12-23 16:37:26 -08009206 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9207 if (newDefaultNetwork != null) {
9208 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009209 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009210
James Mattisd31bdfa2020-12-23 16:37:26 -08009211 // Set an app level managed default and return since further processing only applies to the
9212 // default network.
9213 if (mDefaultRequest != nri) {
9214 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9215 return;
9216 }
9217
9218 makeDefaultNetwork(newDefaultNetwork);
9219
James Mattise3ef1912020-12-20 11:09:58 -08009220 if (oldDefaultNetwork != null) {
9221 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9222 }
9223 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009224 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009225 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009226 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009227 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009228 updateTcpBufferSizes(null != newDefaultNetwork
9229 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009230 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009231 }
9232
James Mattisd31bdfa2020-12-23 16:37:26 -08009233 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9234 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9235 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9236 try {
9237 if (VDBG) {
9238 log("Setting default network for " + nri
9239 + " using UIDs " + nri.getUids()
9240 + " with old network " + (oldDefaultNetwork != null
9241 ? oldDefaultNetwork.network().getNetId() : "null")
9242 + " and new network " + (newDefaultNetwork != null
9243 ? newDefaultNetwork.network().getNetId() : "null"));
9244 }
9245 if (nri.getUids().isEmpty()) {
9246 throw new IllegalStateException("makeDefaultForApps called without specifying"
9247 + " any applications to set as the default." + nri);
9248 }
9249 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009250 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009251 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009252 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009253 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009254 }
9255 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009256 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009257 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009258 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009259 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009260 }
9261 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009262 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009263 }
9264 }
9265
Junyu Lai35665cc2022-12-19 17:37:48 +08009266 /**
9267 * Collect restricted uid ranges for the given network and UserHandle, these uids
9268 * are not restricted for matched enterprise networks but being restricted for non-matched
9269 * enterprise networks and non-enterprise networks.
9270 */
9271 @NonNull
9272 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9273 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9274 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9275 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9276 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9277
9278 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9279 // The NC is built from a `ProfileNetworkPreference` which has only one
9280 // enterprise ID, so it's guaranteed to have exactly one.
9281 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9282 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9283 continue;
9284 }
9285 }
9286
9287 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9288 pref.capabilities.getUidRanges())) {
9289 throw new IllegalArgumentException(
9290 "Overlapping uid range in preference: " + pref);
9291 }
9292 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9293 }
9294 return restrictedUidRanges;
9295 }
9296
9297 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009298 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +09009299 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009300
Junyu Lai35665cc2022-12-19 17:37:48 +08009301 ensureRunningOnConnectivityServiceThread();
9302 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9303 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9304 .getUserHandles(true /* excludeDying */);
9305 if (users.isEmpty()) {
9306 throw new IllegalStateException("No user is available");
9307 }
9308
9309 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9310 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9311 for (final UserHandle user : users) {
9312 final ArraySet<UidRange> restrictedUidRanges =
9313 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9314 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9315 UidRange.createForUser(user), restrictedUidRanges));
9316 }
9317
9318 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9319 configs.add(new NativeUidRangeConfig(
9320 nai.network.netId, rangesParcel, 0 /* subPriority */));
9321 }
9322
9323 // The netd API replaces the previous configs with the current configs.
9324 // Thus, for network disconnection or preference removal, no need to
9325 // unset previous config. Instead, collecting all currently needed
9326 // configs and issue to netd.
9327 try {
9328 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9329 } catch (ServiceSpecificException e) {
9330 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009331 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009332 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009333 // Netd died. This will cause a runtime restart anyway.
9334 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009335 }
9336 }
9337
James Mattisd31bdfa2020-12-23 16:37:26 -08009338 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9339 try {
9340 if (null != newDefaultNetwork) {
9341 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9342 } else {
9343 mNetd.networkClearDefault();
9344 }
9345 } catch (RemoteException | ServiceSpecificException e) {
9346 loge("Exception setting default network :" + e);
9347 }
9348 }
9349
Chalard Jean05cbe972019-12-09 11:50:38 +09009350 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009351 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009352 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009353 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009354 processNewlySatisfiedListenRequests(nai);
9355 }
9356
9357 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009358 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9359 if (nri.isMultilayerRequest()) {
9360 continue;
9361 }
9362 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009363 if (!nr.isListen()) continue;
9364 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009365 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009366 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9367 }
9368 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009369 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009370
Chalard Jeancd397a22019-11-22 22:33:33 +09009371 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009372 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9373 if (nri.isMultilayerRequest()) {
9374 continue;
9375 }
9376 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009377 if (!nr.isListen()) continue;
9378 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9379 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009380 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009381 }
9382 }
9383 }
9384
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009385 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009386 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009387 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009388 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009389 @Nullable public final NetworkRequest mOldNetworkRequest;
9390 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009391 @Nullable public final NetworkAgentInfo mOldNetwork;
9392 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009393 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009394 @Nullable final NetworkRequest oldNetworkRequest,
9395 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009396 @Nullable final NetworkAgentInfo oldNetwork,
9397 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009398 mNetworkRequestInfo = networkRequestInfo;
9399 mOldNetworkRequest = oldNetworkRequest;
9400 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009401 mOldNetwork = oldNetwork;
9402 mNewNetwork = newNetwork;
9403 }
Chalard Jean49707572019-12-10 21:07:02 +09009404
9405 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009406 final NetworkRequest requestToShow = null != mNewNetworkRequest
9407 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9408 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009409 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9410 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009411 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009412 }
9413
Chalard Jean46a62372019-12-10 21:25:24 +09009414 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009415
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009416 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009417 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009418 }
9419
9420 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009421 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009422 // The code is never supposed to add two reassignments of the same request. Make
9423 // sure this stays true, but without imposing this expensive check on all
9424 // reassignments on all user devices.
9425 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009426 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009427 throw new IllegalStateException("Trying to reassign ["
9428 + reassignment + "] but already have ["
9429 + existing + "]");
9430 }
9431 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009432 }
Chalard Jean46a62372019-12-10 21:25:24 +09009433 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009434 }
9435
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009436 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009437 // the passed request.
9438 @Nullable
9439 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009440 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009441 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009442 }
9443 return null;
9444 }
Chalard Jean49707572019-12-10 21:07:02 +09009445
9446 public String toString() {
9447 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9448 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009449 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009450 for (final RequestReassignment rr : getRequestReassignments()) {
9451 sj.add(rr.toString());
9452 }
9453 return sj.toString();
9454 }
9455
9456 public String debugString() {
9457 final StringBuilder sb = new StringBuilder();
9458 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009459 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009460 for (final RequestReassignment rr : getRequestReassignments()) {
9461 sb.append("\n ").append(rr);
9462 }
9463 return sb.append("\n").toString();
9464 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009465 }
9466
Chalard Jean24344d72019-12-04 13:32:31 +09009467 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009468 @Nullable final NetworkRequest previousRequest,
9469 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009470 @Nullable final NetworkAgentInfo previousSatisfier,
9471 @Nullable final NetworkAgentInfo newSatisfier,
9472 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009473 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009474 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009475 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009476 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009477 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09009478 }
James Mattisa076c532020-12-02 14:12:41 -08009479 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009480 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009481 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009482 // If this network switch can't be supported gracefully, the request is not
9483 // lingered. This allows letting go of the network sooner to reclaim some
9484 // performance on the new network, since the radio can't do both at the same
9485 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009486 //
9487 // Also don't linger the request if the old network has been destroyed.
9488 // A destroyed network does not provide actual network connectivity, so
9489 // lingering it is not useful. In particular this ensures that a destroyed
9490 // network is outscored by its replacement,
9491 // then it is torn down immediately instead of being lingered, and any apps that
9492 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009493 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9494 }
Chalard Jean24344d72019-12-04 13:32:31 +09009495 } else {
9496 if (VDBG || DDBG) log(" accepting network in place of null");
9497 }
junyulai0ac374f2020-12-14 18:41:52 +08009498
9499 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9500 // and immediately satisfies a request then remove the timer. This will happen for
9501 // all networks except in the case of an underlying network for a VCN.
9502 if (newSatisfier.isNascent()) {
9503 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009504 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009505 }
9506
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009507 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009508 newSatisfier.unlingerRequest(newRequest.requestId);
9509 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009510 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009511 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009512 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009513 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009514 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009515 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009516 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009517 }
James Mattisa076c532020-12-02 14:12:41 -08009518 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009519 }
James Mattisa076c532020-12-02 14:12:41 -08009520 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009521 }
9522
James Mattisa076c532020-12-02 14:12:41 -08009523 /**
9524 * This function is triggered when something can affect what network should satisfy what
9525 * request, and it computes the network reassignment from the passed collection of requests to
9526 * network match to the one that the system should now have. That data is encoded in an
9527 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9528 * satisfier.
9529 *
9530 * After the reassignment is computed, it is applied to the state objects.
9531 *
9532 * @param networkRequests the nri objects to evaluate for possible network reassignment
9533 * @return NetworkReassignment listing of proposed network assignment changes
9534 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009535 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009536 private NetworkReassignment computeNetworkReassignment(
9537 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009538 final NetworkReassignment changes = new NetworkReassignment();
9539
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009540 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009541 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009542 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009543 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009544 }
Chalard Jean857a1712019-12-10 21:08:07 +09009545
James Mattisa076c532020-12-02 14:12:41 -08009546 for (final NetworkRequestInfo nri : networkRequests) {
9547 // Non-multilayer listen requests can be ignored.
9548 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9549 continue;
9550 }
9551 NetworkAgentInfo bestNetwork = null;
9552 NetworkRequest bestRequest = null;
9553 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009554 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009555 // Stop evaluating as the highest possible priority request is satisfied.
9556 if (null != bestNetwork) {
9557 bestRequest = req;
9558 break;
9559 }
9560 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009561 if (null == bestNetwork && isDefaultBlocked(nri)) {
9562 // Remove default networking if disallowed for managed default requests.
9563 bestNetwork = mNoServiceNetwork;
9564 }
9565 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009566 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009567 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009568 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009569 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009570 }
9571 return changes;
9572 }
9573
James Mattisa076c532020-12-02 14:12:41 -08009574 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9575 return new HashSet<>(mNetworkRequests.values());
9576 }
9577
Paul Jensenc88b39b2015-06-16 14:27:36 -04009578 /**
James Mattisa076c532020-12-02 14:12:41 -08009579 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009580 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009581 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009582 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009583 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9584 }
9585
9586 /**
9587 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9588 * being disconnected.
9589 */
9590 private void rematchNetworksAndRequests(
9591 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9592 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009593 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009594 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009595 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009596 final long computed = SystemClock.elapsedRealtime();
9597 applyNetworkReassignment(changes, start);
9598 final long applied = SystemClock.elapsedRealtime();
9599 issueNetworkNeeds();
9600 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009601 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009602 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9603 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009604 log(changes.debugString());
9605 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009606 // Shorter form, only one line of log
9607 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9608 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009609 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009610 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009611
Chalard Jeand7f762d2019-12-10 19:01:29 +09009612 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009613 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009614 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009615
9616 // Since most of the time there are only 0 or 1 background networks, it would probably
9617 // be more efficient to just use an ArrayList here. TODO : measure performance
9618 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9619 for (final NetworkAgentInfo nai : nais) {
9620 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9621 }
9622
Chalard Jeand7f762d2019-12-10 19:01:29 +09009623 // First, update the lists of satisfied requests in the network agents. This is necessary
9624 // because some code later depends on this state to be correct, most prominently computing
9625 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009626 for (final NetworkReassignment.RequestReassignment event :
9627 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009628 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9629 event.mOldNetworkRequest, event.mNewNetworkRequest,
9630 event.mOldNetwork, event.mNewNetwork,
9631 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009632 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009633
James Mattise3ef1912020-12-20 11:09:58 -08009634 // Process default network changes if applicable.
9635 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009636
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009637 // Notify requested networks are available after the default net is switched, but
9638 // before LegacyTypeTracker sends legacy broadcasts
9639 for (final NetworkReassignment.RequestReassignment event :
9640 changes.getRequestReassignments()) {
9641 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009642 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009643 } else {
James Mattisa076c532020-12-02 14:12:41 -08009644 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009645 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009646 }
9647 }
9648
junyulai0ac374f2020-12-14 18:41:52 +08009649 // Update the inactivity state before processing listen callbacks, because the background
9650 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009651 // just yet though, because they have to be sent after the listens are processed to keep
9652 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009653 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009654 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009655 // Rematching may have altered the inactivity state of some networks, so update all
9656 // inactivity timers. updateInactivityState reads the state from the network agent
9657 // and does nothing if the state has not changed : the source of truth is controlled
9658 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9659 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009660 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009661 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009662 }
9663 }
9664
Chalard Jeanb10ab412019-12-11 14:12:30 +09009665 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009666 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009667 // Process listen requests and update capabilities if the background state has
9668 // changed for this network. For consistency with previous behavior, send onLost
9669 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009670 processNewlyLostListenRequests(nai);
9671 if (oldBackground != nai.isBackgroundNetwork()) {
9672 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009673 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009674 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009675 }
9676
junyulai0ac374f2020-12-14 18:41:52 +08009677 for (final NetworkAgentInfo nai : inactiveNetworks) {
9678 // For nascent networks, if connecting with no foreground request, skip broadcasting
9679 // LOSING for backward compatibility. This is typical when mobile data connected while
9680 // wifi connected with mobile data always-on enabled.
9681 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009682 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009683 }
9684
James Mattise3ef1912020-12-20 11:09:58 -08009685 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009686
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009687 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +00009688 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009689 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009690 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009691 // This network has active linger timers and no requests, but is not
9692 // lingering. Linger it.
9693 //
9694 // One way (the only way?) this can happen if this network is unvalidated
9695 // and became unneeded due to another network improving its score to the
9696 // point where this network will no longer be able to satisfy any requests
9697 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009698 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009699 notifyNetworkLosing(nai, now);
9700 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009701 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009702 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009703 teardownUnneededNetwork(nai);
9704 }
9705 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009706 }
9707 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009708
Chalard Jean62edfd82019-12-02 18:39:29 +09009709 /**
9710 * Apply a change in background state resulting from rematching networks with requests.
9711 *
9712 * During rematch, a network may change background states by starting to satisfy or stopping
9713 * to satisfy a foreground request. Listens don't count for this. When a network changes
9714 * background states, its capabilities need to be updated and callbacks fired for the
9715 * capability change.
9716 *
9717 * @param nai The network that changed background states
9718 */
9719 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
9720 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
9721 if (Objects.equals(nai.networkCapabilities, newNc)) return;
9722 updateNetworkPermissions(nai, newNc);
9723 nai.getAndSetNetworkCapabilities(newNc);
9724 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
9725 }
9726
Chalard Jeanf0344532019-11-19 19:23:38 +09009727 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08009728 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009729 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09009730 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
9731 changes.getReassignment(mDefaultRequest);
9732 final NetworkAgentInfo oldDefaultNetwork =
9733 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
9734 final NetworkAgentInfo newDefaultNetwork =
9735 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08009736
Chalard Jean5b409c72021-02-04 13:12:59 +09009737 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009738 // Maintain the illusion : since the legacy API only understands one network at a time,
9739 // if the default network changed, apps should see a disconnected broadcast for the
9740 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009741 if (oldDefaultNetwork != null) {
9742 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9743 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009744 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009745 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009746 // The new default network can be newly null if and only if the old default
9747 // network doesn't satisfy the default request any more because it lost a
9748 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009749 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009750 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009751 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009752 }
9753 }
9754
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009755 // Now that all the callbacks have been sent, send the legacy network broadcasts
9756 // as needed. This is necessary so that legacy requests correctly bind dns
9757 // requests to this network. The legacy users are listening for this broadcast
9758 // and will generally do a dns request so they can ensureRouteToHost and if
9759 // they do that before the callbacks happen they'll use the default network.
9760 //
9761 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
9762 // callbacks, but if apps can receive the broadcast before the callback, they still might
9763 // have an inconsistent view of networking.
9764 //
9765 // This *does* introduce a race where if the user uses the new api
9766 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
9767 // they may get old info. Reverse this after the old startUsing api is removed.
9768 // This is on top of the multiple intent sequencing referenced in the todo above.
9769 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09009770 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009771 addNetworkToLegacyTypeTracker(nai);
9772 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08009773 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009774 }
9775
Chalard Jean0354d8c2021-01-12 10:58:56 +09009776 private void issueNetworkNeeds() {
9777 ensureRunningOnConnectivityServiceThread();
9778 for (final NetworkOfferInfo noi : mNetworkOffers) {
9779 issueNetworkNeeds(noi);
9780 }
9781 }
9782
9783 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
9784 ensureRunningOnConnectivityServiceThread();
9785 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9786 informOffer(nri, noi.offer, mNetworkRanker);
9787 }
9788 }
9789
9790 /**
9791 * Inform a NetworkOffer about any new situation of a request.
9792 *
9793 * This function handles updates to offers. A number of events may happen that require
9794 * updating the registrant for this offer about the situation :
9795 * • The offer itself was updated. This may lead the offer to no longer being able
9796 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
9797 * or conversely being strengthened enough to beat the satisfier (and therefore
9798 * start being needed)
9799 * • The network satisfying a request changed (including cases where the request
9800 * starts or stops being satisfied). The new network may be a stronger or weaker
9801 * match than the old one, possibly affecting whether the offer is needed.
9802 * • The network satisfying a request updated their score. This may lead the offer
9803 * to no longer be able to beat it if the current satisfier got better, or
9804 * conversely start being a good choice if the current satisfier got weaker.
9805 *
9806 * @param nri The request
9807 * @param offer The offer. This may be an updated offer.
9808 */
9809 private static void informOffer(@NonNull NetworkRequestInfo nri,
9810 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9811 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9812 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009813
9814 // Multi-layer requests have a currently active request, the one being satisfied.
9815 // Since the system will try to bring up a better network than is currently satisfying
9816 // the request, NetworkProviders need to be told the offers matching the requests *above*
9817 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9818 // not needed, and the offer is needed for the active request iff the offer can beat
9819 // the satisfier.
9820 // For non-multilayer requests, the logic above gracefully degenerates to only the
9821 // last case.
9822 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9823 // providers that the offer is needed for this request, until the active request is found.
9824 // In a second phase, deal with the currently active request. In a third phase, inform
9825 // the providers that offer is unneeded for the remaining requests.
9826
9827 // First phase : inform providers of all requests above the active request.
9828 int i;
9829 for (i = 0; nri.mRequests.size() > i; ++i) {
9830 final NetworkRequest request = nri.mRequests.get(i);
9831 if (activeRequest == request) break; // Found the active request : go to phase 2
9832 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9833 // Since this request is higher-priority than the one currently satisfied, if the
9834 // offer can satisfy it, the provider should try and bring up the network for sure ;
9835 // no need to even ask the ranker – an offer that can satisfy is always better than
9836 // no network. Hence tell the provider so unless it already knew.
9837 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9838 offer.onNetworkNeeded(request);
9839 }
9840 }
9841
9842 // Second phase : deal with the active request (if any)
9843 if (null != activeRequest && activeRequest.isRequest()) {
9844 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009845 // If an offer can satisfy the request, it is considered needed if it is currently
9846 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009847 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009848 && satisfier.factorySerialNumber == offer.providerId
9849 && activeRequest.canBeSatisfiedBy(offer.caps);
9850 final boolean newNeeded = currentlyServing
9851 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009852 if (newNeeded != oldNeeded) {
9853 if (newNeeded) {
9854 offer.onNetworkNeeded(activeRequest);
9855 } else {
9856 // The offer used to be able to beat the satisfier. Now it can't.
9857 offer.onNetworkUnneeded(activeRequest);
9858 }
9859 }
9860 }
9861
9862 // Third phase : inform the providers that the offer isn't needed for any request
9863 // below the active one.
9864 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
9865 final NetworkRequest request = nri.mRequests.get(i);
9866 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9867 // Since this request is lower-priority than the one currently satisfied, if the
9868 // offer can satisfy it, the provider should not try and bring up the network.
9869 // Hence tell the provider so unless it already knew.
9870 if (offer.neededFor(request)) {
9871 offer.onNetworkUnneeded(request);
9872 }
9873 }
9874 }
9875
Chalard Jean61c79252019-11-07 23:07:32 +09009876 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
9877 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9878 NetworkRequest nr = nai.requestAt(i);
9879 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
9880 // legacy type tracker filters out repeat adds
9881 mLegacyTypeTracker.add(nr.legacyType, nai);
9882 }
9883 }
9884
9885 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09009886 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09009887 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
9888 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
9889 if (nai.isVPN()) {
9890 mLegacyTypeTracker.add(TYPE_VPN, nai);
9891 }
9892 }
9893
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009894 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04009895 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +09009896 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09009897 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04009898 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09009899 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009900
Chalard Jean254bd162022-08-25 13:04:51 +09009901 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009902 // Don't repeat publish.
9903 if (newInetCondition == mDefaultInetConditionPublished) return;
9904
9905 mDefaultInetConditionPublished = newInetCondition;
9906 sendInetConditionBroadcast(nai.networkInfo);
9907 }
9908
Chalard Jeand61375d2020-01-14 22:46:36 +09009909 @NonNull
9910 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
9911 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009912 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09009913 final boolean suspended =
9914 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9915 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
9916 // Only override the state with SUSPENDED if the network is currently in CONNECTED
9917 // state. This is because the network could have been suspended before connecting,
9918 // or it could be disconnecting while being suspended, and in both these cases
9919 // the state should not be overridden. Note that the only detailed state that
9920 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
9921 // worry about multiple different substates of CONNECTED.
9922 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
9923 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009924 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
9925 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
9926 // network agent is created, then goes to suspended, then goes out of suspended without
9927 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +09009928 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009929 ? NetworkInfo.DetailedState.CONNECTED
9930 : NetworkInfo.DetailedState.CONNECTING,
9931 info.getReason(),
9932 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09009933 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009934 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09009935 return newInfo;
9936 }
9937
9938 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
9939 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
9940
Erik Kline99f301b2017-02-15 19:59:17 +09009941 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009942 NetworkInfo oldInfo = null;
9943 synchronized (networkAgent) {
9944 oldInfo = networkAgent.networkInfo;
9945 networkAgent.networkInfo = newInfo;
9946 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009947
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009948 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009949 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
9950 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009951 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009952
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09009953 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009954 // A network that has just connected has zero requests and is thus a foreground network.
9955 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
9956
Luke Huangfdd11f82019-04-09 18:41:49 +08009957 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09009958
9959 networkAgent.setCreated();
9960
9961 // If the network is created immediately on register, then apply the LinkProperties now.
9962 // Otherwise, this is done further down when the network goes into connected state.
9963 // Applying the LinkProperties means that the network is ready to carry traffic -
9964 // interfaces and routing rules have been added, DNS servers programmed, etc.
9965 // For VPNs, this must be done before the capabilities are updated, because as soon as
9966 // that happens, UIDs are routed to the network.
9967 if (shouldCreateNetworksImmediately()) {
9968 applyInitialLinkProperties(networkAgent);
9969 }
9970
9971 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
9972 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +09009973 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009974 // Initialize the network's capabilities to their starting values according to the
9975 // underlying networks. This ensures that the capabilities are correct before
9976 // anything happens to the network.
9977 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009978 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009979 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +09009980 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +08009981 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009982 }
9983
Chalard Jean254bd162022-08-25 13:04:51 +09009984 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
9985 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009986
lucaslin45e639b2019-04-03 17:09:28 +08009987 // NetworkCapabilities need to be set before sending the private DNS config to
9988 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009989 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9990
Erik Kline9a62f012018-03-21 07:18:33 -07009991 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09009992 if (!shouldCreateNetworksImmediately()) {
9993 applyInitialLinkProperties(networkAgent);
9994 } else {
9995 // The network was created when the agent registered, and the LinkProperties are
9996 // already up-to-date. However, updateLinkProperties also makes some changes only
9997 // when the network connects. Apply those changes here. On T and below these are
9998 // handled by the applyInitialLinkProperties call just above.
9999 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10000 // If something depends on both LinkProperties and connected state, it should be in
10001 // this method as well.
10002 networkAgent.clatd.update();
10003 updateProxy(networkAgent.linkProperties, null);
10004 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010005
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010006 // If a rate limit has been configured and is applicable to this network (network
10007 // provides internet connectivity), apply it. The tc police filter cannot be attached
10008 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
10009 // updateInterfaces -> INetd#networkAddInterface.
10010 // Note: in case of a system server crash, the NetworkController constructor in netd
10011 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10012 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10013 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10014 mIngressRateLimit);
10015 }
10016
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010017 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10018 // command must be sent after updating LinkProperties to maximize chances of
10019 // NetworkMonitor seeing the correct LinkProperties when starting.
10020 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010021 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010022 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010023 }
Chalard Jeand4900722022-02-06 12:25:38 +090010024 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10025 params.networkAgentConfig = networkAgent.networkAgentConfig;
10026 params.networkCapabilities = networkAgent.networkCapabilities;
10027 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10028 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010029 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10030 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10031 // call that would cause a Log.wtf to be emitted from the system_server process, and
10032 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10033 // process to check the interface version, just use an SDK check. NetworkStack will
10034 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010035 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010036 networkAgent.networkMonitor().notifyNetworkConnected(params);
10037 } else {
10038 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10039 params.networkCapabilities);
10040 }
Chalard Jean0f141332023-06-05 19:26:17 +090010041 final long evaluationDelay;
10042 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10043 // If the network is anything other than pure wifi, use the default timeout.
10044 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10045 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10046 // If the network is explicitly selected, use the default timeout because it's
10047 // shorter and the user is likely staring at the screen expecting it to validate
10048 // right away.
10049 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10050 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10051 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10052 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10053 } else {
10054 // It's wifi, automatically connected, and bad wifi is preferred : use the
10055 // longer timeout to avoid the device switching to captive portals with bad
10056 // signal or very slow response.
10057 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10058 }
10059 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010060
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010061 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10062 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10063 // capabilities, so it only needs to be done once on initial connect, not every time the
10064 // network's capabilities change. Note that we do this before rematching the network,
10065 // so we could decide to tear it down immediately afterwards. That's fine though - on
10066 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10067 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010068 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010069
junyulai0ac374f2020-12-14 18:41:52 +080010070 // Before first rematching networks, put an inactivity timer without any request, this
10071 // allows {@code updateInactivityState} to update the state accordingly and prevent
10072 // tearing down for any {@code unneeded} evaluation in this period.
10073 // Note that the timer will not be rescheduled since the expiry time is
10074 // fixed after connection regardless of the network satisfying other requests or not.
10075 // But it will be removed as soon as the network satisfies a request for the first time.
10076 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10077 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010078 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010079
Paul Jensen05e85ee2014-09-11 11:00:39 -040010080 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010081 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010082
10083 // This has to happen after matching the requests, because callbacks are just requests.
10084 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010085 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010086 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010087 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010088 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010089 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010090 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010091 if (networkAgent.isVPN()) {
10092 // As the active or bound network changes for apps, broadcast the default proxy, as
10093 // apps may need to update their proxy data. This is called after disconnecting from
10094 // VPN to make sure we do not broadcast the old proxy data.
10095 // TODO(b/122649188): send the broadcast only to VPN users.
10096 mProxyTracker.sendProxyBroadcast();
10097 }
Chalard Jean254bd162022-08-25 13:04:51 +090010098 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10099 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010100 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010101 }
10102 }
10103
Chalard Jean28018572020-12-21 18:36:52 +090010104 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010105 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10106 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010107 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010108 }
10109
Erik Kline99f301b2017-02-15 19:59:17 +090010110 // Notify only this one new request of the current state. Transfer all the
10111 // current state by calling NetworkCapabilities and LinkProperties callbacks
10112 // so that callers can be guaranteed to have as close to atomicity in state
10113 // transfer as can be supported by this current API.
10114 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010115 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010116 if (nri.mPendingIntent != null) {
10117 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10118 // Attempt no subsequent state pushes where intents are involved.
10119 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010120 }
Erik Kline99f301b2017-02-15 19:59:17 +090010121
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010122 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010123 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010124 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10125 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10126 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010127 }
10128
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010129 // Notify the requests on this NAI that the network is now lingered.
10130 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010131 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010132 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10133 }
10134
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010135 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10136 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10137 return vpnBlocked
10138 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10139 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10140 }
10141
10142 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10143 if (blockedReasons == BLOCKED_REASON_NONE) {
10144 mUidBlockedReasons.delete(uid);
10145 } else {
10146 mUidBlockedReasons.put(uid, blockedReasons);
10147 }
10148 }
10149
junyulaif2c67e42018-08-07 19:50:45 +080010150 /**
10151 * Notify of the blocked state apps with a registered callback matching a given NAI.
10152 *
10153 * Unlike other callbacks, blocked status is different between each individual uid. So for
10154 * any given nai, all requests need to be considered according to the uid who filed it.
10155 *
10156 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010157 * @param oldMetered True if the previous network capabilities were metered.
10158 * @param newMetered True if the current network capabilities are metered.
10159 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10160 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010161 */
10162 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010163 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10164 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010165
10166 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10167 NetworkRequest nr = nai.requestAt(i);
10168 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010169
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010170 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10171 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10172 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010173 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010174 : oldVpnBlocked;
10175
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010176 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10177 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10178 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010179 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010180 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010181 }
10182 }
10183 }
10184
10185 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010186 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010187 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010188 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010189 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010190 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010191 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010192 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010193 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010194
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010195 final int oldBlockedState = getBlockedState(
10196 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10197 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10198 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010199 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010200 }
junyulaif2c67e42018-08-07 19:50:45 +080010201 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10202 NetworkRequest nr = nai.requestAt(i);
10203 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010204 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010205 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10206 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010207 }
10208 }
10209 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010210 }
10211
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010212 @VisibleForTesting
10213 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010214 // The NetworkInfo we actually send out has no bearing on the real
10215 // state of affairs. For example, if the default connection is mobile,
10216 // and a request for HIPRI has just gone away, we need to pretend that
10217 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10218 // the state to DISCONNECTED, even though the network is of type MOBILE
10219 // and is still connected.
10220 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10221 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010222 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010223 if (state != DetailedState.DISCONNECTED) {
10224 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010225 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010226 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010227 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010228 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10229 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10230 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10231 if (info.isFailover()) {
10232 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10233 nai.networkInfo.setFailover(false);
10234 }
10235 if (info.getReason() != null) {
10236 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10237 }
10238 if (info.getExtraInfo() != null) {
10239 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10240 }
10241 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010242 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010243 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010244 if (newDefaultAgent != null) {
10245 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10246 newDefaultAgent.networkInfo);
10247 } else {
10248 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10249 }
10250 }
10251 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10252 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010253 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010254 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010255 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010256 }
10257 }
10258 }
10259
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010260 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010261 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010262 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010263 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010264 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010265 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10266 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010267 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10268 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010269 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010270 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010271 } else {
10272 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10273 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010274 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010275 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010276
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010277 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10278 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10279 }
10280
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010281 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010282 * Returns the list of all interfaces that could be used by network traffic that does not
10283 * explicitly specify a network. This includes the default network, but also all VPNs that are
10284 * currently connected.
10285 *
10286 * Must be called on the handler thread.
10287 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010288 @NonNull
10289 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010290 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010291 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010292 final Set<Integer> activeNetIds = new ArraySet<>();
10293 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10294 if (nri.isBeingSatisfied()) {
10295 activeNetIds.add(nri.getSatisfier().network().netId);
10296 }
10297 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010298 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010299 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010300 defaultNetworks.add(nai.network);
10301 }
10302 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010303 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010304 }
10305
10306 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010307 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10308 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010309 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010310 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010311 ensureRunningOnConnectivityServiceThread();
10312 String activeIface = null;
10313 LinkProperties activeLinkProperties = getActiveLinkProperties();
10314 if (activeLinkProperties != null) {
10315 activeIface = activeLinkProperties.getInterfaceName();
10316 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010317
junyulai2050bed2021-01-23 09:46:34 +080010318 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010319 try {
junyulaide41fc22021-01-22 22:46:01 +080010320 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010321 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010322 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10323 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010324 } catch (Exception ignored) {
10325 }
10326 }
10327
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010328 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010329 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010330 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010331 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010332 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010333
10334 if (!TextUtils.isEmpty(settingUrl)) {
10335 return settingUrl;
10336 }
10337
10338 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010339 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010340 if (!TextUtils.isEmpty(settingUrl)) {
10341 return settingUrl;
10342 }
10343
10344 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010345 }
10346
10347 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010348 public void startNattKeepalive(Network network, int intervalSeconds,
10349 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010350 enforceKeepalivePermission();
10351 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010352 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010353 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10354 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010355 // false and set the underpinned network to null because there is no way and no
10356 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10357 // deprecated method.
10358 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010359 }
10360
10361 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010362 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010363 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010364 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010365 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010366 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010367 mKeepaliveTracker.startNattKeepalive(
10368 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010369 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10370 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010371 } finally {
10372 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10373 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010374 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10375 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010376 }
10377 }
junyulaid05a1922019-01-15 11:32:44 +080010378 }
10379
10380 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010381 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010382 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010383 try {
10384 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010385 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010386 mKeepaliveTracker.startTcpKeepalive(
10387 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10388 } finally {
10389 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10390 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010391 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10392 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010393 }
10394 }
junyulai0835a1e2019-01-08 20:04:33 +080010395 }
10396
10397 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010398 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010399 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010400 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10401 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010402 }
10403
10404 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090010405 public int[] getSupportedKeepalives() {
10406 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10407 // Backwards compatibility with CTS 13
10408 android.Manifest.permission.QUERY_ALL_PACKAGES);
10409
10410 return BinderUtils.withCleanCallingIdentity(() ->
10411 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10412 }
10413
10414 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010415 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010416 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010417
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010418 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010419 final long token = Binder.clearCallingIdentity();
10420 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010421 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10422 UserHandle.getUserHandleForUid(uid))) {
10423 return;
10424 }
10425
Heemin Seogdb8489d2019-06-12 09:21:44 -070010426 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10427 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010428
10429 // Turn airplane mode off
10430 setAirplaneMode(false);
10431
10432 // restore private DNS settings to default mode (opportunistic)
10433 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10434 UserHandle.getUserHandleForUid(uid))) {
10435 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10436 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10437 }
10438
10439 Settings.Global.putString(mContext.getContentResolver(),
10440 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010441 } finally {
10442 Binder.restoreCallingIdentity(token);
10443 }
Stuart Scottd5463642015-04-02 18:00:02 -070010444 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010445
Ricky Wai7097cc92018-01-23 04:09:45 +000010446 @Override
10447 public byte[] getNetworkWatchlistConfigHash() {
10448 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10449 if (nwm == null) {
10450 loge("Unable to get NetworkWatchlistManager");
10451 return null;
10452 }
10453 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10454 return nwm.getWatchlistConfigHash();
10455 }
10456
Hugo Benichibe0c7652016-05-31 16:28:06 +090010457 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010458 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010459 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010460 }
Hugo Benichif4210292017-04-21 15:07:12 +090010461
10462 private static boolean toBool(int encodedBoolean) {
10463 return encodedBoolean != 0; // Only 0 means false.
10464 }
10465
10466 private static int encodeBool(boolean b) {
10467 return b ? 1 : 0;
10468 }
mswest4632928412018-03-12 10:34:34 -070010469
10470 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010471 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10472 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10473 @NonNull String[] args) {
10474 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10475 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010476 }
10477
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010478 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010479 @Override
10480 public int onCommand(String cmd) {
10481 if (cmd == null) {
10482 return handleDefaultCommands(cmd);
10483 }
10484 final PrintWriter pw = getOutPrintWriter();
10485 try {
10486 switch (cmd) {
10487 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010488 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
10489 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070010490 final String action = getNextArg();
10491 if ("enable".equals(action)) {
10492 setAirplaneMode(true);
10493 return 0;
10494 } else if ("disable".equals(action)) {
10495 setAirplaneMode(false);
10496 return 0;
10497 } else if (action == null) {
10498 final ContentResolver cr = mContext.getContentResolver();
10499 final int enabled = Settings.Global.getInt(cr,
10500 Settings.Global.AIRPLANE_MODE_ON);
10501 pw.println(enabled == 0 ? "disabled" : "enabled");
10502 return 0;
10503 } else {
10504 onHelp();
10505 return -1;
10506 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010507 case "reevaluate":
10508 // Usage : adb shell cmd connectivity reevaluate <netId>
10509 // If netId is omitted, then reevaluate the default network
10510 final String netId = getNextArg();
10511 final NetworkAgentInfo nai;
10512 if (null == netId) {
10513 // Note that the command is running on the wrong thread to call this,
10514 // so this could in principle return stale data. But it can't crash.
10515 nai = getDefaultNetwork();
10516 } else {
10517 // If netId can't be parsed, this throws NumberFormatException, which
10518 // is passed back to adb who prints it.
10519 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10520 }
10521 if (null == nai) {
10522 pw.println("Unknown network (net ID not found or no default network)");
10523 return 0;
10524 }
10525 Log.d(TAG, "Reevaluating network " + nai.network);
10526 reportNetworkConnectivity(nai.network, !nai.isValidated());
10527 return 0;
mswest4632928412018-03-12 10:34:34 -070010528 default:
10529 return handleDefaultCommands(cmd);
10530 }
10531 } catch (Exception e) {
10532 pw.println(e);
10533 }
10534 return -1;
10535 }
10536
10537 @Override
10538 public void onHelp() {
10539 PrintWriter pw = getOutPrintWriter();
10540 pw.println("Connectivity service commands:");
10541 pw.println(" help");
10542 pw.println(" Print this help text.");
10543 pw.println(" airplane-mode [enable|disable]");
10544 pw.println(" Turn airplane mode on or off.");
10545 pw.println(" airplane-mode");
10546 pw.println(" Get airplane mode.");
10547 }
10548 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010549
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010550 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010551 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10552 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10553 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010554 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010555 }
10556
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010557 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10558 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010559 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10560 final TransportInfo newInfo = nc.getTransportInfo();
10561 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10562 return;
10563 }
10564 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010565 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010566 }
10567 }
10568
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010569 /**
10570 * @param connectionInfo the connection to resolve.
10571 * @return {@code uid} if the connection is found and the app has permission to observe it
10572 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10573 * connection is not found.
10574 */
10575 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010576 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10577 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10578 }
10579
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010580 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010581 connectionInfo.local, connectionInfo.remote);
10582
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010583 if (uid == INVALID_UID) return uid; // Not found.
10584
10585 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10586 // VPN, if any, that applies to the UID that owns the connection.
10587 if (checkNetworkStackPermission()) return uid;
10588
10589 final NetworkAgentInfo vpn = getVpnForUid(uid);
10590 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010591 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010592 return INVALID_UID;
10593 }
10594
10595 return uid;
10596 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010597
Benedict Wong493e04b2018-11-09 14:45:34 -080010598 /**
10599 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10600 *
10601 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10602 */
10603 @Override
10604 public IBinder startOrGetTestNetworkService() {
10605 synchronized (mTNSLock) {
10606 TestNetworkService.enforceTestNetworkPermissions(mContext);
10607
10608 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010609 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010610 }
10611
10612 return mTNS;
10613 }
10614 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010615
Cody Kesting73708bf2019-12-18 10:57:50 -080010616 /**
10617 * Handler used for managing all Connectivity Diagnostics related functions.
10618 *
10619 * @see android.net.ConnectivityDiagnosticsManager
10620 *
10621 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10622 */
10623 @VisibleForTesting
10624 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010625 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10626
Cody Kesting73708bf2019-12-18 10:57:50 -080010627 /**
10628 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10629 * android.net.ConnectivityDiagnosticsManager}.
10630 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10631 * NetworkRequestInfo to be registered
10632 */
10633 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10634
10635 /**
10636 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10637 * android.net.ConnectivityDiagnosticsManager}.
10638 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10639 * arg1 = the uid of the caller
10640 */
10641 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10642
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010643 /**
10644 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010645 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010646 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10647 * NetworkMonitor.
10648 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010649 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010650 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010651
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010652 /**
10653 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10654 * been detected on the network.
10655 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10656 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10657 * arg2 = NetID.
10658 * data = PersistableBundle of extras passed from NetworkMonitor.
10659 */
10660 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10661
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010662 /**
10663 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10664 * the platform. This event will invoke {@link
10665 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10666 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070010667 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010668 */
10669 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
10670
Cody Kesting73708bf2019-12-18 10:57:50 -080010671 private ConnectivityDiagnosticsHandler(Looper looper) {
10672 super(looper);
10673 }
10674
10675 @Override
10676 public void handleMessage(Message msg) {
10677 switch (msg.what) {
10678 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10679 handleRegisterConnectivityDiagnosticsCallback(
10680 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
10681 break;
10682 }
10683 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10684 handleUnregisterConnectivityDiagnosticsCallback(
10685 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
10686 break;
10687 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010688 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010689 final ConnectivityReportEvent reportEvent =
10690 (ConnectivityReportEvent) msg.obj;
10691
Aaron Huang959d3642021-01-21 15:47:41 +080010692 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010693 break;
10694 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010695 case EVENT_DATA_STALL_SUSPECTED: {
10696 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080010697 final Pair<Long, PersistableBundle> arg =
10698 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010699 if (nai == null) break;
10700
Aaron Huang959d3642021-01-21 15:47:41 +080010701 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010702 break;
10703 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010704 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070010705 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010706 break;
10707 }
10708 default: {
10709 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
10710 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010711 }
10712 }
10713 }
10714
10715 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
10716 @VisibleForTesting
10717 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
10718 @NonNull private final IConnectivityDiagnosticsCallback mCb;
10719 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010720 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010721
10722 @VisibleForTesting
10723 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010724 @NonNull IConnectivityDiagnosticsCallback cb,
10725 @NonNull NetworkRequestInfo nri,
10726 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010727 mCb = cb;
10728 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010729 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010730 }
10731
10732 @Override
10733 public void binderDied() {
10734 log("ConnectivityDiagnosticsCallback IBinder died.");
10735 unregisterConnectivityDiagnosticsCallback(mCb);
10736 }
10737 }
10738
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010739 /**
10740 * Class used for sending information from {@link
10741 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
10742 */
10743 private static class NetworkTestedResults {
10744 private final int mNetId;
10745 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010746 @Nullable private final String mRedirectUrl;
10747
10748 private NetworkTestedResults(
10749 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
10750 mNetId = netId;
10751 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010752 mRedirectUrl = redirectUrl;
10753 }
10754 }
10755
10756 /**
10757 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
10758 * ConnectivityDiagnosticsHandler}.
10759 */
10760 private static class ConnectivityReportEvent {
10761 private final long mTimestampMillis;
10762 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080010763 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010764
Aaron Huang959d3642021-01-21 15:47:41 +080010765 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
10766 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010767 mTimestampMillis = timestampMillis;
10768 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080010769 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010770 }
10771 }
10772
Cody Kestingf1120be2020-08-03 18:01:40 -070010773 /**
10774 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
10775 * ConnectivityDiagnosticsHandler}.
10776 */
10777 private static class ReportedNetworkConnectivityInfo {
10778 public final boolean hasConnectivity;
10779 public final boolean isNetworkRevalidating;
10780 public final int reporterUid;
10781 @NonNull public final NetworkAgentInfo nai;
10782
10783 private ReportedNetworkConnectivityInfo(
10784 boolean hasConnectivity,
10785 boolean isNetworkRevalidating,
10786 int reporterUid,
10787 @NonNull NetworkAgentInfo nai) {
10788 this.hasConnectivity = hasConnectivity;
10789 this.isNetworkRevalidating = isNetworkRevalidating;
10790 this.reporterUid = reporterUid;
10791 this.nai = nai;
10792 }
10793 }
10794
Cody Kesting73708bf2019-12-18 10:57:50 -080010795 private void handleRegisterConnectivityDiagnosticsCallback(
10796 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
10797 ensureRunningOnConnectivityServiceThread();
10798
10799 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080010800 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010801 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
10802
James Mattis64b8b0f2020-11-24 17:40:49 -080010803 // Connectivity Diagnostics are meant to be used with a single network request. It would be
10804 // confusing for these networks to change when an NRI is satisfied in another layer.
10805 if (nri.isMultilayerRequest()) {
10806 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
10807 + "network requests.");
10808 }
10809
Cody Kesting73708bf2019-12-18 10:57:50 -080010810 // This means that the client registered the same callback multiple times. Do
10811 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080010812 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010813 if (VDBG) log("Diagnostics callback is already registered");
10814
10815 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10816 // incremented when the NetworkRequestInfo is created as part of
10817 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010818 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080010819 return;
10820 }
10821
Cody Kesting31f1ff62020-03-05 10:46:02 -080010822 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080010823
10824 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080010825 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010826 } catch (RemoteException e) {
10827 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080010828 return;
10829 }
10830
10831 // Once registered, provide ConnectivityReports for matching Networks
10832 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
10833 synchronized (mNetworkForNetId) {
10834 for (int i = 0; i < mNetworkForNetId.size(); i++) {
10835 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080010836 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
10837 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080010838 matchingNetworks.add(nai);
10839 }
10840 }
10841 }
10842 for (final NetworkAgentInfo nai : matchingNetworks) {
10843 final ConnectivityReport report = nai.getConnectivityReport();
10844 if (report == null) {
10845 continue;
10846 }
10847 if (!checkConnectivityDiagnosticsPermissions(
10848 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10849 continue;
10850 }
10851
10852 try {
10853 cb.onConnectivityReportAvailable(report);
10854 } catch (RemoteException e) {
10855 // Exception while sending the ConnectivityReport. Move on to the next network.
10856 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010857 }
10858 }
10859
10860 private void handleUnregisterConnectivityDiagnosticsCallback(
10861 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
10862 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010863 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010864
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010865 final ConnectivityDiagnosticsCallbackInfo cbInfo =
10866 mConnectivityDiagnosticsCallbacks.remove(iCb);
10867 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010868 if (VDBG) log("Removing diagnostics callback that is not currently registered");
10869 return;
10870 }
10871
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010872 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080010873
Cody Kesting70fa2b22020-12-02 12:16:56 -080010874 // Caller's UID must either be the registrants (if they are unregistering) or the System's
10875 // (if the Binder died)
10876 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
10877 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080010878 return;
10879 }
10880
Cody Kesting46cb1672020-03-04 13:35:20 -080010881 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10882 // incremented when the NetworkRequestInfo is created as part of
10883 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010884 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080010885
Cody Kesting31f1ff62020-03-05 10:46:02 -080010886 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010887 }
10888
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010889 private void handleNetworkTestedWithExtras(
10890 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
10891 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080010892 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010893 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010894 final ConnectivityReport report =
10895 new ConnectivityReport(
10896 reportEvent.mNai.network,
10897 reportEvent.mTimestampMillis,
10898 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010899 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010900 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080010901 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070010902
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010903 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010904 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010905 for (final IConnectivityDiagnosticsCallback cb : results) {
10906 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080010907 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010908 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070010909 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010910 }
10911 }
10912 }
10913
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010914 private void handleDataStallSuspected(
10915 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
10916 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080010917 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010918 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010919 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080010920 new DataStallReport(
10921 nai.network,
10922 timestampMillis,
10923 detectionMethod,
10924 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010925 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080010926 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010927 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010928 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010929 for (final IConnectivityDiagnosticsCallback cb : results) {
10930 try {
10931 cb.onDataStallSuspected(report);
10932 } catch (RemoteException ex) {
10933 loge("Error invoking onDataStallSuspected", ex);
10934 }
10935 }
10936 }
10937
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010938 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070010939 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
10940 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
10941 final ConnectivityReport cachedReport = nai.getConnectivityReport();
10942
10943 // If the Network is being re-validated as a result of this call to
10944 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
10945 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010946 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010947 getMatchingPermissionedCallbacks(
10948 nai,
10949 reportedNetworkConnectivityInfo.isNetworkRevalidating
10950 ? Process.INVALID_UID
10951 : reportedNetworkConnectivityInfo.reporterUid);
10952
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010953 for (final IConnectivityDiagnosticsCallback cb : results) {
10954 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070010955 cb.onNetworkConnectivityReported(
10956 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010957 } catch (RemoteException ex) {
10958 loge("Error invoking onNetworkConnectivityReported", ex);
10959 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010960
10961 // If the Network isn't re-validating, also provide the cached report. If there is no
10962 // cached report, the Network is still being validated and a report will be sent once
10963 // validation is complete. Note that networks which never undergo validation will still
10964 // have a cached ConnectivityReport with RESULT_SKIPPED.
10965 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
10966 try {
10967 cb.onConnectivityReportAvailable(cachedReport);
10968 } catch (RemoteException ex) {
10969 loge("Error invoking onConnectivityReportAvailable", ex);
10970 }
10971 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010972 }
10973 }
10974
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010975 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090010976 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
10977 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010978 sanitized.setUids(null);
10979 sanitized.setAdministratorUids(new int[0]);
10980 sanitized.setOwnerUid(Process.INVALID_UID);
10981 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080010982 }
10983
Cody Kestingf1120be2020-08-03 18:01:40 -070010984 /**
10985 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
10986 *
10987 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
10988 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010989 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070010990 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010991 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010992 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010993 mConnectivityDiagnosticsCallbacks.entrySet()) {
10994 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
10995 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070010996
James Mattis64b8b0f2020-11-24 17:40:49 -080010997 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070010998 if (!nai.satisfies(nri.mRequests.get(0))) {
10999 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011000 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011001
11002 // UID for this callback must either be:
11003 // - INVALID_UID (which sends callbacks to all UIDs), or
11004 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11005 // notified as a result)
11006 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11007 continue;
11008 }
11009
11010 if (!checkConnectivityDiagnosticsPermissions(
11011 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11012 continue;
11013 }
11014
11015 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011016 }
11017 return results;
11018 }
11019
Cody Kesting7474f672021-05-11 14:22:40 -070011020 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11021 @NonNull NetworkAgentInfo nai) {
11022 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11023 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11024 }
11025
Cody Kesting160ef392021-05-05 13:17:22 -070011026 private boolean hasLocationPermission(String packageName, int uid) {
11027 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11028 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11029 // call in a try-catch.
11030 try {
11031 if (!mLocationPermissionChecker.checkLocationPermission(
11032 packageName, null /* featureId */, uid, null /* message */)) {
11033 return false;
11034 }
11035 } catch (SecurityException e) {
11036 return false;
11037 }
11038
11039 return true;
11040 }
11041
11042 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11043 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011044 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011045 && virtual.networkCapabilities.getOwnerUid() == uid
11046 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11047 return true;
11048 }
11049 }
11050
11051 return false;
11052 }
11053
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011054 @VisibleForTesting
11055 boolean checkConnectivityDiagnosticsPermissions(
11056 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
11057 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
11058 return true;
11059 }
11060
Cody Kesting160ef392021-05-05 13:17:22 -070011061 // Administrator UIDs also contains the Owner UID
11062 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11063 if (!CollectionUtils.contains(administratorUids, callbackUid)
11064 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011065 return false;
11066 }
11067
Cody Kesting7474f672021-05-11 14:22:40 -070011068 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11069 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011070 }
11071
Cody Kestingd199a9d2019-12-17 12:55:28 -080011072 @Override
11073 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011074 @NonNull IConnectivityDiagnosticsCallback callback,
11075 @NonNull NetworkRequest request,
11076 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011077 Objects.requireNonNull(callback, "callback must not be null");
11078 Objects.requireNonNull(request, "request must not be null");
11079 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11080
Cody Kesting73708bf2019-12-18 10:57:50 -080011081 if (request.legacyType != TYPE_NONE) {
11082 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11083 + " Please use NetworkCapabilities instead.");
11084 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011085 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011086 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011087
11088 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11089 // and administrator uids to be safe.
11090 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011091 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011092
11093 final NetworkRequest requestWithId =
11094 new NetworkRequest(
11095 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11096
11097 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11098 //
11099 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11100 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11101 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011102 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011103 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011104 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011105
11106 mConnectivityDiagnosticsHandler.sendMessage(
11107 mConnectivityDiagnosticsHandler.obtainMessage(
11108 ConnectivityDiagnosticsHandler
11109 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11110 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011111 }
11112
11113 @Override
11114 public void unregisterConnectivityDiagnosticsCallback(
11115 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011116 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011117 mConnectivityDiagnosticsHandler.sendMessage(
11118 mConnectivityDiagnosticsHandler.obtainMessage(
11119 ConnectivityDiagnosticsHandler
11120 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011121 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011122 0,
11123 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011124 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011125
Yan Yanfe96dde2022-12-05 23:00:01 +000011126 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11127 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11128 if (underlyingNetworks == null) return false;
11129
11130 for (Network network : underlyingNetworks) {
11131 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11132 return true;
11133 }
11134 }
11135 return false;
11136 }
11137
Cody Kestingf53a0752020-04-15 12:33:28 -070011138 @Override
11139 public void simulateDataStall(int detectionMethod, long timestampMillis,
11140 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011141 Objects.requireNonNull(network, "network must not be null");
11142 Objects.requireNonNull(extras, "extras must not be null");
11143
paulhu3ffffe72021-09-16 10:15:22 +080011144 enforceAnyPermissionOf(mContext,
11145 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011146 android.Manifest.permission.NETWORK_STACK);
11147 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011148 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11149 throw new SecurityException(
11150 "Data Stall simulation is only possible for test networks or networks built on"
11151 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011152 }
11153
11154 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011155 if (nai == null
11156 || (nai.creatorUid != mDeps.getCallingUid()
11157 && nai.creatorUid != Process.SYSTEM_UID)) {
11158 throw new SecurityException(
11159 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011160 }
11161
Cody Kesting652e3ec2020-05-21 12:08:21 -070011162 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11163 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11164 // Data Stall information as a DataStallReportParcelable and passing to
11165 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11166 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011167 final DataStallReportParcelable p = new DataStallReportParcelable();
11168 p.timestampMillis = timestampMillis;
11169 p.detectionMethod = detectionMethod;
11170
11171 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11172 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11173 }
11174 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11175 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11176 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11177 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11178 }
11179
Serik Beketayevec8ad212020-12-07 22:43:07 -080011180 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011181 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011182
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011183 /**
11184 * Class to hold the information for network activity change event from idle timers
11185 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
11186 */
11187 private static final class NetworkActivityParams {
11188 public final boolean isActive;
11189 // Label used for idle timer. Transport type is used as label.
11190 // label is int since NMS was using the identifier as int, and it has not been changed
11191 public final int label;
11192 public final long timestampNs;
11193 // Uid represents the uid that was responsible for waking the radio.
11194 // -1 for no uid and uid is -1 if isActive is false.
11195 public final int uid;
11196
11197 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
11198 this.isActive = isActive;
11199 this.label = label;
11200 this.timestampNs = timestampNs;
11201 this.uid = uid;
11202 }
11203 }
11204
lucaslin66f44212021-02-23 01:12:55 +080011205 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11206 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011207 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080011208 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011209 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
11210 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080011211 }
lucaslin37a16d92021-01-21 19:48:09 +080011212
11213 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011214 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011215 mHandler.post(() -> {
11216 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
11217 nai.clatd.interfaceLinkStateChanged(iface, up);
11218 }
11219 });
lucaslin37a16d92021-01-21 19:48:09 +080011220 }
11221
11222 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011223 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011224 mHandler.post(() -> {
11225 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
11226 nai.clatd.interfaceRemoved(iface);
11227 }
11228 });
lucaslin66f44212021-02-23 01:12:55 +080011229 }
11230 }
11231
lucaslin1a8b4c62021-01-21 02:02:55 +080011232 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11233
11234 /**
11235 * Class used for updating network activity tracking with netd and notify network activity
11236 * changes.
11237 */
11238 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011239 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011240 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011241 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011242 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080011243 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11244 new RemoteCallbackList<>();
11245 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090011246 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011247 // If there is no default network, default network is considered active to keep the existing
11248 // behavior. Initial value is used until first connect to the default network.
11249 private volatile boolean mIsDefaultNetworkActive = true;
Chalard Jean46bfbf02022-02-02 00:56:25 +090011250 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080011251
Chalard Jean46bfbf02022-02-02 00:56:25 +090011252 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011253 public final int timeout;
11254 public final int transportType;
11255
11256 IdleTimerParams(int timeout, int transport) {
11257 this.timeout = timeout;
11258 this.transportType = transport;
11259 }
11260 }
11261
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011262 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011263 @NonNull Handler handler) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011264 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011265 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011266 mHandler = handler;
11267 }
11268
11269 private void ensureRunningOnConnectivityServiceThread() {
11270 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
11271 throw new IllegalStateException("Not running on ConnectivityService thread: "
11272 + Thread.currentThread().getName());
11273 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011274 }
11275
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011276 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011277 ensureRunningOnConnectivityServiceThread();
Motomu Utsumic298cf02023-05-31 12:06:12 +090011278 if (mActiveIdleTimers.isEmpty()) {
11279 // This activity change is not for the current default network.
11280 // This can happen if netd callback post activity change event message but
11281 // the default network is lost before processing this message.
11282 return;
11283 }
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011284 sendDataActivityBroadcast(transportTypeToLegacyType(activityParams.label),
11285 activityParams.isActive, activityParams.timestampNs);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011286 mIsDefaultNetworkActive = activityParams.isActive;
11287 if (mIsDefaultNetworkActive) {
11288 reportNetworkActive();
lucaslin66f44212021-02-23 01:12:55 +080011289 }
11290 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011291
lucaslin1193a5d2021-01-21 02:04:15 +080011292 private void reportNetworkActive() {
11293 final int length = mNetworkActivityListeners.beginBroadcast();
11294 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
11295 try {
11296 for (int i = 0; i < length; i++) {
11297 try {
11298 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
11299 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011300 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080011301 }
11302 }
11303 } finally {
11304 mNetworkActivityListeners.finishBroadcast();
11305 }
11306 }
11307
lucaslin1a8b4c62021-01-21 02:02:55 +080011308 // This is deprecated and only to support legacy use cases.
11309 private int transportTypeToLegacyType(int type) {
11310 switch (type) {
11311 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011312 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080011313 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011314 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080011315 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011316 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080011317 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011318 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080011319 default:
11320 loge("Unexpected transport in transportTypeToLegacyType: " + type);
11321 }
11322 return ConnectivityManager.TYPE_NONE;
11323 }
11324
11325 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
11326 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
11327 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
11328 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
11329 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
11330 final long ident = Binder.clearCallingIdentity();
11331 try {
11332 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
11333 RECEIVE_DATA_ACTIVITY_CHANGE,
11334 null /* resultReceiver */,
11335 null /* scheduler */,
11336 0 /* initialCode */,
11337 null /* initialData */,
11338 null /* initialExtra */);
11339 } finally {
11340 Binder.restoreCallingIdentity(ident);
11341 }
11342 }
11343
11344 /**
11345 * Setup data activity tracking for the given network.
11346 *
11347 * Every {@code setupDataActivityTracking} should be paired with a
11348 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090011349 *
11350 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080011351 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090011352 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011353 final String iface = networkAgent.linkProperties.getInterfaceName();
11354
11355 final int timeout;
11356 final int type;
11357
11358 if (networkAgent.networkCapabilities.hasTransport(
11359 NetworkCapabilities.TRANSPORT_CELLULAR)) {
11360 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011361 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080011362 10);
11363 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11364 } else if (networkAgent.networkCapabilities.hasTransport(
11365 NetworkCapabilities.TRANSPORT_WIFI)) {
11366 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011367 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080011368 15);
11369 type = NetworkCapabilities.TRANSPORT_WIFI;
11370 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011371 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080011372 }
11373
lucaslinb961efc2021-01-21 02:03:17 +080011374 updateRadioPowerState(true /* isActive */, type);
11375
lucaslin1a8b4c62021-01-21 02:02:55 +080011376 if (timeout > 0 && iface != null) {
11377 try {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011378 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
11379 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
Motomu Utsumi6225d572023-05-29 15:08:57 +090011380 return true;
lucaslin1a8b4c62021-01-21 02:02:55 +080011381 } catch (Exception e) {
11382 // You shall not crash!
11383 loge("Exception in setupDataActivityTracking " + e);
11384 }
11385 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011386 return false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011387 }
11388
11389 /**
11390 * Remove data activity tracking when network disconnects.
11391 */
11392 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
11393 final String iface = networkAgent.linkProperties.getInterfaceName();
11394 final NetworkCapabilities caps = networkAgent.networkCapabilities;
11395
lucaslinb961efc2021-01-21 02:03:17 +080011396 if (iface == null) return;
11397
11398 final int type;
11399 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
11400 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11401 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
11402 type = NetworkCapabilities.TRANSPORT_WIFI;
11403 } else {
11404 return; // do not track any other networks
11405 }
11406
11407 try {
11408 updateRadioPowerState(false /* isActive */, type);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011409 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
11410 if (params == null) {
11411 // IdleTimer is not added if the configured timeout is 0 or negative value
11412 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080011413 }
Motomu Utsumic298cf02023-05-31 12:06:12 +090011414 // The call fails silently if no idle timer setup for this interface
11415 mNetd.idletimerRemoveInterface(iface, params.timeout,
11416 Integer.toString(params.transportType));
lucaslinb961efc2021-01-21 02:03:17 +080011417 } catch (Exception e) {
11418 // You shall not crash!
11419 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080011420 }
11421 }
11422
Motomu Utsumi6225d572023-05-29 15:08:57 +090011423 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
11424 boolean hasIdleTimer) {
11425 if (defaultNetwork != null) {
11426 mIsDefaultNetworkActive = true;
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011427 // Callbacks are called only when the network has the idle timer.
11428 if (hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011429 reportNetworkActive();
11430 }
11431 } else {
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011432 // If there is no default network, default network is considered active to keep the
11433 // existing behavior.
11434 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090011435 }
11436 }
11437
lucaslin1a8b4c62021-01-21 02:02:55 +080011438 /**
11439 * Update data activity tracking when network state is updated.
11440 */
11441 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
11442 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011443 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi6225d572023-05-29 15:08:57 +090011444 boolean hasIdleTimer = false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011445 if (newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011446 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080011447 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011448 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
lucaslin1a8b4c62021-01-21 02:02:55 +080011449 if (oldNetwork != null) {
11450 removeDataActivityTracking(oldNetwork);
11451 }
11452 }
lucaslinb961efc2021-01-21 02:03:17 +080011453
11454 private void updateRadioPowerState(boolean isActive, int transportType) {
11455 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
11456 switch (transportType) {
11457 case NetworkCapabilities.TRANSPORT_CELLULAR:
11458 bs.reportMobileRadioPowerState(isActive, NO_UID);
11459 break;
11460 case NetworkCapabilities.TRANSPORT_WIFI:
11461 bs.reportWifiRadioPowerState(isActive, NO_UID);
11462 break;
11463 default:
11464 logw("Untracked transport type:" + transportType);
11465 }
11466 }
lucaslin1193a5d2021-01-21 02:04:15 +080011467
11468 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011469 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080011470 }
11471
11472 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
11473 mNetworkActivityListeners.register(l);
11474 }
11475
11476 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
11477 mNetworkActivityListeners.unregister(l);
11478 }
lucaslin012f7a12021-01-21 02:04:35 +080011479
11480 public void dump(IndentingPrintWriter pw) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011481 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
11482 pw.println("Idle timers:");
11483 try {
11484 for (Map.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
lucaslin012f7a12021-01-21 02:04:35 +080011485 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
11486 final IdleTimerParams params = ent.getValue();
11487 pw.print(" timeout="); pw.print(params.timeout);
11488 pw.print(" type="); pw.println(params.transportType);
11489 }
Motomu Utsumic298cf02023-05-31 12:06:12 +090011490 } catch (Exception e) {
11491 // mActiveIdleTimers should only be accessed from handler thread, except dump().
11492 // As dump() is never called in normal usage, it would be needlessly expensive
11493 // to lock the collection only for its benefit.
11494 // Also, mActiveIdleTimers is not expected to be updated frequently.
11495 // So catching the exception and logging.
11496 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080011497 }
11498 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011499 }
James Mattis47db0582021-01-01 14:13:35 -080011500
Daniel Brightf9e945b2020-06-15 16:10:01 -070011501 /**
11502 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
11503 *
11504 * @param socketInfo the socket information
11505 * @param callback the callback to register
11506 */
11507 @Override
11508 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
11509 @NonNull final IQosCallback callback) {
11510 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
11511 if (nai == null || nai.networkCapabilities == null) {
11512 try {
11513 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
11514 } catch (final RemoteException ex) {
11515 loge("registerQosCallbackInternal: RemoteException", ex);
11516 }
11517 return;
11518 }
11519 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
11520 }
11521
11522 /**
11523 * Register a {@link IQosCallback} with base {@link QosFilter}.
11524 *
11525 * @param filter the filter to register
11526 * @param callback the callback to register
11527 * @param nai the agent information related to the filter's network
11528 */
11529 @VisibleForTesting
11530 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
11531 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011532 Objects.requireNonNull(filter, "filter must be non-null");
11533 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011534
11535 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080011536 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
11537 // on this network is unregistered when the app loses permission or b) no QoS
11538 // callbacks are sent for restricted networks unless the app currently has permission
11539 // to access restricted networks.
11540 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070011541 }
11542 mQosCallbackTracker.registerCallback(callback, filter, nai);
11543 }
11544
11545 /**
11546 * Unregisters the given callback.
11547 *
11548 * @param callback the callback to unregister
11549 */
11550 @Override
11551 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011552 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011553 mQosCallbackTracker.unregisterCallback(callback);
11554 }
James Mattis47db0582021-01-01 14:13:35 -080011555
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011556 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
11557 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
11558 // Enterprise device can be fully managed like device owner and such use case
11559 // also should be supported. Calling app check for work profile and fully managed device
11560 // is already done in DevicePolicyManager.
11561 // This check is an extra caution to be sure device is fully managed or not.
11562 final UserManager um = mContext.getSystemService(UserManager.class);
11563 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
11564 if (um.isManagedProfile(profile.getIdentifier())) {
11565 return true;
11566 }
Chalard Jeandf29a852023-05-29 17:02:43 +090011567 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011568 return false;
11569 }
11570
James Mattis45d81842021-01-10 14:24:24 -080011571 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011572 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011573 *
11574 * See the documentation for the individual preferences for a description of the supported
11575 * behaviors.
11576 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011577 * @param profile If the device owner is set, any profile is allowed.
11578 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011579 * @param preferences the list of profile network preferences for the
11580 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011581 * @param listener an optional listener to listen for completion of the operation.
11582 */
11583 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011584 public void setProfileNetworkPreferences(
11585 @NonNull final UserHandle profile,
11586 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090011587 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011588 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011589 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011590
11591 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011592 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11593 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11594 .build();
11595 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011596 }
11597
paulhu3ffffe72021-09-16 10:15:22 +080011598 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011599 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011600 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011601 }
11602 if (profile.getIdentifier() < 0) {
11603 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11604 + "UserHandle.CURRENT not supported)");
11605 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011606 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11607 throw new IllegalArgumentException("Profile must be a managed profile "
11608 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011609 }
paulhuaa0743d2021-05-26 21:56:03 +080011610
Chalard Jean0606fc82022-12-14 20:34:43 +090011611 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011612 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011613 for (final ProfileNetworkPreference preference : preferences) {
11614 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011615 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011616 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011617 switch (preference.getPreference()) {
11618 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11619 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011620 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011621 if (preference.getPreferenceEnterpriseId() != 0) {
11622 throw new IllegalArgumentException(
11623 "Invalid enterprise identifier in setProfileNetworkPreferences");
11624 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011625 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011626 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11627 blockingNonEnterprise = true;
11628 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011629 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11630 allowFallback = false;
11631 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011632 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011633 // This code is needed even though there is a check later on,
11634 // because isRangeAlreadyInPreferenceList assumes that every preference
11635 // has a UID list.
11636 if (hasDefaultPreference) {
11637 throw new IllegalArgumentException(
11638 "Default profile preference should not be set along with other "
11639 + "preference");
11640 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011641 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11642 throw new IllegalArgumentException(
11643 "Invalid enterprise identifier in setProfileNetworkPreferences");
11644 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011645 final Set<UidRange> uidRangeSet =
11646 getUidListToBeAppliedForNetworkPreference(profile, preference);
11647 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11648 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11649 } else {
11650 throw new IllegalArgumentException(
11651 "Overlapping uid range in setProfileNetworkPreferences");
11652 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011653 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011654 nc.addEnterpriseId(
11655 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011656 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11657 break;
11658 default:
11659 throw new IllegalArgumentException(
11660 "Invalid preference in setProfileNetworkPreferences");
11661 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011662 preferenceList.add(new ProfileNetworkPreferenceInfo(
11663 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011664 if (hasDefaultPreference && preferenceList.size() > 1) {
11665 throw new IllegalArgumentException(
11666 "Default profile preference should not be set along with other preference");
11667 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011668 }
11669 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011670 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011671 }
11672
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011673 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
11674 @NonNull final UserHandle profile,
11675 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
11676 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080011677 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
11678 profileNetworkPreference.getIncludedUids());
11679
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011680 if (uidRangeSet.size() > 0) {
11681 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
11682 throw new IllegalArgumentException(
11683 "Allow uid range is outside the uid range of profile.");
11684 }
11685 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080011686 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011687 profileNetworkPreference.getExcludedUids());
11688 if (disallowUidRangeSet.size() > 0) {
11689 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
11690 throw new IllegalArgumentException(
11691 "disallow uid range is outside the uid range of profile.");
11692 }
11693 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
11694 disallowUidRangeSet);
11695 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011696 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011697 uidRangeSet.add(profileUids);
11698 }
11699 }
11700 return uidRangeSet;
11701 }
11702
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011703 private boolean isEnterpriseIdentifierValid(
11704 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011705 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011706 return true;
11707 }
11708 return false;
11709 }
11710
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011711 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090011712 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011713 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090011714 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011715 // The NRI for a user should contain the request for capabilities.
11716 // If fallback to default network is needed then NRI should include
11717 // the request for the default network. Create an image of it to
11718 // have the correct UIDs in it (also a request can only be part of one NRI, because
11719 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011720 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
11721 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011722 if (pref.allowFallback) {
11723 nrs.add(createDefaultInternetRequestForTransport(
11724 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11725 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011726 if (VDBG) {
11727 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
11728 pref.capabilities.getUids()));
11729 }
11730
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011731 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080011732 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080011733 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011734 result.add(nri);
11735 }
11736 return result;
11737 }
11738
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011739 /**
11740 * Compare if the given UID range sets have the same UIDs.
11741 *
11742 */
11743 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090011744 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011745 @NonNull Set<UidRange> uidRangeSet) {
11746 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
11747 return false;
11748 }
Chalard Jean0606fc82022-12-14 20:34:43 +090011749 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011750 if (UidRangeUtils.doesRangeSetOverlap(
11751 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
11752 return true;
11753 }
11754 }
11755 return false;
11756 }
11757
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011758 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090011759 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011760 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011761 /*
11762 * handleSetProfileNetworkPreference is always called for single user.
11763 * preferenceList only contains preferences for different uids within the same user
11764 * (enforced by getUidListToBeAppliedForNetworkPreference).
11765 * Clear all the existing preferences for the user before applying new preferences.
11766 *
11767 */
Chalard Jean0606fc82022-12-14 20:34:43 +090011768 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
11769 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011770 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
11771 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011772
paulhu74128522021-09-28 02:29:03 +000011773 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
11774 addPerAppDefaultNetworkRequests(
11775 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080011776 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080011777
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011778 // Finally, rematch.
11779 rematchAllNetworksAndRequests();
11780
11781 if (null != listener) {
11782 try {
11783 listener.onComplete();
11784 } catch (RemoteException e) {
11785 loge("Listener for setProfileNetworkPreference has died");
11786 }
11787 }
11788 }
11789
paulhu51f77dc2021-06-07 02:34:20 +000011790 @VisibleForTesting
11791 @NonNull
11792 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
11793 @NonNull final Set<Integer> uids) {
11794 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11795 if (uids.size() == 0) {
11796 // Should not create NetworkRequestInfo if no preferences. Without uid range in
11797 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
11798 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
11799 return nris;
11800 }
11801
11802 final List<NetworkRequest> requests = new ArrayList<>();
11803 // The NRI should be comprised of two layers:
11804 // - The request for the mobile network preferred.
11805 // - The request for the default network, for fallback.
11806 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090011807 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000011808 requests.add(createDefaultInternetRequestForTransport(
11809 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11810 final Set<UidRange> ranges = new ArraySet<>();
11811 for (final int uid : uids) {
11812 ranges.add(new UidRange(uid, uid));
11813 }
11814 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080011815 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080011816 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000011817 return nris;
11818 }
11819
11820 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000011821 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000011822 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
11823 addPerAppDefaultNetworkRequests(
11824 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000011825 // Finally, rematch.
11826 rematchAllNetworksAndRequests();
11827 }
11828
Patrick Rohr2857ac42022-01-21 14:58:16 +010011829 private void handleIngressRateLimitChanged() {
11830 final long oldIngressRateLimit = mIngressRateLimit;
11831 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
11832 mContext);
11833 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
11834 if (canNetworkBeRateLimited(networkAgent)) {
11835 // If rate limit has previously been enabled, remove the old limit first.
11836 if (oldIngressRateLimit >= 0) {
11837 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
11838 }
11839 if (mIngressRateLimit >= 0) {
11840 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
11841 mIngressRateLimit);
11842 }
11843 }
11844 }
11845 }
11846
11847 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090011848 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090011849 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090011850
Patrick Rohrff3b3f82022-02-09 15:15:52 +010011851 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
11852 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
11853 // internet connectivity can be rate limited.
11854 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
11855 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010011856 return false;
11857 }
11858
11859 final String iface = networkAgent.linkProperties.getInterfaceName();
11860 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010011861 // This may happen in tests, but if there is no interface then there is nothing that
11862 // can be rate limited.
11863 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010011864 return false;
11865 }
11866 return true;
11867 }
11868
James Mattis45d81842021-01-10 14:24:24 -080011869 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080011870 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
11871 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080011872 }
11873
11874 /**
11875 * Used by automotive devices to set the network preferences used to direct traffic at an
11876 * application level as per the given OemNetworkPreferences. An example use-case would be an
11877 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
11878 * vehicle via a particular network.
11879 *
11880 * Calling this will overwrite the existing preference.
11881 *
James Mattisda32cfe2021-01-26 16:23:52 -080011882 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090011883 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080011884 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080011885 */
James Mattis47db0582021-01-01 14:13:35 -080011886 @Override
James Mattis45d81842021-01-10 14:24:24 -080011887 public void setOemNetworkPreference(
11888 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011889 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080011890
James Mattisfa270db2021-05-31 17:11:10 -070011891 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11892 // Only bypass the permission/device checks if this is a valid test request.
11893 if (isValidTestOemNetworkPreference(preference)) {
11894 enforceManageTestNetworksPermission();
11895 } else {
11896 enforceAutomotiveDevice();
11897 enforceOemNetworkPreferencesPermission();
11898 validateOemNetworkPreferences(preference);
11899 }
James Mattis45d81842021-01-10 14:24:24 -080011900
James Mattis45d81842021-01-10 14:24:24 -080011901 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
11902 new Pair<>(preference, listener)));
11903 }
11904
James Mattisfa270db2021-05-31 17:11:10 -070011905 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000011906 * Sets the specified UIDs to get/receive the VPN as the only default network.
11907 *
11908 * Calling this will overwrite the existing network preference for this session, and the
11909 * specified UIDs won't get any default network when no VPN is connected.
11910 *
11911 * @param session The VPN session which manages the passed UIDs.
11912 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
11913 * setting for this session if the array is empty. Null is not allowed, the
11914 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
11915 * @hide
11916 */
11917 @Override
11918 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
11919 Objects.requireNonNull(ranges);
11920 enforceNetworkStackOrSettingsPermission();
11921 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
11922 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
11923 throw new IllegalArgumentException(
11924 "setVpnNetworkPreference: Passed UID ranges overlap");
11925 }
11926
11927 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
11928 new VpnNetworkPreferenceInfo(session,
11929 new ArraySet<UidRange>(Arrays.asList(ranges)))));
11930 }
11931
11932 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
11933 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
11934
11935 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
11936 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
11937
11938 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
11939 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
11940 // Finally, rematch.
11941 rematchAllNetworksAndRequests();
11942 }
11943
11944 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
11945 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
11946 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11947 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
11948 final List<NetworkRequest> requests = new ArrayList<>();
11949 // Request VPN only, so other networks won't be the fallback options when VPN is not
11950 // connected temporarily.
11951 requests.add(createVpnRequest());
11952 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
11953 setNetworkRequestUids(requests, uidRanges);
11954 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
11955 }
11956 return nris;
11957 }
11958
11959 /**
James Mattisfa270db2021-05-31 17:11:10 -070011960 * Check the validity of an OEM network preference to be used for testing purposes.
11961 * @param preference the preference to validate
11962 * @return true if this is a valid OEM network preference test request.
11963 */
11964 private boolean isValidTestOemNetworkPreference(
11965 @NonNull final OemNetworkPreferences preference) {
11966 // Allow for clearing of an existing OemNetworkPreference used for testing.
11967 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
11968 // changes after this check is complete. This is an unlikely scenario as calling of this API
11969 // is controlled by the OEM therefore the added complexity is not worth adding given those
11970 // circumstances. That said, it is an edge case to be aware of hence this comment.
11971 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
11972 && isTestOemNetworkPreference(mOemNetworkPreferences);
11973 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
11974 }
11975
11976 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
11977 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
11978 return prefMap.size() == 1
11979 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
11980 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
11981 }
11982
James Mattis45d81842021-01-10 14:24:24 -080011983 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
11984 for (@OemNetworkPreferences.OemNetworkPreference final int pref
11985 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070011986 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
11987 throw new IllegalArgumentException(
11988 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
11989 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080011990 }
11991 }
11992 }
11993
11994 private void handleSetOemNetworkPreference(
11995 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011996 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080011997 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11998 if (DBG) {
11999 log("set OEM network preferences :" + preference.toString());
12000 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012001
James Mattiscb1e0362021-04-06 17:07:42 -070012002 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012003 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12004 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12005 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012006 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012007
12008 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012009 try {
12010 listener.onComplete();
12011 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012012 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012013 }
James Mattis45d81842021-01-10 14:24:24 -080012014 }
12015 }
12016
paulhu74128522021-09-28 02:29:03 +000012017 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012018 // Skip the requests which are set by other network preference. Because the uid range rules
12019 // should stay in netd.
12020 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012021 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012022 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012023 }
12024
James Mattis3ce3d3c2021-02-09 18:18:28 -080012025 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12026 ensureRunningOnConnectivityServiceThread();
12027 mDefaultNetworkRequests.addAll(nris);
12028 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12029 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012030 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012031 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12032 nrisToRegister.addAll(
12033 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12034 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012035 }
12036
12037 /**
12038 * All current requests that are tracking the default network need to be assessed as to whether
12039 * or not the current set of per-application default requests will be changing their default
12040 * network. If so, those requests will need to be updated so that they will send callbacks for
12041 * default network changes at the appropriate time. Additionally, those requests tracking the
12042 * default that were previously updated by this flow will need to be reassessed.
12043 * @return the nris which will need to be updated.
12044 */
12045 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12046 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12047 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12048 // same nri in the map's values for each of its NetworkRequest objects.
12049 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012050 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012051 // Include this nri if it is currently being tracked.
12052 if (isPerAppTrackedNri(nri)) {
12053 defaultCallbackRequests.add(nri);
12054 continue;
12055 }
12056 // We only track callbacks for requests tracking the default.
12057 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12058 continue;
12059 }
12060 // Include this nri if it will be tracked by the new per-app default requests.
12061 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012062 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012063 if (isNriGoingToBeTracked) {
12064 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012065 }
12066 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012067 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012068 }
12069
James Mattis3ce3d3c2021-02-09 18:18:28 -080012070 /**
12071 * Create nris for those network requests that are currently tracking the default network that
12072 * are being controlled by a per-application default.
12073 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12074 * foundation when creating the nri. Important items include the calling uid's original
12075 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12076 * requests are assumed to have already been validated as needing to be updated.
12077 * @return the Set of nris to use when registering network requests.
12078 */
12079 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12080 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12081 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12082 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12083 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012084 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012085
Chalard Jean9473c982021-07-29 20:03:04 +090012086 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012087 if (trackingNri == mDefaultRequest) {
12088 callbackRequestsToRegister.add(new NetworkRequestInfo(
12089 callbackRequest,
12090 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12091 continue;
12092 }
12093
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012094 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012095 callbackRequestsToRegister.add(new NetworkRequestInfo(
12096 callbackRequest,
12097 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012098 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012099 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012100 }
12101 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012102 }
12103
Chalard Jean17215832021-03-01 14:06:28 +090012104 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12105 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012106 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012107 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012108 }
12109 }
12110
James Mattis45d81842021-01-10 14:24:24 -080012111 /**
12112 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12113 */
12114 @VisibleForTesting
12115 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012116 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080012117 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012118 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080012119 final SparseArray<Set<Integer>> uids =
12120 createUidsFromOemNetworkPreferences(preference);
12121 for (int i = 0; i < uids.size(); i++) {
12122 final int key = uids.keyAt(i);
12123 final Set<Integer> value = uids.valueAt(i);
12124 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
12125 // No need to add an nri without any requests.
12126 if (0 == nri.mRequests.size()) {
12127 continue;
12128 }
12129 nris.add(nri);
12130 }
12131
12132 return nris;
12133 }
12134
12135 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
12136 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070012137 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080012138 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080012139 final List<UserHandle> users =
12140 mContext.getSystemService(UserManager.class).getUserHandles(true);
12141 if (null == users || users.size() == 0) {
12142 if (VDBG || DDBG) {
12143 log("No users currently available for setting the OEM network preference.");
12144 }
James Mattisb6b6a432021-06-01 22:30:36 -070012145 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080012146 }
James Mattis45d81842021-01-10 14:24:24 -080012147 for (final Map.Entry<String, Integer> entry :
12148 preference.getNetworkPreferences().entrySet()) {
12149 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070012150 // Add the rules for all users as this policy is device wide.
12151 for (final UserHandle user : users) {
12152 try {
12153 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
12154 if (!prefToUids.contains(pref)) {
12155 prefToUids.put(pref, new ArraySet<>());
12156 }
12157 prefToUids.get(pref).add(uid);
12158 } catch (PackageManager.NameNotFoundException e) {
12159 // Although this may seem like an error scenario, it is ok that uninstalled
12160 // packages are sent on a network preference as the system will watch for
12161 // package installations associated with this network preference and update
12162 // accordingly. This is done to minimize race conditions on app install.
12163 continue;
James Mattis45d81842021-01-10 14:24:24 -080012164 }
James Mattis45d81842021-01-10 14:24:24 -080012165 }
12166 }
James Mattisb6b6a432021-06-01 22:30:36 -070012167 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080012168 }
12169
12170 private NetworkRequestInfo createNriFromOemNetworkPreferences(
12171 @OemNetworkPreferences.OemNetworkPreference final int preference,
12172 @NonNull final Set<Integer> uids) {
12173 final List<NetworkRequest> requests = new ArrayList<>();
12174 // Requests will ultimately be evaluated by order of insertion therefore it matters.
12175 switch (preference) {
12176 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
12177 requests.add(createUnmeteredNetworkRequest());
12178 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070012179 requests.add(createDefaultInternetRequestForTransport(
12180 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080012181 break;
12182 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
12183 requests.add(createUnmeteredNetworkRequest());
12184 requests.add(createOemPaidNetworkRequest());
12185 break;
12186 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
12187 requests.add(createOemPaidNetworkRequest());
12188 break;
12189 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
12190 requests.add(createOemPrivateNetworkRequest());
12191 break;
James Mattisfa270db2021-05-31 17:11:10 -070012192 case OEM_NETWORK_PREFERENCE_TEST:
12193 requests.add(createUnmeteredNetworkRequest());
12194 requests.add(createTestNetworkRequest());
12195 requests.add(createDefaultRequest());
12196 break;
12197 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
12198 requests.add(createTestNetworkRequest());
12199 break;
James Mattis45d81842021-01-10 14:24:24 -080012200 default:
12201 // This should never happen.
12202 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
12203 + " called with invalid preference of " + preference);
12204 }
12205
James Mattisfa270db2021-05-31 17:11:10 -070012206 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090012207 for (final int uid : uids) {
12208 ranges.add(new UidRange(uid, uid));
12209 }
12210 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080012211 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080012212 }
12213
12214 private NetworkRequest createUnmeteredNetworkRequest() {
12215 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12216 .addCapability(NET_CAPABILITY_NOT_METERED)
12217 .addCapability(NET_CAPABILITY_VALIDATED);
12218 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
12219 }
12220
12221 private NetworkRequest createOemPaidNetworkRequest() {
12222 // NET_CAPABILITY_OEM_PAID is a restricted capability.
12223 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12224 .addCapability(NET_CAPABILITY_OEM_PAID)
12225 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12226 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12227 }
12228
12229 private NetworkRequest createOemPrivateNetworkRequest() {
12230 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
12231 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12232 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
12233 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12234 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12235 }
12236
12237 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070012238 final NetworkCapabilities netcap = new NetworkCapabilities();
12239 netcap.addCapability(NET_CAPABILITY_INTERNET);
12240 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
12241 return netcap;
12242 }
12243
12244 private NetworkRequest createTestNetworkRequest() {
12245 final NetworkCapabilities netcap = new NetworkCapabilities();
12246 netcap.clearAll();
12247 netcap.addTransportType(TRANSPORT_TEST);
12248 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080012249 }
James Mattis47db0582021-01-01 14:13:35 -080012250 }
markchien738ad912021-12-09 18:15:45 +080012251
12252 @Override
12253 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
12254 enforceNetworkStackOrSettingsPermission();
12255
12256 try {
12257 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012258 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012259 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012260 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012261 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012262 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012263 throw new IllegalStateException(e);
12264 }
12265 }
12266
12267 @Override
12268 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
12269 enforceNetworkStackOrSettingsPermission();
12270
12271 try {
12272 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012273 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012274 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012275 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012276 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012277 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012278 throw new IllegalStateException(e);
12279 }
12280 }
markchiene1561fa2021-12-09 22:00:56 +080012281
12282 @Override
markchien3c04e662022-03-22 16:29:56 +080012283 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080012284 enforceNetworkStackOrSettingsPermission();
12285
markchien3c04e662022-03-22 16:29:56 +080012286 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
12287 int firewallRule = getFirewallRuleType(chain, rule);
12288
12289 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
12290 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
12291 }
12292
markchiene1561fa2021-12-09 22:00:56 +080012293 try {
markchien3c04e662022-03-22 16:29:56 +080012294 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012295 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080012296 throw new IllegalStateException(e);
12297 }
12298 }
markchien98a6f952022-01-13 23:43:53 +080012299
Motomu Utsumi900b8062023-01-19 16:16:49 +090012300 @Override
12301 public int getUidFirewallRule(final int chain, final int uid) {
12302 enforceNetworkStackOrSettingsPermission();
12303 return mBpfNetMaps.getUidRule(chain, uid);
12304 }
12305
markchien3c04e662022-03-22 16:29:56 +080012306 private int getFirewallRuleType(int chain, int rule) {
12307 final int defaultRule;
12308 switch (chain) {
12309 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000012310 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
12311 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000012312 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080012313 defaultRule = FIREWALL_RULE_ALLOW;
12314 break;
12315 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
12316 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
12317 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
12318 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
12319 defaultRule = FIREWALL_RULE_DENY;
12320 break;
12321 default:
12322 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
12323 }
12324 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
12325
12326 return rule;
12327 }
12328
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012329 private void closeSocketsForFirewallChainLocked(final int chain)
12330 throws ErrnoException, SocketException, InterruptedIOException {
12331 if (mBpfNetMaps.isFirewallAllowList(chain)) {
12332 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
12333 // So, close all non-system socket owned by uids that are not explicitly allowed
12334 Set<Range<Integer>> ranges = new ArraySet<>();
12335 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
12336 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
12337 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
12338 } else {
12339 // Denylist means the firewall allows all by default, uids must be explicitly denied
12340 // So, close socket owned by uids that are explicitly denied
12341 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
12342 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
12343 }
12344 }
12345
markchien98a6f952022-01-13 23:43:53 +080012346 @Override
12347 public void setFirewallChainEnabled(final int chain, final boolean enable) {
12348 enforceNetworkStackOrSettingsPermission();
12349
12350 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012351 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012352 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080012353 throw new IllegalStateException(e);
12354 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012355
Chalard Jeandf29a852023-05-29 17:02:43 +090012356 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012357 try {
12358 closeSocketsForFirewallChainLocked(chain);
12359 } catch (ErrnoException | SocketException | InterruptedIOException e) {
12360 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
12361 }
12362 }
markchien98a6f952022-01-13 23:43:53 +080012363 }
12364
markchien00a0bed2022-01-13 23:46:13 +080012365 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012366 public boolean getFirewallChainEnabled(final int chain) {
12367 enforceNetworkStackOrSettingsPermission();
12368
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000012369 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012370 }
12371
12372 @Override
markchien00a0bed2022-01-13 23:46:13 +080012373 public void replaceFirewallChain(final int chain, final int[] uids) {
12374 enforceNetworkStackOrSettingsPermission();
12375
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000012376 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080012377 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080012378
12379 @Override
12380 public IBinder getCompanionDeviceManagerProxyService() {
12381 enforceNetworkStackPermission(mContext);
12382 return mCdmps;
12383 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070012384}