blob: bc76bf07e12eeec9381cd2af5d944bc344590982 [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000018
Haoyu Baib5da5752012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Mark Fasheh7501e762023-05-04 20:23:11 +000020import static android.app.ActivityManager.UidFrozenStateChangedCallback.UID_FROZEN_STATE_FROZEN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090021import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
22import static android.content.pm.PackageManager.FEATURE_WATCH;
23import static android.content.pm.PackageManager.FEATURE_WIFI;
24import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
Chalard Jean9a396cc2018-02-21 18:43:54 +090025import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090026import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
27import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
28import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
29import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
33import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090034import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
35import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000036import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Jeff Sharkey971cd162011-08-29 16:02:57 -070037import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
markchien3c04e662022-03-22 16:29:56 +080038import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
39import static android.net.ConnectivityManager.FIREWALL_RULE_DEFAULT;
40import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090041import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090042import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090043import static android.net.ConnectivityManager.TYPE_MOBILE;
44import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
45import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
46import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
47import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
48import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
49import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
50import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
51import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
52import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070053import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090054import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070055import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090056import static android.net.ConnectivityManager.TYPE_WIFI;
57import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070058import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070059import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080060import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080061import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080062import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070063import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080064import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040065import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090066import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090067import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090068import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090070import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
71import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060072import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090073import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080074import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090075import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080076import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
77import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080078import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090079import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080080import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
81import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080082import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
83import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
84import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090085import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090086import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060087import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070088import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080089import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090090import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070091import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
92import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070093import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080094import static android.os.Process.VPN_UID;
Motomu Utsumi6f4d8062023-04-21 12:35:22 +090095import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
Patrick Rohr2857ac42022-01-21 14:58:16 +010096import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070097import static android.system.OsConstants.IPPROTO_TCP;
98import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey07e19362017-10-27 17:22:59 -060099
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900100import static com.android.net.module.util.DeviceConfigUtils.TETHERING_MODULE_NAME;
Xiao Ma60142372022-07-16 17:30:20 +0900101import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Junyu Lai4c6fe232023-04-11 11:33:46 +0800102import static com.android.net.module.util.PermissionUtils.checkAnyPermissionOf;
paulhu3ffffe72021-09-16 10:15:22 +0800103import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
104import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
105import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900106
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800107import static java.util.Map.Entry;
108
Chalard Jean5b639762020-03-09 21:25:37 +0900109import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000110import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800111import android.annotation.Nullable;
Michael Groover73f69482023-01-27 11:01:25 -0600112import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800113import android.annotation.TargetApi;
Mark Fasheh7501e762023-05-04 20:23:11 +0000114import android.app.ActivityManager;
115import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800116import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800117import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700118import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700119import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900120import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800121import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700122import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800123import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800124import android.content.ContentResolver;
125import android.content.Context;
126import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700127import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800128import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900129import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700130import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900131import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900132import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700133import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800134import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800135import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800136import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900137import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800138import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900139import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800140import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900141import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800142import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700143import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900144import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800145import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800146import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800147import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800148import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800149import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900150import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900151import android.net.INetworkMonitor;
152import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900153import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900154import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700155import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800156import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900157import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900158import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900159import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800160import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100161import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800162import android.net.NativeNetworkConfig;
163import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800164import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700165import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700166import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900167import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700168import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800169import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700170import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900171import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900172import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000173import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900174import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700175import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900176import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700177import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900178import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700179import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800180import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900181import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700182import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000183import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800184import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900185import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800186import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400187import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700188import android.net.QosCallbackException;
189import android.net.QosFilter;
190import android.net.QosSocketFilter;
191import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700192import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800193import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800194import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800195import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900196import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400197import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800198import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800199import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400200import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800201import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900202import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900203import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900204import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900205import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800206import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900207import android.net.networkstack.ModuleNetworkStackClient;
208import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900209import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800210import android.net.resolv.aidl.DnsHealthEventParcel;
211import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
212import android.net.resolv.aidl.Nat64PrefixEventParcel;
213import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900214import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900215import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800216import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800217import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800218import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700219import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000220import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800221import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700222import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700223import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800224import android.os.Looper;
225import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700226import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700227import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900228import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800229import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700230import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700231import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800232import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700233import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900234import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900235import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700236import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700237import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400238import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800239import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900240import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700241import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700242import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700243import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800244import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900245import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000246import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600247import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900248import android.util.Pair;
Motomu Utsumia20f7602023-03-16 17:04:21 +0900249import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700250import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700251import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800252
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800253import androidx.annotation.RequiresApi;
254
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900255import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400256import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400257import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700258import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900259import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800260import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900261import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800262import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000263import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900264import com.android.net.module.util.BitUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900265import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900266import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100267import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900268import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
269import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900270import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800271import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800272import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100273import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000274import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800275import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
276import com.android.networkstack.apishim.ConstantsShim;
277import com.android.networkstack.apishim.common.BroadcastOptionsShim;
278import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900279import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900280import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000281import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900282import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800283import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800284import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900285import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VAN6ca02962023-02-20 20:10:09 +0900286import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900287import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500288import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700289import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900290import com.android.server.connectivity.FullScore;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900291import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VAN6ca02962023-02-20 20:10:09 +0900292import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000293import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100294import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700295import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900296import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700297import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600298import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900299import com.android.server.connectivity.NetworkNotificationManager;
300import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900301import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900302import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900303import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700304import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900305import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900306import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700307import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800308import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000309import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800310import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600311
Josh Gao461a1222020-06-16 15:58:11 -0700312import libcore.io.IoUtils;
313
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900314import org.xmlpull.v1.XmlPullParserException;
315
The Android Open Source Project28527d22009-03-03 19:31:44 -0800316import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100317import java.io.IOException;
Motomu Utsumia20f7602023-03-16 17:04:21 +0900318import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800319import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900320import java.io.Writer;
Maciej Żenczykowskif310a142023-06-05 07:29:28 +0000321import java.lang.IllegalArgumentException;
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 Utsumia20f7602023-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
393 private static final int DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_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 Żenczykowskif310a142023-06-05 07:29:28 +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 */
555 private static final int EVENT_PROXY_HAS_CHANGED = 16;
556
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 Fasheh7501e762023-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.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000868 @VisibleForTesting
869 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400870
Erik Kline05f2b402015-04-30 12:58:40 +0900871 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700872
Chalard Jean46bfbf02022-02-02 00:56:25 +0900873 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400874
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700875 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900876 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700877
Valentin Iftime9fa35092019-09-24 13:32:13 +0200878 private Set<String> mWolSupportedInterfaces;
879
Roshan Pius08c94fb2020-01-16 12:17:17 -0800880 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800881 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800882 private final AppOpsManager mAppOpsManager;
883
884 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400885
chiachangwang3d60bac2023-01-17 14:38:08 +0000886 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900887 private final QosCallbackTracker mQosCallbackTracker;
888 private final NetworkNotificationManager mNotifier;
889 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900890
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700891 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800892 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700893
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900894 // Sequence number for NetworkProvider IDs.
895 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
896 NetworkProvider.FIRST_PROVIDER_ID);
897
Erik Klineedf878b2015-07-09 18:24:03 +0900898 // NetworkRequest activity String log entries.
899 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
900 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
901
Hugo Benichid159fdd2016-07-11 11:05:12 +0900902 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900903 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900904 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
905
Hugo Benichi47011212017-03-30 10:46:05 +0900906 private static final int MAX_WAKELOCK_LOGS = 20;
907 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900908 private int mTotalWakelockAcquisitions = 0;
909 private int mTotalWakelockReleases = 0;
910 private long mTotalWakelockDurationMs = 0;
911 private long mMaxWakelockDurationMs = 0;
912 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900913
Hugo Benichi208c0102016-07-28 17:53:06 +0900914 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900915
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700916 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900917 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700918
Erik Kline95ecfee2016-10-02 18:02:14 +0900919 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900920 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900921
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900922 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800923 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
924 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800925
Patrick Rohr2857ac42022-01-21 14:58:16 +0100926 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
927 // configured via {@link
928 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
929 // Only the handler thread is allowed to access this field.
930 private long mIngressRateLimit = -1;
931
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900932 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
933 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900934 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900935 @GuardedBy("mSelfCertifiedCapabilityCache")
936 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
937 mSelfCertifiedCapabilityCache = new HashMap<>();
938
Robert Greenwalt802c1102014-06-02 15:32:02 -0700939 /**
940 * Implements support for the legacy "one network per network type" model.
941 *
942 * We used to have a static array of NetworkStateTrackers, one for each
943 * network type, but that doesn't work any more now that we can have,
944 * for example, more that one wifi network. This class stores all the
945 * NetworkAgentInfo objects that support a given type, but the legacy
946 * API will only see the first one.
947 *
948 * It serves two main purposes:
949 *
950 * 1. Provide information about "the network for a given type" (since this
951 * API only supports one).
952 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
953 * the first network for a given type changes, or if the default network
954 * changes.
955 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900956 @VisibleForTesting
957 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900958
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900959 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900960 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900961
Robert Greenwalt802c1102014-06-02 15:32:02 -0700962 /**
963 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
964 * Each list holds references to all NetworkAgentInfos that are used to
965 * satisfy requests for that network type.
966 *
967 * This array is built out at startup such that an unsupported network
968 * doesn't get an ArrayList instance, making this a tristate:
969 * unsupported, supported but not active and active.
970 *
971 * The actual lists are populated when we scan the network types that
972 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900973 *
974 * Threading model:
975 * - addSupportedType() is only called in the constructor
976 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
977 * They are therefore not thread-safe with respect to each other.
978 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
979 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900980 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900981 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700982 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900983 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900984 @NonNull
985 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700986
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900987 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
988 // an entry have no timer (equivalent to -1). Lazily loaded.
989 @NonNull
990 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
991
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900992 LegacyTypeTracker(@NonNull ConnectivityService service) {
993 mService = service;
994 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700995 }
996
Chiachang Wang3bc52762021-11-25 14:17:57 +0800997 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
998 // addressed.
999 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001000 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1001 final PackageManager pm = ctx.getPackageManager();
1002 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1003 addSupportedType(TYPE_WIFI);
1004 }
1005 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1006 addSupportedType(TYPE_WIFI_P2P);
1007 }
1008 if (tm.isDataCapable()) {
1009 // Telephony does not have granular support for these types: they are either all
1010 // supported, or none is supported
1011 addSupportedType(TYPE_MOBILE);
1012 addSupportedType(TYPE_MOBILE_MMS);
1013 addSupportedType(TYPE_MOBILE_SUPL);
1014 addSupportedType(TYPE_MOBILE_DUN);
1015 addSupportedType(TYPE_MOBILE_HIPRI);
1016 addSupportedType(TYPE_MOBILE_FOTA);
1017 addSupportedType(TYPE_MOBILE_IMS);
1018 addSupportedType(TYPE_MOBILE_CBS);
1019 addSupportedType(TYPE_MOBILE_IA);
1020 addSupportedType(TYPE_MOBILE_EMERGENCY);
1021 }
1022 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1023 addSupportedType(TYPE_BLUETOOTH);
1024 }
1025 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1026 // TYPE_PROXY is only used on Wear
1027 addSupportedType(TYPE_PROXY);
1028 }
1029 // Ethernet is often not specified in the configs, although many devices can use it via
1030 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001031 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001032 addSupportedType(TYPE_ETHERNET);
1033 }
1034
1035 // Always add TYPE_VPN as a supported type
1036 addSupportedType(TYPE_VPN);
1037 }
1038
1039 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001040 if (mTypeLists[type] != null) {
1041 throw new IllegalStateException(
1042 "legacy list for type " + type + "already initialized");
1043 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001044 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001045 }
1046
Robert Greenwalt802c1102014-06-02 15:32:02 -07001047 public boolean isTypeSupported(int type) {
1048 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1049 }
1050
1051 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001052 synchronized (mTypeLists) {
1053 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1054 return mTypeLists[type].get(0);
1055 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001056 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001057 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001058 }
1059
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001060 public int getRestoreTimerForType(int type) {
1061 synchronized (mTypeLists) {
1062 if (mRestoreTimers == null) {
1063 mRestoreTimers = loadRestoreTimers();
1064 }
1065 return mRestoreTimers.getOrDefault(type, -1);
1066 }
1067 }
1068
1069 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1070 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001071 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001072 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1073 for (final String config : configs) {
1074 final String[] splits = TextUtils.split(config, ",");
1075 if (splits.length != 2) {
1076 logwtf("Invalid restore timer token count: " + config);
1077 continue;
1078 }
1079 try {
1080 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1081 } catch (NumberFormatException e) {
1082 logwtf("Invalid restore timer number format: " + config, e);
1083 }
1084 }
1085 return ret;
1086 }
1087
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001088 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001089 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001090 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001091 log("Sending " + state
1092 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001093 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001094 }
1095 }
1096
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001097 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1098 // network type, to preserve previous behaviour.
1099 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1100 if (vpnNai != mService.getLegacyLockdownNai()) return;
1101
1102 if (vpnNai.declaredUnderlyingNetworks == null
1103 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1104 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1105 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1106 return;
1107 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001108 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001109 vpnNai.declaredUnderlyingNetworks[0]);
1110 if (underlyingNai == null) return;
1111
1112 final int type = underlyingNai.networkInfo.getType();
1113 final DetailedState state = DetailedState.CONNECTED;
1114 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1115 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1116 }
1117
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001118 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001119 public void add(int type, NetworkAgentInfo nai) {
1120 if (!isTypeSupported(type)) {
1121 return; // Invalid network type.
1122 }
1123 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1124
1125 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1126 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001127 return;
1128 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001129 synchronized (mTypeLists) {
1130 list.add(nai);
1131 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001132
Chalard Jean5b409c72021-02-04 13:12:59 +09001133 // Send a broadcast if this is the first network of its type or if it's the default.
1134 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001135
1136 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1137 // to preserve previous behaviour.
1138 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001139 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001140 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1141 mService.sendLegacyNetworkBroadcast(nai, state, type);
1142 }
1143
1144 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1145 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001146 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001147 }
1148
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001149 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001150 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001151 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1152 if (list == null || list.isEmpty()) {
1153 return;
1154 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001155 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001156
Hugo Benichi389633f2016-06-21 09:48:07 +09001157 synchronized (mTypeLists) {
1158 if (!list.remove(nai)) {
1159 return;
1160 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001161 }
1162
Lorenzo Colitti49767722015-05-01 00:30:10 +09001163 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001164 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1165 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001166 }
1167
1168 if (!list.isEmpty() && wasFirstNetwork) {
1169 if (DBG) log("Other network available for type " + type +
1170 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001171 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001172 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001173 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001174 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001175 }
1176 }
1177
1178 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001179 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1180 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001181 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001182 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001183 }
1184 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001185
Chalard Jean46bfbf02022-02-02 00:56:25 +09001186 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001187 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001188 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001189 final DetailedState state = nai.networkInfo.getDetailedState();
1190 for (int type = 0; type < mTypeLists.length; type++) {
1191 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001192 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001193 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001194 if (isFirst || contains && isDefault) {
1195 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001196 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001197 }
1198 }
1199 }
1200
Robert Greenwalt94e22142014-07-30 16:31:24 -07001201 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001202 pw.println("mLegacyTypeTracker:");
1203 pw.increaseIndent();
1204 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001205 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001206 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001207 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001208 pw.println();
1209 pw.println("Current state:");
1210 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001211 synchronized (mTypeLists) {
1212 for (int type = 0; type < mTypeLists.length; type++) {
1213 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1214 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001215 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001216 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001217 }
1218 }
1219 pw.decreaseIndent();
1220 pw.decreaseIndent();
1221 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001222 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001223 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001224 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001225
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001226 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001227 /**
1228 * Helper class which parses out priority arguments and dumps sections according to their
1229 * priority. If priority arguments are omitted, function calls the legacy dump command.
1230 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001231 private class LocalPriorityDump {
1232 private static final String PRIORITY_ARG = "--dump-priority";
1233 private static final String PRIORITY_ARG_HIGH = "HIGH";
1234 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1235
1236 LocalPriorityDump() {}
1237
1238 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1239 doDump(fd, pw, new String[] {DIAG_ARG});
1240 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001241 }
1242
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001243 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1244 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001245 }
1246
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001247 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1248 if (args == null) {
1249 dumpNormal(fd, pw, args);
1250 return;
1251 }
1252
1253 String priority = null;
1254 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1255 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1256 argIndex++;
1257 priority = args[argIndex];
1258 }
1259 }
1260
1261 if (PRIORITY_ARG_HIGH.equals(priority)) {
1262 dumpHigh(fd, pw);
1263 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1264 dumpNormal(fd, pw, args);
1265 } else {
1266 // ConnectivityService publishes binder service using publishBinderService() with
1267 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001268 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1269 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001270 // TODO: Integrate into signal dump.
1271 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001272 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001273 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001274 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001275
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001276 /**
1277 * Dependencies of ConnectivityService, for injection in tests.
1278 */
1279 @VisibleForTesting
1280 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001281 public int getCallingUid() {
1282 return Binder.getCallingUid();
1283 }
1284
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001285 /**
1286 * Get system properties to use in ConnectivityService.
1287 */
1288 public MockableSystemProperties getSystemProperties() {
1289 return new MockableSystemProperties();
1290 }
1291
1292 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001293 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1294 */
1295 public ConnectivityResources getResources(@NonNull Context ctx) {
1296 return new ConnectivityResources(ctx);
1297 }
1298
1299 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001300 * Create a HandlerThread to use in ConnectivityService.
1301 */
1302 public HandlerThread makeHandlerThread() {
1303 return new HandlerThread("ConnectivityServiceThread");
1304 }
1305
1306 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001307 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001308 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001309 public NetworkStackClientBase getNetworkStack() {
1310 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001311 }
1312
1313 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001314 * @see ProxyTracker
1315 */
1316 public ProxyTracker makeProxyTracker(@NonNull Context context,
1317 @NonNull Handler connServiceHandler) {
1318 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1319 }
1320
1321 /**
1322 * @see NetIdManager
1323 */
1324 public NetIdManager makeNetIdManager() {
1325 return new NetIdManager();
1326 }
1327
1328 /**
1329 * @see NetworkUtils#queryUserAccess(int, int)
1330 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001331 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1332 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001333 }
1334
1335 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001336 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1337 * requires CAP_NET_ADMIN, which the unit tests do not have.
1338 */
1339 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1340 InetSocketAddress remote) {
1341 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1342 }
1343
1344 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001345 * @see MultinetworkPolicyTracker
1346 */
1347 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1348 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1349 return new MultinetworkPolicyTracker(c, h, r);
1350 }
1351
Aaron Huang330a4c02020-10-27 03:36:19 +08001352 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001353 * @see AutomaticOnOffKeepaliveTracker
1354 */
1355 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1356 @NonNull Context c, @NonNull Handler h) {
1357 return new AutomaticOnOffKeepaliveTracker(c, h);
1358 }
1359
1360 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001361 * @see BatteryStatsManager
1362 */
1363 public void reportNetworkInterfaceForTransports(Context context, String iface,
1364 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001365 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001366 context.getSystemService(BatteryStatsManager.class);
1367 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1368 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001369
1370 public boolean getCellular464XlatEnabled() {
1371 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1372 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001373
1374 /**
1375 * @see PendingIntent#intentFilterEquals
1376 */
1377 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1378 return a.intentFilterEquals(b);
1379 }
1380
1381 /**
1382 * @see LocationPermissionChecker
1383 */
1384 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1385 return new LocationPermissionChecker(context);
1386 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001387
1388 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001389 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001390 *
1391 * This method returns null in versions before T, where carrier privilege
1392 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001393 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001394 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001395 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1396 @NonNull final Context context, @NonNull final TelephonyManager tm) {
1397 if (SdkLevel.isAtLeastT()) {
1398 return new CarrierPrivilegeAuthenticator(context, tm);
1399 } else {
1400 return null;
1401 }
1402 }
1403
1404 /**
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001405 * @see DeviceConfigUtils#isFeatureEnabled
1406 */
Motomu Utsumi6f4d8062023-04-21 12:35:22 +09001407 public boolean isFeatureEnabled(Context context, String name) {
1408 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING, name,
1409 TETHERING_MODULE_NAME, false /* defaultValue */);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001410 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001411
1412 /**
1413 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001414 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001415 * @return BpfNetMaps implementation.
1416 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001417 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1418 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001419 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001420
1421 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001422 * @see ClatCoordinator
1423 */
1424 public ClatCoordinator getClatCoordinator(INetd netd) {
1425 return new ClatCoordinator(
1426 new ClatCoordinator.Dependencies() {
1427 @NonNull
1428 public INetd getNetd() {
1429 return netd;
1430 }
1431 });
1432 }
1433
1434 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001435 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1436 */
1437 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1438 final InterfaceParams params = InterfaceParams.getByName(iface);
1439 if (params == null) {
1440 // the interface might have disappeared.
1441 logw("Failed to get interface params for interface " + iface);
1442 return;
1443 }
1444 try {
1445 // converting rateInBytesPerSecond from long to int is safe here because the
1446 // setting's range is limited to INT_MAX.
1447 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001448 Log.i(TAG,
1449 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001450 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1451 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1452 } catch (IOException e) {
1453 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1454 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1455 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1456 + ") failure: ", e);
1457 }
1458 }
1459
1460 /**
1461 * Wraps {@link TcUtils#tcFilterDelDev}
1462 */
1463 public void disableIngressRateLimit(String iface) {
1464 final InterfaceParams params = InterfaceParams.getByName(iface);
1465 if (params == null) {
1466 // the interface might have disappeared.
1467 logw("Failed to get interface params for interface " + iface);
1468 return;
1469 }
1470 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001471 Log.i(TAG,
1472 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001473 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1474 } catch (IOException e) {
1475 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1476 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1477 }
1478 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001479
1480 /**
1481 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1482 */
1483 // TODO: when available in all active branches:
1484 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1485 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1486 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1487 return BroadcastOptionsShimImpl.newInstance(options);
1488 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001489
1490 /**
1491 * Wrapper method for
1492 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1493 *
1494 * @param changeId The ID of the compatibility change in question.
1495 * @param packageName The package name of the app in question.
1496 * @param user The user that the operation is done for.
1497 * @return {@code true} if the change is enabled for the specified package.
1498 */
1499 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1500 @NonNull final UserHandle user) {
1501 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1502 }
Motomu Utsumia20f7602023-03-16 17:04:21 +09001503
1504 /**
1505 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1506 *
1507 * @param ranges target uid ranges
1508 * @param exemptUids uids to skip close socket
1509 */
1510 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1511 @NonNull final Set<Integer> exemptUids)
1512 throws SocketException, InterruptedIOException, ErrnoException {
1513 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1514 }
Motomu Utsumied1848c2023-03-28 18:08:12 +09001515
1516 /**
1517 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1518 *
1519 * @param ownerUids target uids to close sockets
1520 */
1521 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1522 throws SocketException, InterruptedIOException, ErrnoException {
1523 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1524 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001525 }
1526
junyulaie7c7d2a2021-01-26 15:29:15 +08001527 public ConnectivityService(Context context) {
1528 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001529 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1530 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001531 }
1532
1533 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001534 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1535 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001536 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001537
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001538 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001539 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001540 mSystemProperties = mDeps.getSystemProperties();
1541 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001542 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001543 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001544 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1545 // Pass limit - 1 to maintain backward compatibility.
1546 // TODO: Remove the workaround.
1547 mNetworkRequestCounter =
1548 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1549 mSystemNetworkRequestCounter =
1550 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001551
Hugo Benichi208c0102016-07-28 17:53:06 +09001552 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001553 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1554 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001555 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001556 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001557 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001558 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1559 mDefaultNetworkRequests.add(mDefaultRequest);
1560 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001561
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001562 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001563 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001564
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001565 // The default WiFi request is a background request so that apps using WiFi are
1566 // migrated to a better network (typically ethernet) when one comes up, instead
1567 // of staying on WiFi forever.
1568 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1569 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1570
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001571 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1572 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1573 NetworkRequest.Type.BACKGROUND_REQUEST);
1574
Chalard Jean0702f982021-09-16 21:50:07 +09001575 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1576 // TODO: Consider making the timer customizable.
1577 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1578 mCellularRadioTimesharingCapable =
1579 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1580
Maciej Żenczykowskif310a142023-06-05 07:29:28 +00001581 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1582 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1583
1584 if (SdkLevel.isAtLeastU()) {
1585 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1586 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1587 final int defaultUMarkMask = 0x80000000; // u32
1588
1589 if ((mark == 0) || (mask == 0)) {
1590 // simply treat unset/disabled as the default U value
1591 mark = defaultUMarkMask;
1592 mask = defaultUMarkMask;
1593 }
1594 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1595 // invalid device overlay settings
1596 throw new IllegalArgumentException(
1597 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1598 }
1599 }
1600
1601 mWakeUpMark = mark;
1602 mWakeUpMask = mask;
1603
Paul Hu51f816b2022-08-11 14:43:47 +00001604 mNetd = netd;
1605 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001606 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001607 mPermissionMonitor =
1608 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001609 mHandlerThread.start();
1610 mHandler = new InternalHandler(mHandlerThread.getLooper());
1611 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001612 mConnectivityDiagnosticsHandler =
1613 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001614
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001615 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001616 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001617
junyulaie7c7d2a2021-01-26 15:29:15 +08001618 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001619 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001620 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001621 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001622
Wink Saville32506bc2013-06-29 21:10:57 -07001623 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001624 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001625 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001626 mCarrierPrivilegeAuthenticator =
1627 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001628
Sudheer Shanka9967d462021-03-18 19:09:25 +00001629 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001630 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1631 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001632 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001633
1634 final PowerManager powerManager = (PowerManager) context.getSystemService(
1635 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001636 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001637 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001638
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001639 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1640 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001641 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001642 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001643 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001644 mProtectedNetworks.add(p);
1645 } else {
1646 if (DBG) loge("Ignoring protectedNetwork " + p);
1647 }
1648 }
1649
soma, kawata29444ae2019-05-23 09:30:40 +09001650 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1651
James Mattis02220e22021-03-13 19:27:21 -08001652 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001653 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001654 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001655 final IntentFilter userIntentFilter = new IntentFilter();
1656 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1657 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1658 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1659 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001660
James Mattis02220e22021-03-13 19:27:21 -08001661 // Listen to package add/removes for netd
1662 final IntentFilter packageIntentFilter = new IntentFilter();
1663 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1664 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1665 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1666 packageIntentFilter.addDataScheme("package");
1667 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001668 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001669
lucaslind5c2d072021-02-20 18:59:47 +08001670 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001671
Chalard Jean46bfbf02022-02-02 00:56:25 +09001672 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001673 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001674 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001675 } catch (RemoteException | ServiceSpecificException e) {
1676 loge("Error registering event listener :" + e);
1677 }
1678
Erik Kline05f2b402015-04-30 12:58:40 +09001679 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1680 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001681
chiachangwang7c17c282023-02-02 05:58:59 +00001682 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001683 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001684 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001685
1686 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001687 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001688 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1689 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001690 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001691 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1692 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001693
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001694 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001695 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001696 mNetworkRanker =
1697 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1698
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001699 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001700
Chiachang Wangc1215d32020-10-20 15:38:58 +08001701 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001702 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001703
Chalard Jean28018572020-12-21 18:36:52 +09001704 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1705 // request that doesn't allow fallback to the default network. It should never be visible
1706 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1707 // arguments like the handler or the DnsResolver.
1708 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001709 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001710 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001711 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001712 new LinkProperties(), new NetworkCapabilities(),
1713 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001714 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1715 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001716
1717 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001718 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1719 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1720 // Even if it could, running on S would at least require mocking out the BPF map,
1721 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1722 // the bpf syscall. http://aosp/1907693
1723 if (SdkLevel.isAtLeastT()) {
1724 mDscpPolicyTracker = new DscpPolicyTracker();
1725 }
Tyler Wear72388212021-09-09 14:49:02 -07001726 } catch (ErrnoException e) {
1727 loge("Unable to create DscpPolicyTracker");
1728 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001729
1730 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1731 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001732
1733 if (SdkLevel.isAtLeastT()) {
1734 mCdmps = new CompanionDeviceManagerProxyService(context);
1735 } else {
1736 mCdmps = null;
1737 }
Mark Fasheh7501e762023-05-04 20:23:11 +00001738
1739 if (SdkLevel.isAtLeastU()
1740 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION)) {
1741 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1742 new UidFrozenStateChangedCallback() {
1743 @Override
1744 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1745 if (uids.length != frozenStates.length) {
1746 Log.wtf(TAG, "uids has length " + uids.length
1747 + " but frozenStates has length " + frozenStates.length);
1748 return;
1749 }
1750
1751 final UidFrozenStateChangedArgs args =
1752 new UidFrozenStateChangedArgs(uids, frozenStates);
1753
1754 mHandler.sendMessage(
1755 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1756 }
1757 };
1758
1759 final ActivityManager activityManager =
1760 mContext.getSystemService(ActivityManager.class);
1761 activityManager.registerUidFrozenStateChangedCallback(
1762 (Runnable r) -> r.run(), frozenStateChangedCallback);
1763 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001764 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001765
Xiao Ma0a171c02022-01-23 16:14:51 +00001766 /**
1767 * Check whether or not the device supports Ethernet transport.
1768 */
1769 public static boolean deviceSupportsEthernet(final Context context) {
1770 final PackageManager pm = context.getPackageManager();
1771 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1772 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1773 }
1774
Chalard Jean46adcf32018-04-18 20:18:38 +09001775 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001776 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1777 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001778 }
1779
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001780 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1781 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001782 final NetworkCapabilities netCap = new NetworkCapabilities();
1783 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001784 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001785 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001786 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001787 return netCap;
1788 }
1789
James Mattis45d81842021-01-10 14:24:24 -08001790 private NetworkRequest createDefaultRequest() {
1791 return createDefaultInternetRequestForTransport(
1792 TYPE_NONE, NetworkRequest.Type.REQUEST);
1793 }
1794
lucaslin3ba7cc22022-12-19 02:35:33 +00001795 private NetworkRequest createVpnRequest() {
1796 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1797 .withoutDefaultCapabilities()
1798 .addTransportType(TRANSPORT_VPN)
1799 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1800 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1801 .build();
1802 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1803 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1804 }
1805
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001806 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001807 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001808 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001809 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001810 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001811 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001812 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001813 netCap.addTransportType(transportType);
1814 }
James Mattis45d81842021-01-10 14:24:24 -08001815 return createNetworkRequest(type, netCap);
1816 }
1817
1818 private NetworkRequest createNetworkRequest(
1819 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001820 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001821 }
1822
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001823 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1824 NetworkRequest.Type type) {
1825 final NetworkCapabilities netCap = new NetworkCapabilities();
1826 netCap.clearAll();
1827 netCap.addCapability(capability);
1828 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1829 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1830 }
1831
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001832 // Used only for testing.
1833 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001834 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001835 // changing ContentResolver to make registerContentObserver non-final).
1836 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1837 // by subclassing SettingsObserver.
1838 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001839 void updateAlwaysOnNetworks() {
1840 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001841 }
1842
Erik Kline9a62f012018-03-21 07:18:33 -07001843 // See FakeSettingsProvider comment above.
1844 @VisibleForTesting
1845 void updatePrivateDnsSettings() {
1846 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1847 }
1848
paulhu51f77dc2021-06-07 02:34:20 +00001849 @VisibleForTesting
1850 void updateMobileDataPreferredUids() {
1851 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1852 }
1853
Patrick Rohr2857ac42022-01-21 14:58:16 +01001854 @VisibleForTesting
1855 void updateIngressRateLimit() {
1856 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1857 }
1858
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001859 private void handleAlwaysOnNetworkRequest(
1860 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001861 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001862 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001863 handleAlwaysOnNetworkRequest(networkRequest, enable);
1864 }
1865
1866 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001867 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001868 if (enable == isEnabled) {
1869 return; // Nothing to do.
1870 }
1871
1872 if (enable) {
1873 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001874 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001875 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001876 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001877 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001878 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1879 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001880 }
1881 }
1882
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001883 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001884 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1885 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1886 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1887 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001888 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1889 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001890 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001891 }
1892
paulhu51f77dc2021-06-07 02:34:20 +00001893 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001894 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001895 private void registerSettingsCallbacks() {
1896 // Watch for global HTTP proxy changes.
1897 mSettingsObserver.observe(
1898 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1899 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1900
Chalard Jean46bfbf02022-02-02 00:56:25 +09001901 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001902 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001903 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001904 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1905
Chalard Jean46bfbf02022-02-02 00:56:25 +09001906 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001907 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001908 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001909 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001910
1911 // Watch for mobile data preferred uids changes.
1912 mSettingsObserver.observe(
1913 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1914 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001915
1916 // Watch for ingress rate limit changes.
1917 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01001918 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01001919 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1920 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001921 }
1922
Erik Kline31b4a9e2018-01-11 21:07:29 +09001923 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001924 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1925 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001926 }
1927 }
1928
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001929 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001930 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1931 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001932 return mNextNetworkRequestId++;
1933 }
1934
junyulai74f9a8b2018-06-13 15:00:37 +08001935 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09001936 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08001937 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001938 if (network == null) {
1939 return null;
1940 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001941 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001942 }
1943
1944 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001945 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001946 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001947 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001948 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001949
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001950 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001951 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001952 private NetworkAgentInfo getVpnForUid(int uid) {
1953 synchronized (mNetworkForNetId) {
1954 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1955 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09001956 if (nai.isVPN() && nai.everConnected()
1957 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001958 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001959 }
1960 }
1961 }
1962 return null;
1963 }
1964
Chalard Jean46bfbf02022-02-02 00:56:25 +09001965 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001966 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001967 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001968 final NetworkAgentInfo nai = getVpnForUid(uid);
1969 if (nai != null) return nai.declaredUnderlyingNetworks;
1970 return null;
1971 }
1972
Lorenzo Colittia7574052021-01-19 01:33:05 +09001973 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001974 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001975
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001976 final Network[] networks = getVpnUnderlyingNetworks(uid);
1977 if (networks != null) {
1978 // getUnderlyingNetworks() returns:
1979 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1980 // empty array => the VPN explicitly said "no default network".
1981 // non-empty array => the VPN specified one or more default networks; we use the
1982 // first one.
1983 if (networks.length > 0) {
1984 nai = getNetworkAgentInfoForNetwork(networks[0]);
1985 } else {
1986 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001987 }
1988 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001989 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001990 }
1991
1992 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001993 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001994 */
paulhu7aeba372020-12-30 00:42:19 +08001995 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1996 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001997 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001998 if (ignoreBlocked) {
1999 return false;
2000 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002001 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002002 final long ident = Binder.clearCallingIdentity();
2003 try {
2004 final boolean metered = nc == null ? true : nc.isMetered();
2005 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2006 } finally {
2007 Binder.restoreCallingIdentity(ident);
2008 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002009 }
2010
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002011 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002012 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2013 return;
2014 }
Hugo Benichi47011212017-03-30 10:46:05 +09002015 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002016 synchronized (mBlockedAppUids) {
2017 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002018 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002019 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002020 blocked = false;
2021 } else {
2022 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002023 }
2024 }
Hugo Benichi47011212017-03-30 10:46:05 +09002025 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2026 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2027 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002028 }
2029
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002030 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002031 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2032 return;
2033 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002034 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002035 final int requestId = nri.getActiveRequest() != null
2036 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002037 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002038 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002039 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002040 }
2041
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002042 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002043 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002044 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002045 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002046 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002047 @NonNull
2048 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2049 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002050 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2051 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2052 // but only exists if an app asks about them or requests them. Ensure the requesting app
2053 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002054 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002055 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2056 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2057 null /* extraInfo */);
2058 }
2059 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002060 return filtered;
2061 }
2062
2063 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2064 boolean ignoreBlocked) {
2065 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2066 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002067 }
2068
2069 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002070 * Return NetworkInfo for the active (i.e., connected) network interface.
2071 * It is assumed that at most one network is active at a time. If more
2072 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002073 * @return the info for the active network, or {@code null} if none is
2074 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002075 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002076 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002077 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002078 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002079 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002080 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002081 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2082 if (nai == null) return null;
2083 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2084 maybeLogBlockedNetworkInfo(networkInfo, uid);
2085 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002086 }
2087
Paul Jensen1f567382015-02-13 14:18:39 -05002088 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002089 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002090 public Network getActiveNetwork() {
2091 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002092 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002093 }
2094
2095 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002096 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002097 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002098 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002099 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002100 }
2101
Chalard Jean46bfbf02022-02-02 00:56:25 +09002102 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002103 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002104 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2105 if (vpnNai != null) {
2106 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2107 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2108 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002109 }
Paul Jensen1f567382015-02-13 14:18:39 -05002110 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002111
James Mattis2516da32021-01-31 17:06:19 -08002112 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002113 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2114 ignoreBlocked)) {
2115 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002116 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002117 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002118 }
2119
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002120 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002121 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002122 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002123 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002124 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2125 if (nai == null) return null;
2126 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002127 }
2128
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002129 /** Returns a NetworkInfo object for a network that doesn't exist. */
2130 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2131 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2132 getNetworkTypeName(networkType), "" /* subtypeName */);
2133 info.setIsAvailable(true);
2134 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2135 // background data is restricted.
2136 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2137 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2138 ? DetailedState.BLOCKED
2139 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002140 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2141 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002142 return info;
2143 }
2144
Lorenzo Colittia7574052021-01-19 01:33:05 +09002145 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002146 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2147 return null;
2148 }
2149 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002150 if (nai == null) {
2151 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002152 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002153 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2154 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002155 }
2156
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002157 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002158 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002159 public NetworkInfo getNetworkInfo(int networkType) {
2160 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002161 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002162 if (getVpnUnderlyingNetworks(uid) != null) {
2163 // A VPN is active, so we may need to return one of its underlying networks. This
2164 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002165 // getNetworkAgentInfoForUid.
2166 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2167 if (nai == null) return null;
2168 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2169 if (networkInfo.getType() == networkType) {
2170 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002171 }
2172 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002173 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002174 }
2175
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002176 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002177 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002178 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002179 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002180 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002181 if (nai == null) return null;
2182 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002183 }
2184
2185 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002186 public NetworkInfo[] getAllNetworkInfo() {
2187 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002188 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002189 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2190 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002191 NetworkInfo info = getNetworkInfo(networkType);
2192 if (info != null) {
2193 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002194 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002195 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002196 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002197 }
2198
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002199 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002200 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002201 public Network getNetworkForType(int networkType) {
2202 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002203 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2204 return null;
2205 }
2206 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2207 if (nai == null) {
2208 return null;
2209 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002210 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002211 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2212 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002213 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002214 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002215 }
2216
2217 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002218 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002219 public Network[] getAllNetworks() {
2220 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002221 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002222 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002223 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002224 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002225 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002226 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002227 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002228 }
2229
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002230 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002231 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002232 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002233 // The basic principle is: if an app's traffic could possibly go over a
2234 // network, without the app doing anything multinetwork-specific,
2235 // (hence, by "default"), then include that network's capabilities in
2236 // the array.
2237 //
2238 // In the normal case, app traffic only goes over the system's default
2239 // network connection, so that's the only network returned.
2240 //
2241 // With a VPN in force, some app traffic may go into the VPN, and thus
2242 // over whatever underlying networks the VPN specifies, while other app
2243 // traffic may go over the system default network (e.g.: a split-tunnel
2244 // VPN, or an app disallowed by the VPN), so the set of networks
2245 // returned includes the VPN's underlying networks and the system
2246 // default.
2247 enforceAccessPermission();
2248
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002249 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002250
James Mattis2516da32021-01-31 17:06:19 -08002251 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2252 if (!nri.isBeingSatisfied()) {
2253 continue;
2254 }
2255 final NetworkAgentInfo nai = nri.getSatisfier();
2256 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2257 if (null != nc
2258 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2259 && !result.containsKey(nai.network)) {
2260 result.put(
2261 nai.network,
2262 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002263 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002264 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2265 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002266 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002267 }
2268
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002269 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002270 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002271 if (null != networks) {
2272 for (final Network network : networks) {
2273 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2274 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002275 result.put(
2276 network,
2277 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002278 nc,
2279 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002280 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002281 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002282 }
2283 }
2284 }
2285
2286 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2287 out = result.values().toArray(out);
2288 return out;
2289 }
2290
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002291 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002292 public boolean isNetworkSupported(int networkType) {
2293 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002294 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002295 }
2296
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002297 /**
2298 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002299 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002300 * @return the ip properties for the active network, or {@code null} if
2301 * none is active
2302 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002303 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002304 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002305 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002306 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002307 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2308 if (nai == null) return null;
2309 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002310 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002311 }
2312
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002313 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002314 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002315 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002316 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002317 final LinkProperties lp = getLinkProperties(nai);
2318 if (lp == null) return null;
2319 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002320 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002321 }
2322
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002323 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002324 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002325 public LinkProperties getLinkProperties(Network network) {
2326 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002327 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2328 if (lp == null) return null;
2329 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002330 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002331 }
2332
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002333 @Nullable
2334 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002335 if (nai == null) {
2336 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002337 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002338 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002339 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002340 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002341 }
2342
lucaslinc582d502022-01-27 09:07:00 +08002343 @Override
2344 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002345 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002346 @NonNull String packageName, @Nullable String callingAttributionTag) {
2347 Objects.requireNonNull(packageName);
2348 Objects.requireNonNull(lp);
2349 enforceNetworkStackOrSettingsPermission();
2350 if (!checkAccessPermission(-1 /* pid */, uid)) {
2351 return null;
2352 }
2353 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2354 }
2355
Qingxi Lib2748102020-01-08 12:51:49 -08002356 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2357 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2358 }
2359
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002360 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002361 if (nai == null) return null;
2362 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002363 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002364 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002365 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002366 }
2367
2368 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002369 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2370 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002371 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002372 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002373 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002374 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002375 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002376 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002377 }
2378
lucaslinc582d502022-01-27 09:07:00 +08002379 @Override
lucaslind2b06132022-03-02 10:56:57 +08002380 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2381 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2382 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002383 Objects.requireNonNull(nc);
2384 Objects.requireNonNull(packageName);
2385 enforceNetworkStackOrSettingsPermission();
2386 if (!checkAccessPermission(-1 /* pid */, uid)) {
2387 return null;
2388 }
2389 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2390 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2391 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2392 callingAttributionTag);
2393 }
2394
lucaslin69e1aa92022-03-22 18:15:09 +08002395 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2396 if (nc.getUnderlyingNetworks() != null
2397 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2398 nc.setUnderlyingNetworks(null);
2399 }
2400 }
2401
Qingxi Libb8da982020-01-17 17:54:27 -08002402 @VisibleForTesting
2403 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002404 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002405 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2406 // this would be expensive (one more permission check every time any NC callback is
2407 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2408 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2409 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002410 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002411 if (!checkSettingsPermission(callerPid, callerUid)) {
2412 newNc.setUids(null);
2413 newNc.setSSID(null);
2414 }
Etan Cohen107ae952018-12-30 17:59:59 -08002415 if (newNc.getNetworkSpecifier() != null) {
2416 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2417 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002418 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2419 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002420 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2421 newNc.setAdministratorUids(new int[0]);
2422 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002423 if (!checkAnyPermissionOf(mContext,
Benedict Wong53de25f2021-03-24 14:01:51 -07002424 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002425 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002426 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002427 }
lucaslin69e1aa92022-03-22 18:15:09 +08002428 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002429
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002430 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002431 }
2432
Roshan Pius98f59ec2021-02-23 08:47:39 -08002433 /**
2434 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002435 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002436 * NetworkCapabilities.
2437 * Note: This wrapper does not support any sort of invalidation and thus must not be
2438 * persistent or long-lived. It may only be used for the time necessary to
2439 * compute the redactions required by one particular NetworkCallback or
2440 * synchronous call.
2441 */
2442 private class RedactionPermissionChecker {
2443 private final int mCallingPid;
2444 private final int mCallingUid;
2445 @NonNull private final String mCallingPackageName;
2446 @Nullable private final String mCallingAttributionTag;
2447
2448 private Boolean mHasLocationPermission = null;
2449 private Boolean mHasLocalMacAddressPermission = null;
2450 private Boolean mHasSettingsPermission = null;
2451
2452 RedactionPermissionChecker(int callingPid, int callingUid,
2453 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2454 mCallingPid = callingPid;
2455 mCallingUid = callingUid;
2456 mCallingPackageName = callingPackageName;
2457 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002458 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002459
2460 private boolean hasLocationPermissionInternal() {
2461 final long token = Binder.clearCallingIdentity();
2462 try {
2463 return mLocationPermissionChecker.checkLocationPermission(
2464 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2465 null /* message */);
2466 } finally {
2467 Binder.restoreCallingIdentity(token);
2468 }
2469 }
2470
2471 /**
2472 * Returns whether the app holds location permission or not (might return cached result
2473 * if the permission was already checked before).
2474 */
2475 public boolean hasLocationPermission() {
2476 if (mHasLocationPermission == null) {
2477 // If there is no cached result, perform the check now.
2478 mHasLocationPermission = hasLocationPermissionInternal();
2479 }
2480 return mHasLocationPermission;
2481 }
2482
2483 /**
2484 * Returns whether the app holds local mac address permission or not (might return cached
2485 * result if the permission was already checked before).
2486 */
2487 public boolean hasLocalMacAddressPermission() {
2488 if (mHasLocalMacAddressPermission == null) {
2489 // If there is no cached result, perform the check now.
2490 mHasLocalMacAddressPermission =
2491 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2492 }
2493 return mHasLocalMacAddressPermission;
2494 }
2495
2496 /**
2497 * Returns whether the app holds settings permission or not (might return cached
2498 * result if the permission was already checked before).
2499 */
2500 public boolean hasSettingsPermission() {
2501 if (mHasSettingsPermission == null) {
2502 // If there is no cached result, perform the check now.
2503 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2504 }
2505 return mHasSettingsPermission;
2506 }
2507 }
2508
2509 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2510 @NetworkCapabilities.NetCapability long redaction) {
2511 return (redactions & redaction) != 0;
2512 }
2513
2514 /**
2515 * Use the provided |applicableRedactions| to check the receiving app's
2516 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2517 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2518 * before being sent to the corresponding app.
2519 */
2520 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2521 @NetworkCapabilities.RedactionType long applicableRedactions,
2522 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2523 boolean includeLocationSensitiveInfo) {
2524 long redactions = applicableRedactions;
2525 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2526 if (includeLocationSensitiveInfo
2527 && redactionPermissionChecker.hasLocationPermission()) {
2528 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2529 }
2530 }
2531 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2532 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2533 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2534 }
2535 }
2536 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2537 if (redactionPermissionChecker.hasSettingsPermission()) {
2538 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2539 }
2540 }
2541 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002542 }
2543
Qingxi Lib2748102020-01-08 12:51:49 -08002544 @VisibleForTesting
2545 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002546 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002547 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002548 int callingPid, int callingUid, @NonNull String callingPkgName,
2549 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002550 if (nc == null) {
2551 return null;
2552 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002553 // Avoid doing location permission check if the transport info has no location sensitive
2554 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002555 final RedactionPermissionChecker redactionPermissionChecker =
2556 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2557 callingAttributionTag);
2558 final long redactions = retrieveRequiredRedactions(
2559 nc.getApplicableRedactions(), redactionPermissionChecker,
2560 includeLocationSensitiveInfo);
2561 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002562 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002563 // TODO : calling UID is redacted because apps should generally not know what UID is
2564 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002565 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002566 newNc.setOwnerUid(INVALID_UID);
2567 return newNc;
2568 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002569 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2570 if (nc.hasTransport(TRANSPORT_VPN)) {
2571 // Owner UIDs already checked above. No need to re-check.
2572 return newNc;
2573 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002574 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2575 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002576 // compatibility for older apps.
2577 if (!includeLocationSensitiveInfo
2578 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002579 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002580 newNc.setOwnerUid(INVALID_UID);
2581 return newNc;
2582 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002583 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002584 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002585 newNc.setOwnerUid(INVALID_UID);
2586 }
Qingxi Lib2748102020-01-08 12:51:49 -08002587 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002588 }
2589
lucaslinc582d502022-01-27 09:07:00 +08002590 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002591 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2592 LinkProperties lp, int callerPid, int callerUid) {
2593 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002594 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2595 // this would be expensive (one more permission check every time any LP callback is
2596 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2597 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2598 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002599
2600 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2601 final boolean needsSanitization =
2602 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2603 if (!needsSanitization) {
2604 return new LinkProperties(lp);
2605 }
2606
2607 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002608 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002609 }
2610
2611 final LinkProperties newLp = new LinkProperties(lp);
2612 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2613 // object gets parceled.
2614 newLp.setCaptivePortalApiUrl(null);
2615 newLp.setCaptivePortalData(null);
2616 return newLp;
2617 }
2618
Roshan Pius08c94fb2020-01-16 12:17:17 -08002619 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2620 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002621 // There is no need to track the effective UID of the request here. If the caller
2622 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002623 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002624 // Unprivileged apps can only pass in null or their own UID.
2625 if (nc.getUids() == null) {
2626 // If the caller passes in null, the callback will also match networks that do not
2627 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2628 // In this case, redact everything in the request immediately. This ensures that the
2629 // app is not able to get any redacted information by filing an unredacted request
2630 // and observing whether the request matches something.
2631 if (nc.getNetworkSpecifier() != null) {
2632 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2633 }
2634 } else {
2635 nc.setSingleUid(callerUid);
2636 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002637 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002638 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002639 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002640
2641 // Clear owner UID; this can never come from an app.
2642 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002643 }
2644
Chalard Jean38354d12018-03-20 19:13:57 +09002645 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002646 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002647 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2648 }
2649 }
2650
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002651 @Override
2652 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2653 enforceAccessPermission();
2654 final int callerUid = Binder.getCallingUid();
2655 final long token = Binder.clearCallingIdentity();
2656 try {
2657 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2658 } finally {
2659 Binder.restoreCallingIdentity(token);
2660 }
2661 }
2662
junyulaiebd15162021-03-03 12:09:05 +08002663 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002664 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002665 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002666 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002667 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002668
Serik Beketayev05130302021-01-15 16:47:25 -08002669 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002670 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002671 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2672 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002673 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002674 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002675 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002676 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2677 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002678 }
2679 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002680 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002681 }
2682
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002683 @Override
junyulaiebd15162021-03-03 12:09:05 +08002684 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002685 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002686 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002687 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002688
2689 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2690 for (Network network : getAllNetworks()) {
2691 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09002692 final boolean includeNetwork = (nai != null) && nai.isCreated();
2693 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002694 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2695 // NetworkCapabilities, which may contain UIDs of apps to which the
2696 // network applies. Should the UIDs be cleared so as not to leak or
2697 // interfere ?
2698 result.add(nai.getNetworkStateSnapshot());
2699 }
2700 }
2701 return result;
2702 }
2703
2704 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002705 public boolean isActiveNetworkMetered() {
2706 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002707
Qingxi Lib2748102020-01-08 12:51:49 -08002708 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002709 if (caps != null) {
2710 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2711 } else {
2712 // Always return the most conservative value
2713 return true;
2714 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002715 }
2716
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002717 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002718 * Ensures that the system cannot call a particular method.
2719 */
2720 private boolean disallowedBecauseSystemCaller() {
2721 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002722 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2723 // for devices launched with Q and above. However, existing devices upgrading to Q and
2724 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002725 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002726 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002727 log("This method exists only for app backwards compatibility"
2728 + " and must not be called by system services.");
2729 return true;
2730 }
2731 return false;
2732 }
2733
paulhub2c28682021-08-18 18:35:54 +08002734 private int getAppUid(final String app, final UserHandle user) {
2735 final PackageManager pm =
2736 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2737 final long token = Binder.clearCallingIdentity();
2738 try {
2739 return pm.getPackageUid(app, 0 /* flags */);
2740 } catch (PackageManager.NameNotFoundException e) {
2741 return -1;
2742 } finally {
2743 Binder.restoreCallingIdentity(token);
2744 }
2745 }
2746
2747 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2748 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2749 if (getAppUid(packageName, user) != callingUid) {
2750 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2751 }
2752 }
2753
Lorenzo Colitti23862912018-09-28 11:31:55 +09002754 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002755 * Ensure that a network route exists to deliver traffic to the specified
2756 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002757 * @param networkType the type of the network over which traffic to the
2758 * specified host is to be routed
2759 * @param hostAddress the IP address of the host to which the route is
2760 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002761 * @return {@code true} on success, {@code false} on failure
2762 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002763 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002764 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2765 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002766 if (disallowedBecauseSystemCaller()) {
2767 return false;
2768 }
paulhub2c28682021-08-18 18:35:54 +08002769 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002770 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002771 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002772 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002773 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002774
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002775 InetAddress addr;
2776 try {
2777 addr = InetAddress.getByAddress(hostAddress);
2778 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002779 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002780 return false;
2781 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002782
The Android Open Source Project28527d22009-03-03 19:31:44 -08002783 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002784 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002785 return false;
2786 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002787
2788 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2789 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002790 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002791 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2792 } else {
2793 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2794 }
2795 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002796 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002797
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002798 DetailedState netState;
2799 synchronized (nai) {
2800 netState = nai.networkInfo.getDetailedState();
2801 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002802
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002803 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002804 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002805 log("requestRouteToHostAddress on down network "
2806 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002807 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002808 }
2809 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002810 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002811
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002812 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002813 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002814 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002815 LinkProperties lp;
2816 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002817 synchronized (nai) {
2818 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002819 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002820 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002821 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002822 if (DBG) {
2823 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2824 }
Wink Saville32506bc2013-06-29 21:10:57 -07002825 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002826 } finally {
2827 Binder.restoreCallingIdentity(token);
2828 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002829 }
2830
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002831 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002832 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002833 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002834 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002835 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002836 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002837 if (bestRoute.getGateway().equals(addr)) {
2838 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002839 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002840 } else {
2841 // if we will connect to this through another route, add a direct route
2842 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002843 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002844 }
2845 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002846 if (DBG) log("Adding legacy route " + bestRoute +
2847 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002848
2849 final String dst = bestRoute.getDestinationLinkAddress().toString();
2850 final String nextHop = bestRoute.hasGateway()
2851 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002852 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002853 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2854 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002855 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002856 return false;
2857 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002858 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002859 }
2860
paulhu7c0a2e62021-01-08 00:51:49 +08002861 class DnsResolverUnsolicitedEventCallback extends
2862 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002863 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002864 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002865 try {
2866 mHandler.sendMessage(mHandler.obtainMessage(
2867 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002868 new PrivateDnsValidationUpdate(event.netId,
2869 InetAddresses.parseNumericAddress(event.ipAddress),
2870 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002871 } catch (IllegalArgumentException e) {
2872 loge("Error parsing ip address in validation event");
2873 }
2874 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002875
2876 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002877 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2878 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002879 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2880 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2881 // event callback for certain nai. e.g. cellular. Register here to pass to
2882 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002883 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002884 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2885 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002886 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002887 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002888 }
2889 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002890
2891 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002892 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2893 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2894 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002895 }
dalyk1720e542018-03-05 12:42:22 -05002896
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002897 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002898 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002899 return this.VERSION;
2900 }
2901
2902 @Override
2903 public String getInterfaceHash() {
2904 return this.HASH;
2905 }
paulhu7c0a2e62021-01-08 00:51:49 +08002906 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002907
2908 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002909 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2910 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002911
paulhu7c0a2e62021-01-08 00:51:49 +08002912 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002913 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002914 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002915 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002916 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002917 }
2918 }
2919
Sudheer Shanka9967d462021-03-18 19:09:25 +00002920 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002921 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002922 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002923 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2924 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002925 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002926 };
2927
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002928 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002929 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002930 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002931 }
2932
Mark Fasheh7501e762023-05-04 20:23:11 +00002933 static final class UidFrozenStateChangedArgs {
2934 final int[] mUids;
2935 final int[] mFrozenStates;
2936
2937 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
2938 mUids = uids;
2939 mFrozenStates = frozenStates;
2940 }
2941 }
2942
2943 private void handleFrozenUids(int[] uids, int[] frozenStates) {
2944 final ArraySet<Range<Integer>> ranges = new ArraySet<>();
2945
2946 for (int i = 0; i < uids.length; i++) {
2947 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
2948 Integer uidAsInteger = Integer.valueOf(uids[i]);
2949 ranges.add(new Range(uidAsInteger, uidAsInteger));
2950 }
2951 }
2952
2953 if (!ranges.isEmpty()) {
2954 final Set<Integer> exemptUids = new ArraySet<>();
2955 try {
2956 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
2957 } catch (Exception e) {
2958 loge("Exception in socket destroy: " + e);
2959 }
2960 }
2961 }
2962
2963 @VisibleForTesting
2964 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
2965
Paul Jensen83f5d572014-08-29 09:54:01 -04002966 private void enforceInternetPermission() {
2967 mContext.enforceCallingOrSelfPermission(
2968 android.Manifest.permission.INTERNET,
2969 "ConnectivityService");
2970 }
2971
The Android Open Source Project28527d22009-03-03 19:31:44 -08002972 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002973 mContext.enforceCallingOrSelfPermission(
2974 android.Manifest.permission.ACCESS_NETWORK_STATE,
2975 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002976 }
2977
lucaslinc582d502022-01-27 09:07:00 +08002978 private boolean checkAccessPermission(int pid, int uid) {
2979 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
2980 == PERMISSION_GRANTED;
2981 }
2982
paulhua6ee2122021-02-22 15:40:43 +08002983 /**
2984 * Performs a strict and comprehensive check of whether a calling package is allowed to
2985 * change the state of network, as the condition differs for pre-M, M+, and
2986 * privileged/preinstalled apps. The caller is expected to have either the
2987 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2988 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2989 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2990 * permission and cannot be revoked. See http://b/23597341
2991 *
2992 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2993 * of this app will be updated to the current time.
2994 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002995 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002996 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2997 == PackageManager.PERMISSION_GRANTED) {
2998 return;
2999 }
3000
3001 if (callingPkg == null) {
3002 throw new SecurityException("Calling package name is null.");
3003 }
3004
3005 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3006 final int uid = mDeps.getCallingUid();
3007 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3008 callingPkg, callingAttributionTag, null /* message */);
3009
3010 if (mode == AppOpsManager.MODE_ALLOWED) {
3011 return;
3012 }
3013
3014 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3015 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3016 return;
3017 }
3018
3019 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3020 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3021 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003022 }
3023
Charles He9369e612017-05-15 17:07:18 +01003024 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003025 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003026 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003027 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003028 }
3029
Quang Luong98858d62023-02-11 00:25:24 +00003030 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003031 enforceAnyPermissionOf(mContext,
3032 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003033 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003034 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3035 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3036 }
3037
paulhu8e96a752019-08-12 16:25:11 +08003038 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003039 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003040 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003041 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003042 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003043 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003044 }
3045
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003046 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003047 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003048 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003049 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003050 android.Manifest.permission.NETWORK_SETTINGS,
3051 android.Manifest.permission.NETWORK_FACTORY,
3052 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3053 }
3054
3055 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003056 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003057 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003058 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003059 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3060 android.Manifest.permission.NETWORK_FACTORY,
3061 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3062 }
3063
lucaslin69e1aa92022-03-22 18:15:09 +08003064 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3065 return PERMISSION_GRANTED == mContext.checkPermission(
3066 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3067 || PERMISSION_GRANTED == mContext.checkPermission(
3068 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3069 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003070 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003071 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003072 }
3073
Chalard Jean9a396cc2018-02-21 18:43:54 +09003074 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003075 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003076 android.Manifest.permission.NETWORK_SETTINGS,
3077 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003078 }
3079
3080 private boolean checkSettingsPermission(int pid, int uid) {
3081 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003082 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3083 || PERMISSION_GRANTED == mContext.checkPermission(
3084 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003085 }
3086
paulhu8e96a752019-08-12 16:25:11 +08003087 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003088 enforceNetworkStackPermissionOr(mContext,
3089 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003090 }
3091
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003092 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003093 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003094 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003095 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003096 }
3097
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003098 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003099 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003100 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3101 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003102 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003103 }
3104
James Mattis8378aec2021-01-26 14:05:36 -08003105 private void enforceOemNetworkPreferencesPermission() {
3106 mContext.enforceCallingOrSelfPermission(
3107 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3108 "ConnectivityService");
3109 }
3110
James Mattisfa270db2021-05-31 17:11:10 -07003111 private void enforceManageTestNetworksPermission() {
3112 mContext.enforceCallingOrSelfPermission(
3113 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3114 "ConnectivityService");
3115 }
3116
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003117 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003118 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003119 android.Manifest.permission.NETWORK_STACK,
3120 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003121 }
3122
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003123 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003124 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003125 android.Manifest.permission.NETWORK_STACK,
3126 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3127 }
3128
paulhu1a407652019-03-22 16:35:06 +08003129 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003130 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003131 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003132 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3133 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003134 }
3135
Paul Hu8fc2a552022-05-04 18:44:42 +08003136 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3137 boolean checkUidsAllowedList) {
3138 if (PermissionUtils.checkAnyPermissionOf(mContext,
3139 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3140 return true;
3141 }
3142
3143 // fallback to ConnectivityInternalPermission
3144 // TODO: Remove this fallback check after all apps have declared
3145 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3146 if (PermissionUtils.checkAnyPermissionOf(mContext,
3147 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3148 return true;
3149 }
3150
3151 // Check whether uid is in allowed on restricted networks list.
3152 if (checkUidsAllowedList
3153 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3154 return true;
3155 }
3156 return false;
3157 }
3158
3159 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3160 final int callingUid = mDeps.getCallingUid();
3161 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3162 throw new SecurityException("ConnectivityService: user " + callingUid
3163 + " has no permission to access restricted network.");
3164 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003165 }
3166
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003167 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003168 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003169 }
3170
Roshan Pius98f59ec2021-02-23 08:47:39 -08003171 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3172 return PERMISSION_GRANTED == mContext.checkPermission(
3173 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3174 }
3175
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003176 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003177 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003178 }
3179
3180 private void sendInetConditionBroadcast(NetworkInfo info) {
3181 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3182 }
3183
Wink Saville4f0de1e2011-08-04 15:01:58 -07003184 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003185 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003186 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003187 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003188 if (info.isFailover()) {
3189 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3190 info.setFailover(false);
3191 }
3192 if (info.getReason() != null) {
3193 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3194 }
3195 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003196 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3197 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003198 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003199 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003200 return intent;
3201 }
3202
3203 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3204 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3205 }
3206
Michael Groover73f69482023-01-27 11:01:25 -06003207 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3208 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003209 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3210 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003211 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003212 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003213 if (!mSystemReady
3214 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003215 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003216 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003217 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003218 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003219 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003220 }
3221
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003222 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003223 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003224 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003225 final NetworkInfo ni = intent.getParcelableExtra(
3226 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003227 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3228 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003229 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003230 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003231 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003232 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003233 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003234 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003235 } finally {
3236 Binder.restoreCallingIdentity(ident);
3237 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003238 }
3239 }
3240
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003241 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3242 NetworkInfo info) {
3243 // Delivery group policy APIs are only available on U+.
3244 if (!SdkLevel.isAtLeastU()) return;
3245
3246 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3247 try {
3248 // This allows us to discard older broadcasts still waiting to be delivered
3249 // which have the same namespace and key.
3250 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3251 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3252 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003253 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003254 } catch (UnsupportedApiLevelException e) {
3255 Log.wtf(TAG, "Using unsupported API" + e);
3256 }
3257 }
3258
3259 @VisibleForTesting
3260 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3261 final StringBuilder sb = new StringBuilder();
3262 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3263 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3264 sb.append(info.getExtraInfo());
3265 return sb.toString();
3266 }
3267
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003268 /**
Aaron Huang96011892020-06-27 07:18:23 +08003269 * Called by SystemServer through ConnectivityManager when the system is ready.
3270 */
3271 @Override
3272 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003273 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003274 throw new SecurityException("Calling Uid is not system uid.");
3275 }
3276 systemReadyInternal();
3277 }
3278
3279 /**
3280 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003281 */
3282 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003283 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003284 // Load flags after PackageManager is ready to query module version
3285 mFlags.loadFlags(mDeps, mContext);
3286
Aaron Huang9a57acf2020-12-08 10:03:29 +08003287 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3288 // listening network request which is sent by MultipathPolicyTracker won't be added
3289 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3290 // be called after PermissionMonitor#startMonitoring().
3291 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3292 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3293 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003294 final ConditionVariable startMonitoringDone = new ConditionVariable();
3295 mHandler.post(() -> {
3296 mPermissionMonitor.startMonitoring();
3297 startMonitoringDone.open();
3298 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003299 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003300 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003301
Hugo Benichie5220992017-04-26 14:53:28 +09003302 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003303 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003304 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003305 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003306 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003307 }
3308 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003309
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003310 // Create network requests for always-on networks.
3311 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003312
3313 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003314 // Note that updating can be skipped here if the list is empty only because no uid
3315 // rules are applied before system ready. Normally, the empty uid list means to clear
3316 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003317 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3318 updateMobileDataPreferredUids();
3319 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003320
3321 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
3322 if (SdkLevel.isAtLeastT()) {
3323 mBpfNetMaps.setPullAtomCallback(mContext);
3324 }
Paul Hu3c8c8102022-08-25 07:06:16 +00003325 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3326 // have permission problem. While CV#block() is unbounded in time and can in principle block
3327 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3328 // could have blocked forever too.
3329 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003330 }
3331
The Android Open Source Project28527d22009-03-03 19:31:44 -08003332 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003333 * Start listening for default data network activity state changes.
3334 */
3335 @Override
3336 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003337 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003338 }
3339
3340 /**
3341 * Stop listening for default data network activity state changes.
3342 */
3343 @Override
3344 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003345 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003346 }
3347
3348 /**
3349 * Check whether the default network radio is currently active.
3350 */
3351 @Override
3352 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003353 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003354 }
3355
3356 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003357 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003358 * and set it on it's iface.
3359 */
Junyu Lai970963e2022-10-25 15:46:47 +08003360 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003361 final String iface = newLp.getInterfaceName();
3362 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003363 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003364 // Silently ignore unset MTU value.
3365 return;
3366 }
Hansen Kurli04252032022-12-07 11:21:49 +00003367 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3368 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3369 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003370 return;
3371 }
Hansen Kurli04252032022-12-07 11:21:49 +00003372 // Cannot set MTU without interface name
3373 if (TextUtils.isEmpty(iface)) {
3374 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003375 return;
3376 }
sy.yun4aa73922013-09-02 05:24:09 +09003377
Hansen Kurli04252032022-12-07 11:21:49 +00003378 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3379 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003380 return;
3381 }
3382
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003383 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003384 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003385 mNetd.interfaceSetMtu(iface, mtu);
3386 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003387 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003388 }
3389 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003390
Chenbo Feng15416292018-11-08 17:36:21 -08003391 @VisibleForTesting
3392 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003393
Junyu Lai970963e2022-10-25 15:46:47 +08003394 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003395 String[] values = null;
3396 if (tcpBufferSizes != null) {
3397 values = tcpBufferSizes.split(",");
3398 }
3399
3400 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003401 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003402 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3403 values = tcpBufferSizes.split(",");
3404 }
3405
3406 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3407
3408 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003409 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003410
Chenbo Feng15416292018-11-08 17:36:21 -08003411 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3412 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3413 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003414 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003415 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003416 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003417 }
3418 }
3419
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003420 @Override
3421 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003422 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003423 NETWORK_RESTORE_DELAY_PROP_NAME);
3424 if(restoreDefaultNetworkDelayStr != null &&
3425 restoreDefaultNetworkDelayStr.length() != 0) {
3426 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003427 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003428 } catch (NumberFormatException e) {
3429 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003430 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003431 // if the system property isn't set, use the value for the apn type
3432 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3433
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003434 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3435 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003436 }
3437 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003438 }
3439
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003440 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003441 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003442 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003443 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003444 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003445 // Start gathering diagnostic information.
3446 netDiags.add(new NetworkDiagnostics(
3447 nai.network,
3448 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003449 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003450 DIAG_TIME_MS));
3451 }
3452
3453 for (NetworkDiagnostics netDiag : netDiags) {
3454 pw.println();
3455 netDiag.waitForMeasurements();
3456 netDiag.dump(pw);
3457 }
3458 }
3459
The Android Open Source Project28527d22009-03-03 19:31:44 -08003460 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003461 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3462 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003463 if (!checkDumpPermission(mContext, TAG, writer)) return;
3464
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003465 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003466 }
3467
lucaslin99473f62020-12-10 15:10:54 +08003468 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3469 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3470 != PackageManager.PERMISSION_GRANTED) {
3471 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003472 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003473 + " due to missing android.permission.DUMP permission");
3474 return false;
3475 } else {
3476 return true;
3477 }
3478 }
3479
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003480 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003481 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003482
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003483 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003484 dumpNetworkDiagnostics(pw);
3485 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003486 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003487 dumpNetworks(pw);
3488 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003489 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003490 dumpNetworkRequests(pw);
3491 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003492 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3493 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3494 dumpTrafficController(pw, fd, verbose);
3495 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003496 }
Erik Kline9647f382015-06-05 17:47:34 +09003497
Junyu Lai0da479b2022-04-20 15:06:29 +08003498 pw.println("NetworkProviders for:");
3499 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003500 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003501 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003502 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003503 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003504 pw.println();
3505
Chalard Jean5b409c72021-02-04 13:12:59 +09003506 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003507 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003508 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003509 pw.println("none");
3510 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003511 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003512 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003513 pw.println();
3514
James Mattis8b298a02021-06-01 22:34:04 -07003515 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003516 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003517 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003518 pw.decreaseIndent();
3519 pw.println();
3520
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003521 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003522 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003523 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003524 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003525 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003526
junyulaif2c67e42018-08-07 19:50:45 +08003527 pw.println("Status for known UIDs:");
3528 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003529 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003530 for (int i = 0; i < size; i++) {
3531 // Don't crash if the array is modified while dumping in bugreports.
3532 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003533 final int uid = mUidBlockedReasons.keyAt(i);
3534 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3535 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003536 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003537 } catch (ArrayIndexOutOfBoundsException e) {
3538 pw.println(" ArrayIndexOutOfBoundsException");
3539 } catch (ConcurrentModificationException e) {
3540 pw.println(" ConcurrentModificationException");
3541 }
3542 }
3543 pw.println();
3544 pw.decreaseIndent();
3545
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003546 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003547 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003548 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003549 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003550 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003551
Junyu Lai0da479b2022-04-20 15:06:29 +08003552 pw.println("Network Offers:");
3553 pw.increaseIndent();
3554 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3555 pw.println(offerInfo.offer);
3556 }
3557 pw.decreaseIndent();
3558 pw.println();
3559
Robert Greenwalt94e22142014-07-30 16:31:24 -07003560 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003561
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003562 pw.println();
markchien5e866652019-09-30 14:40:57 +08003563 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003564
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003565 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003566 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003567
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003568 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003569
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003570 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003571 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003572 pw.println("mNetworkRequestInfoLogs (most recent first):");
3573 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003574 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003575 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003576
3577 pw.println();
3578 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3579 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003580 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003581 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003582
3583 pw.println();
3584 pw.println("NetTransition WakeLock activity (most recent first):");
3585 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003586 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3587 pw.println("total releases: " + mTotalWakelockReleases);
3588 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3589 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3590 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3591 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3592 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3593 }
James Mattiscb1e0362021-04-06 17:07:42 -07003594 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003595
3596 pw.println();
3597 pw.println("bandwidth update requests (by uid):");
3598 pw.increaseIndent();
3599 synchronized (mBandwidthRequests) {
3600 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3601 pw.println("[" + mBandwidthRequests.keyAt(i)
3602 + "]: " + mBandwidthRequests.valueAt(i));
3603 }
3604 }
3605 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003606 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003607
James Mattiscb1e0362021-04-06 17:07:42 -07003608 pw.println();
3609 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3610 pw.increaseIndent();
3611 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003612 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003613 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003614
3615 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003616
3617 pw.println();
3618 pw.println("Permission Monitor:");
3619 pw.increaseIndent();
3620 mPermissionMonitor.dump(pw);
3621 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003622
3623 pw.println();
3624 pw.println("Legacy network activity:");
3625 pw.increaseIndent();
3626 mNetworkActivityTracker.dump(pw);
3627 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003628 }
3629
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003630 private void dumpNetworks(IndentingPrintWriter pw) {
3631 for (NetworkAgentInfo nai : networksSortedById()) {
3632 pw.println(nai.toString());
3633 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003634 pw.println("Nat464Xlat:");
3635 pw.increaseIndent();
3636 nai.dumpNat464Xlat(pw);
3637 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003638 pw.println(String.format(
3639 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3640 nai.numForegroundNetworkRequests(),
3641 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3642 nai.numBackgroundNetworkRequests(),
3643 nai.numNetworkRequests()));
3644 pw.increaseIndent();
3645 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3646 pw.println(nai.requestAt(i).toString());
3647 }
3648 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003649 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003650 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003651 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003652 pw.decreaseIndent();
3653 pw.decreaseIndent();
3654 }
3655 }
3656
James Mattis8b298a02021-06-01 22:34:04 -07003657 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3658 if (!mProfileNetworkPreferences.isEmpty()) {
3659 pw.println("Profile preferences:");
3660 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09003661 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07003662 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003663 }
James Mattis8b298a02021-06-01 22:34:04 -07003664 if (!mOemNetworkPreferences.isEmpty()) {
3665 pw.println("OEM preferences:");
3666 pw.increaseIndent();
3667 pw.println(mOemNetworkPreferences);
3668 pw.decreaseIndent();
3669 }
3670 if (!mMobileDataPreferredUids.isEmpty()) {
3671 pw.println("Mobile data preferred UIDs:");
3672 pw.increaseIndent();
3673 pw.println(mMobileDataPreferredUids);
3674 pw.decreaseIndent();
3675 }
James Mattis45d81842021-01-10 14:24:24 -08003676
James Mattis8b298a02021-06-01 22:34:04 -07003677 pw.println("Default requests:");
3678 pw.increaseIndent();
3679 dumpPerAppDefaultRequests(pw);
3680 pw.decreaseIndent();
3681 }
3682
3683 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003684 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3685 if (mDefaultRequest == defaultRequest) {
3686 continue;
3687 }
3688
James Mattis8b298a02021-06-01 22:34:04 -07003689 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3690 final String networkOutput;
3691 if (null == satisfier) {
3692 networkOutput = "null";
3693 } else if (mNoServiceNetwork.equals(satisfier)) {
3694 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003695 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003696 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003697 }
James Mattis8b298a02021-06-01 22:34:04 -07003698 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3699 ? "" : " asUid: " + defaultRequest.mAsUid;
3700 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3701 + defaultRequest.mPid + asUidString + "]";
3702 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3703 + " Preference order: " + defaultRequest.mPreferenceOrder
3704 + " Tracked UIDs: " + defaultRequest.getUids();
3705 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003706 }
3707 }
3708
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003709 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003710 NetworkRequestInfo[] infos = null;
3711 while (infos == null) {
3712 try {
3713 infos = requestsSortedById();
3714 } catch (ConcurrentModificationException e) {
3715 // mNetworkRequests should only be accessed from handler thread, except dump().
3716 // As dump() is never called in normal usage, it would be needlessly expensive
3717 // to lock the collection only for its benefit. Instead, retry getting the
3718 // requests if ConcurrentModificationException is thrown during dump().
3719 }
3720 }
3721 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003722 pw.println(nri.toString());
3723 }
3724 }
3725
Ken Chene6d511f2022-01-25 11:10:42 +08003726 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
3727 boolean verbose) {
3728 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09003729 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08003730 } catch (ServiceSpecificException e) {
3731 pw.println(e.getMessage());
3732 } catch (IOException e) {
3733 loge("Dump BPF maps failed, " + e);
3734 }
3735 }
3736
Chalard Jean524f0b12021-10-25 21:11:56 +09003737 private void dumpAllRequestInfoLogsToLogcat() {
3738 try (PrintWriter logPw = new PrintWriter(new Writer() {
3739 @Override
3740 public void write(final char[] cbuf, final int off, final int len) {
3741 // This method is called with 0-length and 1-length arrays for empty strings
3742 // or strings containing only the DEL character.
3743 if (len <= 1) return;
3744 Log.e(TAG, new String(cbuf, off, len));
3745 }
3746 @Override public void flush() {}
3747 @Override public void close() {}
3748 })) {
3749 mNetworkRequestInfoLogs.dump(logPw);
3750 }
3751 }
3752
Hugo Benichia480ba52018-09-03 08:19:02 +09003753 /**
3754 * Return an array of all current NetworkAgentInfos sorted by network id.
3755 */
3756 private NetworkAgentInfo[] networksSortedById() {
3757 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003758 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003759 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003760 return networks;
3761 }
3762
3763 /**
3764 * Return an array of all current NetworkRequest sorted by request id.
3765 */
James Mattis258ea3c2020-11-15 15:04:40 -08003766 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003767 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003768 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003769 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003770 // Sort the array based off the NRI containing the min requestId in its requests.
3771 Arrays.sort(requests,
3772 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3773 Comparator.comparingInt(req -> req.requestId)).requestId
3774 )
3775 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003776 return requests;
3777 }
3778
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003779 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003780 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003781 if (officialNai != null && officialNai.equals(nai)) return true;
3782 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003783 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003784 " - " + nai);
3785 }
3786 return false;
3787 }
3788
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003789 private boolean isDisconnectRequest(Message msg) {
3790 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
3791 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
3792 return info.getState() == NetworkInfo.State.DISCONNECTED;
3793 }
3794
Robert Greenwalt2034b912009-08-12 16:08:25 -07003795 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003796 private class NetworkStateTrackerHandler extends Handler {
3797 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003798 super(looper);
3799 }
3800
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003801 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003802 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3803 final NetworkAgentInfo nai = arg.first;
3804 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003805 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003806 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003807 }
3808 return;
3809 }
3810
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003811 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003812 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003813 return;
3814 }
3815
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003816 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003817 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09003818 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
3819 final NetworkCapabilities sanitized =
3820 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09003821 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003822 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003823 break;
3824 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003825 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003826 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003827 processLinkPropertiesFromAgent(nai, newLp);
3828 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003829 break;
3830 }
3831 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003832 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003833 updateNetworkInfo(nai, info);
3834 break;
3835 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003836 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003837 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003838 break;
3839 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003840 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09003841 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003842 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003843 // Note that if the NAI had been connected, this would affect the
3844 // score, and therefore would require re-mixing the score and performing
3845 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003846 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003847 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3848 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003849 // Mark the network as temporarily accepting partial connectivity so that it
3850 // will be validated (and possibly become default) even if it only provides
3851 // partial internet access. Note that if user connects to partial connectivity
3852 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3853 // out of wifi coverage) and if the same wifi is available again, the device
3854 // will auto connect to this wifi even though the wifi has "no internet".
3855 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003856 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003857 break;
3858 }
junyulai011b1f12019-01-03 18:50:15 +08003859 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003860 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003861 break;
3862 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003863 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003864 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003865 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003866
3867 if (isLegacyLockdownNai(nai)
3868 && (underlying == null || underlying.size() != 1)) {
3869 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3870 + " must have exactly one underlying network: " + underlying);
3871 }
3872
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003873 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3874 nai.declaredUnderlyingNetworks = (underlying != null)
3875 ? underlying.toArray(new Network[0]) : null;
3876
3877 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3878 if (DBG) {
3879 log(nai.toShortString() + " changed underlying networks to "
3880 + Arrays.toString(nai.declaredUnderlyingNetworks));
3881 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003882 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003883 notifyIfacesChangedForNetworkStats();
3884 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003885 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003886 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003887 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3888 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3889 nai.teardownDelayMs = msg.arg1;
3890 } else {
3891 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3892 }
Chalard Jean550b5212021-03-05 23:07:53 +09003893 break;
3894 }
3895 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3896 nai.setLingerDuration((int) arg.second);
3897 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003898 }
Tyler Wear72388212021-09-09 14:49:02 -07003899 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3900 DscpPolicy policy = (DscpPolicy) arg.second;
3901 if (mDscpPolicyTracker != null) {
3902 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3903 }
3904 break;
3905 }
3906 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3907 if (mDscpPolicyTracker != null) {
3908 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3909 }
3910 break;
3911 }
3912 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3913 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08003914 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07003915 }
3916 break;
3917 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09003918 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09003919 if (!nai.everConnected()) {
3920 Log.d(TAG, "unregisterAfterReplacement on never-connected "
3921 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09003922 teardownUnneededNetwork(nai);
3923 break;
3924 }
3925
3926 if (nai.isDestroyed()) {
3927 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
3928 + ", ignoring");
3929 break;
3930 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003931
3932 final int timeoutMs = (int) arg.second;
3933 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3934 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
3935 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
3936 }
3937
3938 // Marking a network awaiting replacement is used to ensure that any requests
3939 // satisfied by the network do not switch to another network until a
3940 // replacement is available or the wait for a replacement times out.
3941 // If the network is inactive (i.e., nascent or lingering), then there are no
3942 // such requests, and there is no point keeping it. Just tear it down.
3943 // Note that setLingerDuration(0) cannot be used to do this because the network
3944 // could be nascent.
3945 nai.clearInactivityState();
3946 if (unneeded(nai, UnneededFor.TEARDOWN)) {
3947 Log.d(TAG, nai.toShortString()
3948 + " marked awaiting replacement is unneeded, tearing down instead");
3949 teardownUnneededNetwork(nai);
3950 break;
3951 }
3952
3953 Log.d(TAG, "Marking " + nai.toShortString()
3954 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
3955 destroyNativeNetwork(nai);
3956
3957 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
3958 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
3959 // consider the fact that the network could already have disconnected or been
3960 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
3961 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
3962 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
3963 mKeepaliveTracker.handleStopAllKeepalives(nai,
3964 SocketKeepalive.ERROR_INVALID_NETWORK);
3965
3966 nai.updateScoreForNetworkAgentUpdate();
3967 // This rematch is almost certainly not going to result in any changes, because
3968 // the destroyed flag is only just above the "current satisfier wins"
3969 // tie-breaker. But technically anything that affects scoring should rematch.
3970 rematchAllNetworksAndRequests();
3971 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
3972 break;
3973 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003974 }
3975 }
3976
3977 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003978 final int netId = msg.arg2;
3979 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003980 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09003981 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003982 switch (msg.what) {
3983 default:
3984 return false;
lucasline117e2e2019-10-22 18:27:33 +08003985 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08003986 if (nai == null) {
3987 break;
3988 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003989 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
3990 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08003991 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003992 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08003993 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003994 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08003995 if (probePrivateDnsCompleted) {
3996 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3997 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003998 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003999 }
4000 // Only show the notification when the private DNS is broken and the
4001 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004002 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004003 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4004 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004005 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004006 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4007 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4008 // private DNS is broken, it means this network is being reevaluated.
4009 // Either probing private DNS is not necessary any more or it hasn't been
4010 // done yet. In either case, the networkCapabilities should be updated to
4011 // reflect the new status.
4012 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004013 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004014 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004015 }
4016 break;
4017 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004018 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004019 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4020
Erik Kline31b4a9e2018-01-11 21:07:29 +09004021 if (nai == null) break;
4022
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004023 handleNetworkTested(nai, results.mTestResult,
4024 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004025 break;
4026 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004027 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004028 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004029 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004030 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004031 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004032 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004033 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4034 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004035 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004036 if (nai == null) {
4037 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4038 break;
4039 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004040 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004041 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004042 (PendingIntent) msg.obj,
4043 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004044 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004045 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004046 break;
4047 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004048 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004049 if (nai == null) break;
4050
Erik Kline9a62f012018-03-21 07:18:33 -07004051 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004052 break;
4053 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004054 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004055 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004056 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004057 break;
4058 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004059 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004060 return true;
4061 }
4062
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004063 private void handleNetworkTested(
4064 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004065 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4066 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004067 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004068
4069 // If there is any kind of working networking, then the NAI has been evaluated
4070 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4071 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004072 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004073 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004074 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4075 // any callback that receives onAvailable for that rematch receives an extra caps
4076 // callback. To prevent that, update the score in the agent so the updates below won't
4077 // see an update to both caps and score at the same time.
4078 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004079 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4080
he_won.hwang881307a2022-03-15 21:23:52 +09004081 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4082 // Assume the validation failure is due to a temporary failure after roaming
4083 // and ignore it. NetworkMonitor will continue to retry validation. If it
4084 // continues to fail after the block timeout expires, the network will be
4085 // marked unvalidated. If it succeeds, then validation state will not change.
4086 return;
4087 }
4088
Chalard Jean254bd162022-08-25 13:04:51 +09004089 final boolean wasValidated = nai.isValidated();
4090 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004091 final boolean wasPortal = nai.captivePortalDetected();
4092 nai.setPartialConnectivity(partial);
4093 nai.setCaptivePortalDetected(portal);
4094 nai.updateScoreForNetworkAgentUpdate();
4095 final boolean partialConnectivityChanged = (wasPartial != partial);
4096 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004097
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004098 if (DBG) {
4099 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4100 ? " with redirect to " + redirectUrl
4101 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004102 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004103 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004104 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004105 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004106 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004107 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004108 if (valid) {
4109 handleFreshlyValidatedNetwork(nai);
4110 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4111 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004112 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004113 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004114 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004115 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004116 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004117 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004118 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004119 NotificationType.PRIVATE_DNS_BROKEN);
4120 // If network becomes valid, the hasShownBroken should be reset for
4121 // that network so that the notification will be fired when the private
4122 // DNS is broken again.
4123 nai.networkAgentConfig.hasShownBroken = false;
4124 }
4125 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004126 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004127 } else if (portalChanged) {
4128 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
4129 == getCaptivePortalMode()) {
4130 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4131 nai.onPreventAutomaticReconnect();
4132 teardownUnneededNetwork(nai);
4133 return;
4134 } else {
4135 updateCapabilitiesForNetwork(nai);
4136 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004137 } else if (becameEvaluated) {
4138 // If valid or partial connectivity changed, updateCapabilities* has
4139 // done the rematch.
4140 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004141 }
4142 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004143
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004144 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004145 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004146 nai.onValidationStatusChanged(
4147 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4148 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004149
4150 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004151 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004152 // immediately. Re-notify partial connectivity silently if no internet
4153 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004154 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004155 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004156 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4157 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004158 }
4159
Chalard Jean254bd162022-08-25 13:04:51 +09004160 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004161 handleNetworkUnvalidated(nai);
4162 }
4163 }
4164
Calvin Ondada1452016-10-11 15:10:46 -07004165 private int getCaptivePortalMode() {
4166 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004167 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4168 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004169 }
4170
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004171 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4172 switch (msg.what) {
4173 default:
4174 return false;
4175 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4176 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4177 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4178 handleLingerComplete(nai);
4179 }
4180 break;
4181 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004182 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4183 handleNetworkAgentRegistered(msg);
4184 break;
4185 }
4186 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4187 handleNetworkAgentDisconnected(msg);
4188 break;
4189 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004190 }
4191 return true;
4192 }
4193
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004194 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004195 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004196 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004197 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004198 maybeHandleNetworkAgentMessage(msg);
4199 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004200 }
4201 }
4202
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004203 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004204 private final int mNetId;
4205 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004206
4207 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004208 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004209 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004210 }
4211
4212 @Override
4213 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4214 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004215 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004216 }
4217
4218 @Override
4219 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004220 // Legacy version of notifyNetworkTestedWithExtras.
4221 // Would only be called if the system has a NetworkStack module older than the
4222 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004223 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004224 }
4225
4226 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004227 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004228 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4229 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004230 final Message msg = mTrackerHandler.obtainMessage(
4231 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004232 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004233 new NetworkTestedResults(
4234 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004235 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004236
4237 // Invoke ConnectivityReport generation for this Network test event.
4238 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4239 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004240
Cody Kestingf1120be2020-08-03 18:01:40 -07004241 // NetworkMonitor reports the network validation result as a bitmask while
4242 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4243 // logical value for ConnectivityDiagnostics.
4244 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4245 p.result);
4246
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004247 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004248 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004249 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4250 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4251
Aaron Huang959d3642021-01-21 15:47:41 +08004252 ConnectivityReportEvent reportEvent =
4253 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4254 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004255 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004256 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004257 }
4258
4259 @Override
4260 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4261 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4262 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004263 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004264 }
4265
4266 @Override
lucasline117e2e2019-10-22 18:27:33 +08004267 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4268 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4269 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004270 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004271 }
4272
4273 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004274 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4275 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4276 EVENT_CAPPORT_DATA_CHANGED,
4277 0, mNetId, data));
4278 }
4279
4280 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004281 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004282 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004283 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004284
4285 final PendingIntent pendingIntent;
4286 // Only the system server can register notifications with package "android"
4287 final long token = Binder.clearCallingIdentity();
4288 try {
paulhu7746e4e2020-06-09 19:07:03 +08004289 pendingIntent = PendingIntent.getBroadcast(
4290 mContext,
4291 0 /* requestCode */,
4292 intent,
4293 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004294 } finally {
4295 Binder.restoreCallingIdentity(token);
4296 }
4297 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4298 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004299 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004300 }
4301
4302 @Override
4303 public void hideProvisioningNotification() {
4304 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004305 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004306 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004307
4308 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004309 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004310 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004311 }
4312
4313 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004314 public int getInterfaceVersion() {
4315 return this.VERSION;
4316 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004317
4318 @Override
4319 public String getInterfaceHash() {
4320 return this.HASH;
4321 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004322 }
4323
Cody Kestingf1120be2020-08-03 18:01:40 -07004324 /**
4325 * Converts the given NetworkMonitor-specific validation result bitmask to a
4326 * ConnectivityDiagnostics-specific validation result int.
4327 */
4328 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4329 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4330 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4331 }
4332 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4333 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4334 }
4335 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4336 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4337 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4338 }
4339
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004340 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004341 log("Data stall detected with methods: " + p.detectionMethod);
4342
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004343 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004344 int detectionMethod = 0;
4345 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4346 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4347 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4348 }
4349 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4350 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4351 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4352 p.tcpMetricsCollectionPeriodMillis);
4353 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004354 }
4355
Cody Kestingf53a0752020-04-15 12:33:28 -07004356 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004357 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004358 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004359
4360 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4361 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4362 // the cost of going through two handlers.
4363 mConnectivityDiagnosticsHandler.sendMessage(msg);
4364 }
4365
Cody Kestingb37958e2020-05-15 10:36:01 -07004366 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4367 return (p.detectionMethod & detectionMethod) != 0;
4368 }
4369
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004370 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4371 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004372 }
4373
Erik Klinea73af002018-06-26 18:53:43 +09004374 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4375 if (nai == null) return;
4376 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4377 // in order to restart a validation pass from within netd.
4378 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4379 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004380 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004381 }
4382 }
4383
Erik Kline31b4a9e2018-01-11 21:07:29 +09004384 private void handlePrivateDnsSettingsChanged() {
4385 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4386
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004387 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004388 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004389 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004390 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4391 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004392 }
4393 }
4394
Erik Kline9a62f012018-03-21 07:18:33 -07004395 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4396 // Private DNS only ever applies to networks that might provide
4397 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004398 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004399
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004400 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004401 // schedule DNS resolutions. If a DNS resolution is required the
4402 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004403 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004404
4405 // With Private DNS bypass support, we can proceed to update the
4406 // Private DNS config immediately, even if we're in strict mode
4407 // and have not yet resolved the provider name into a set of IPs.
4408 updatePrivateDns(nai, cfg);
4409 }
4410
4411 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4412 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004413 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004414 }
4415
dalyk1720e542018-03-05 12:42:22 -05004416 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4417 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4418 if (nai == null) {
4419 return;
4420 }
4421 mDnsManager.updatePrivateDnsValidation(update);
4422 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4423 }
4424
paulhu7c0a2e62021-01-08 00:51:49 +08004425 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004426 int prefixLength) {
4427 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4428 if (nai == null) return;
4429
paulhu7c0a2e62021-01-08 00:51:49 +08004430 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4431 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004432
4433 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004434 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004435 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004436 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004437 prefixLength);
4438 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004439 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004440 return;
4441 }
4442 }
4443
Lorenzo Colittid523d142020-04-01 20:16:30 +09004444 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004445 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4446 }
4447
Hai Shalome58bdc62021-01-11 18:45:34 -08004448 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004449 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004450 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004451 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4452 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4453 }
4454
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004455 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004456 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004457 * @param nai the agent info to update
4458 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004459 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004460 */
junyulai2b6f0c22021-02-03 20:15:30 +08004461 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4462 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4463 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004464 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004465 // one lingered request, set inactive.
4466 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004467 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004468 if (DBG) log("Unsetting inactive " + nai.toShortString());
4469 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004470 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004471 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004472 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004473 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4474 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004475 }
junyulai2b6f0c22021-02-03 20:15:30 +08004476 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004477 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004478 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004479 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004480 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004481 }
4482
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004483 private void handleNetworkAgentRegistered(Message msg) {
4484 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4485 if (!mNetworkAgentInfos.contains(nai)) {
4486 return;
4487 }
4488
4489 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4490 if (VDBG) log("NetworkAgent registered");
4491 } else {
4492 loge("Error connecting NetworkAgent");
4493 mNetworkAgentInfos.remove(nai);
4494 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004495 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004496 synchronized (mNetworkForNetId) {
4497 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004498 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004499 mNetIdManager.releaseNetId(nai.network.getNetId());
4500 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004501 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004502 }
4503 }
4504 }
Paul Jensend5f53392014-11-25 15:26:53 -05004505
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09004506 @VisibleForTesting
4507 protected static boolean shouldCreateNetworksImmediately() {
4508 // Before U, physical networks are only created when the agent advances to CONNECTED.
4509 // In U and above, all networks are immediately created when the agent is registered.
4510 return SdkLevel.isAtLeastU();
4511 }
4512
4513 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4514 @NonNull NetworkInfo.State state) {
4515 if (nai.isCreated()) return false;
4516 if (state == NetworkInfo.State.CONNECTED) return true;
4517 if (state != NetworkInfo.State.CONNECTING) {
4518 // TODO: throw if no WTFs are observed in the field.
4519 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4520 return false;
4521 }
4522 return nai.isVPN() || shouldCreateNetworksImmediately();
4523 }
4524
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004525 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004526 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004527 }
4528
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004529 @VisibleForTesting
4530 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004531 // T+ devices should use unregisterAfterReplacement.
he_won.hwang881307a2022-03-15 21:23:52 +09004532 if (SdkLevel.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004533
4534 // If the network never roamed, return false. The check below is not sufficient if time
4535 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4536 if (nai.lastRoamTime == 0) return false;
4537
he_won.hwang881307a2022-03-15 21:23:52 +09004538 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4539 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004540 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004541 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004542 final long currentTimeMs = SystemClock.elapsedRealtime();
4543 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004544 if (timeSinceLastRoam <= blockTimeOut) {
4545 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4546 return true;
4547 }
4548 }
4549 return false;
4550 }
4551
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004552 private void handleNetworkAgentDisconnected(Message msg) {
4553 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004554 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004555 }
4556
Chalard Jeand9fffc32018-05-11 20:19:20 +09004557 // Destroys a network, remove references to it from the internal state managed by
4558 // ConnectivityService, free its interfaces and clean up.
4559 // Must be called on the Handler thread.
4560 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004561 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004562
4563 if (!mNetworkAgentInfos.contains(nai)) return;
4564
Chalard Jeand9fffc32018-05-11 20:19:20 +09004565 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004566 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004567 }
lucaslinb25c9a62019-02-12 15:30:13 +08004568 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004569 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004570 // A network agent has disconnected.
4571 // TODO - if we move the logic to the network agent (have them disconnect
4572 // because they lost all their requests or because their score isn't good)
4573 // then they would disconnect organically, report their new state and then
4574 // disconnect the channel.
wangshengrjxtjcb9b5334d2023-05-09 09:51:06 +08004575 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004576 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4577 null, null);
4578 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004579 final boolean wasDefault = isDefaultNetwork(nai);
4580 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004581 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004582 }
4583 notifyIfacesChangedForNetworkStats();
4584 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4585 // by other networks that are already connected. Perhaps that can be done by
4586 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4587 // of rematchAllNetworksAndRequests
4588 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004589 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004590
4591 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004592 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4593 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08004594 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004595 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004596 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004597 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004598 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004599 synchronized (mNetworkForNetId) {
4600 // Remove the NetworkAgent, but don't mark the netId as
4601 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004602 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004603 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004604 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08004605 // Update allowed network lists in netd. This should be called after removing nai
4606 // from mNetworkAgentInfos.
4607 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004608 // Remove all previously satisfied requests.
4609 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004610 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004611 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004612 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004613 if (currentNetwork != null
4614 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004615 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004616 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4617 // rematch not to keep disconnected agents instead of setting it here ; this
4618 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004619 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004620 for (final NetworkOfferInfo noi : mNetworkOffers) {
4621 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004622 }
James Mattise3ef1912020-12-20 11:09:58 -08004623
Chalard Jean5b409c72021-02-04 13:12:59 +09004624 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004625 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004626 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004627 // network, because while incorrect this is the closest to the old (also
4628 // incorrect) behavior.
4629 mNetworkActivityTracker.updateDataActivityTracking(
4630 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004631 ensureNetworkTransitionWakelock(nai.toShortString());
4632 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004633 }
4634 }
junyulai2b6f0c22021-02-03 20:15:30 +08004635 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004636 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004637 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004638 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004639 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004640 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004641 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004642
4643 // Immediate teardown.
4644 if (nai.teardownDelayMs == 0) {
4645 destroyNetwork(nai);
4646 return;
4647 }
4648
4649 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004650 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304651 try {
4652 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4653 } catch (RemoteException e) {
4654 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4655 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004656 }
4657 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4658 }
4659
4660 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004661 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004662 // Tell netd to clean up the configuration for this network
4663 // (routing rules, DNS, etc).
4664 // This may be slow as it requires a lot of netd shelling out to ip and
4665 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004666 // after we've rematched networks with requests (which might change the default
4667 // network or service a new request from an app), so network traffic isn't interrupted
4668 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004669 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004670 }
Chalard Jean254bd162022-08-25 13:04:51 +09004671 if (!nai.isCreated() && !SdkLevel.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004672 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4673 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4674 // false if the network was never created.
4675 // TODO: delete when S is no longer supported.
4676 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004677 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004678 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004679 }
4680
Ken Chen6df7a902021-04-09 15:08:42 +08004681 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004682 try {
4683 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004684 final NativeNetworkConfig config;
4685 if (nai.isVPN()) {
4686 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004687 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004688 return false;
4689 }
4690 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4691 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004692 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08004693 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004694 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004695 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004696 getNetworkPermission(nai.networkCapabilities),
4697 false /* secure */,
4698 VpnManager.TYPE_VPN_NONE,
4699 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08004700 }
Ken Chen6df7a902021-04-09 15:08:42 +08004701 mNetd.networkCreate(config);
4702 mDnsResolver.createNetworkCache(nai.network.getNetId());
4703 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4704 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004705 return true;
4706 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004707 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004708 return false;
4709 }
4710 }
4711
Ken Chen6df7a902021-04-09 15:08:42 +08004712 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004713 if (mDscpPolicyTracker != null) {
4714 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
4715 }
Luke Huangfdd11f82019-04-09 18:41:49 +08004716 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004717 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004718 } catch (RemoteException | ServiceSpecificException e) {
4719 loge("Exception destroying network(networkDestroy): " + e);
4720 }
4721 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004722 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004723 } catch (RemoteException | ServiceSpecificException e) {
4724 loge("Exception destroying network: " + e);
4725 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004726 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
4727 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
4728 // gets created, could add data to DnsManager data structures that will never get deleted.
4729 mDnsManager.removeNetwork(nai.network);
4730
4731 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09004732 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004733 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
4734 }
4735
Chalard Jean254bd162022-08-25 13:04:51 +09004736 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004737 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08004738 }
4739
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004740 // If this method proves to be too slow then we can maintain a separate
4741 // pendingIntent => NetworkRequestInfo map.
4742 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4743 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004744 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4745 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4746 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004747 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004748 return entry.getValue();
4749 }
4750 }
4751 return null;
4752 }
4753
Chalard Jean524f0b12021-10-25 21:11:56 +09004754 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4755 if (SdkLevel.isAtLeastT()) {
4756 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4757 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4758 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4759 // bug is fixed.
4760 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004761 throw new IllegalStateException("This NRI is already registered. New : " + nri
4762 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004763 }
4764 }
4765 }
4766 }
4767
Chalard Jeanac9ace02022-01-26 16:54:05 +09004768 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4769 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08004770 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004771 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4772 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004773 }
4774 return false;
4775 }
4776
James Mattisf7027322020-12-13 16:28:14 -08004777 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004778 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004779 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4780 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4781 final NetworkRequestInfo existingRequest =
4782 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004783 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004784 if (DBG) {
4785 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4786 + nri.mRequests.get(0) + " because their intents matched.");
4787 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004788 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004789 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004790 }
Erik Kline05f2b402015-04-30 12:58:40 +09004791 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004792 }
4793
James Mattisf7027322020-12-13 16:28:14 -08004794 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004795 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004796 }
4797
James Mattis3ce3d3c2021-02-09 18:18:28 -08004798 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004799 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004800 for (final NetworkRequestInfo nri : nris) {
4801 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004802 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004803 for (final NetworkRequest req : nri.mRequests) {
4804 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004805 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004806 if (req.isListen()) {
4807 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4808 if (req.networkCapabilities.hasSignalStrength()
4809 && network.satisfiesImmutableCapabilitiesOf(req)) {
4810 updateSignalStrengthThresholds(network, "REGISTER", req);
4811 }
James Mattisf7027322020-12-13 16:28:14 -08004812 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004813 }
4814 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004815
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004816 // If this NRI has a satisfier already, it is replacing an older request that
4817 // has been removed. Track it.
4818 final NetworkRequest activeRequest = nri.getActiveRequest();
4819 if (null != activeRequest) {
4820 // If there is an active request, then for sure there is a satisfier.
4821 nri.getSatisfier().addRequest(activeRequest);
4822 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004823 }
James Mattisf7027322020-12-13 16:28:14 -08004824
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004825 if (mFlags.noRematchAllRequestsOnRegister()) {
4826 rematchNetworksAndRequests(nris);
4827 } else {
4828 rematchAllNetworksAndRequests();
4829 }
James Mattis45d81842021-01-10 14:24:24 -08004830
Chalard Jean0354d8c2021-01-12 10:58:56 +09004831 // Requests that have not been matched to a network will not have been sent to the
4832 // providers, because the old satisfier and the new satisfier are the same (null in this
4833 // case). Send these requests to the providers.
4834 for (final NetworkRequestInfo nri : nris) {
4835 for (final NetworkOfferInfo noi : mNetworkOffers) {
4836 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004837 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004838 }
4839 }
4840
James Mattisf7027322020-12-13 16:28:14 -08004841 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4842 final int callingUid) {
4843 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004844 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004845 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4846 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4847 handleReleaseNetworkRequest(
4848 nri.mRequests.get(0),
4849 callingUid,
4850 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004851 }
4852 }
4853
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004854 // Determines whether the network is the best (or could become the best, if it validated), for
4855 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4856 // on the value of reason:
4857 //
4858 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4859 // then it should be torn down.
4860 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4861 // then it should be lingered.
4862 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004863 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004864
Chalard Jean254bd162022-08-25 13:04:51 +09004865 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09004866 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4867 return false;
4868 }
4869
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004870 final int numRequests;
4871 switch (reason) {
4872 case TEARDOWN:
4873 numRequests = nai.numRequestNetworkRequests();
4874 break;
4875 case LINGER:
4876 numRequests = nai.numForegroundNetworkRequests();
4877 break;
4878 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004879 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004880 return true;
4881 }
4882
Chalard Jean947acd42021-03-08 22:29:27 +09004883 if (numRequests > 0) return false;
4884
Paul Jensende49eb12015-06-25 15:30:08 -04004885 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004886 if (reason == UnneededFor.LINGER
4887 && !nri.isMultilayerRequest()
4888 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004889 // Background requests don't affect lingering.
4890 continue;
4891 }
4892
James Mattis3d229892020-11-16 16:46:28 -08004893 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004894 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004895 }
4896 }
Paul Jensende49eb12015-06-25 15:30:08 -04004897 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004898 }
4899
James Mattis3d229892020-11-16 16:46:28 -08004900 private boolean isNetworkPotentialSatisfier(
4901 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4902 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004903 // request, return immediately. For multilayer requests, check to see if any of the
4904 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004905 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4906 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004907 return false;
4908 }
4909 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004910 // This multilayer listen request is satisfied therefore no further requests need to be
4911 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004912 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004913 return false;
4914 }
James Mattis3d229892020-11-16 16:46:28 -08004915 // As non-multilayer listen requests have already returned, the below would only happen
4916 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004917 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004918 continue;
4919 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09004920 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08004921 // there is hope for it to become one if it validated, then it is needed.
4922 if (candidate.satisfies(req)) {
4923 // As soon as a network is found that satisfies a request, return. Specifically for
4924 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4925 // is important so as to not evaluate lower priority requests further in
4926 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004927 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4928 ? nri.getSatisfier() : null;
4929 // Note that this catches two important cases:
4930 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4931 // is currently satisfying the request. This is desirable when
4932 // cellular ends up validating but WiFi does not.
4933 // 2. Unvalidated WiFi will not be reaped when validated cellular
4934 // is currently satisfying the request. This is desirable when
4935 // WiFi ends up validating and out scoring cellular.
4936 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004937 }
4938 }
4939
4940 return false;
4941 }
4942
Erik Kline0c04b742016-07-07 16:50:58 +09004943 private NetworkRequestInfo getNriForAppRequest(
4944 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004945 // Looking up the app passed param request in mRequests isn't possible since it may return
4946 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4947 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004948 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4949 // to avoid potential race conditions when validating a package->uid mapping when sending
4950 // the callback on the very low-chance that an application shuts down prior to the callback
4951 // being sent.
4952 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4953 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004954
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004955 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004956 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004957 log(String.format("UID %d attempted to %s for unowned request %s",
4958 callingUid, requestedOperation, nri));
4959 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004960 }
Erik Kline0c04b742016-07-07 16:50:58 +09004961 }
4962
4963 return nri;
4964 }
4965
James Mattisf7027322020-12-13 16:28:14 -08004966 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4967 final String callingMethod) {
4968 if (nri.isMultilayerRequest()) {
4969 throw new IllegalStateException(
4970 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004971 }
4972 }
4973
James Mattisf7027322020-12-13 16:28:14 -08004974 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004975 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004976 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4977 // single NetworkRequest and thus does not apply to multilayer requests.
4978 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4979 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004980 return;
4981 }
James Mattis2516da32021-01-31 17:06:19 -08004982 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004983 return;
4984 }
James Mattisf7027322020-12-13 16:28:14 -08004985 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4986 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004987 }
4988 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004989 callCallbackForRequest(
4990 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004991 }
4992
James Mattisf7027322020-12-13 16:28:14 -08004993 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4994 final int callingUid,
4995 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004996 final NetworkRequestInfo nri =
4997 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4998 if (nri == null) {
4999 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005000 }
James Mattisf7027322020-12-13 16:28:14 -08005001 if (VDBG || (DBG && request.isRequest())) {
5002 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005003 }
5004 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005005 if (callOnUnavailable) {
5006 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5007 }
Erik Kline155a59a2015-11-25 12:49:38 +09005008 }
Erik Kline0c04b742016-07-07 16:50:58 +09005009
James Mattisa076c532020-12-02 14:12:41 -08005010 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005011 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005012 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005013 if (null == mNetworkRequests.remove(req)) {
5014 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5015 continue;
5016 }
James Mattisa076c532020-12-02 14:12:41 -08005017 if (req.isListen()) {
5018 removeListenRequestFromNetworks(req);
5019 }
5020 }
James Mattis8f036802021-06-20 16:26:01 -07005021 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005022 if (mDefaultNetworkRequests.remove(nri)) {
5023 // If this request was one of the defaults, then the UID rules need to be updated
5024 // WARNING : if the app(s) for which this network request is the default are doing
5025 // traffic, this will kill their connected sockets, even if an equivalent request
5026 // is going to be reinstated right away ; unconnected traffic will go on the default
5027 // until the new default is set, which will happen very soon.
5028 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5029 // remove ranges for those requests that won't have a replacement
5030 final NetworkAgentInfo satisfier = nri.getSatisfier();
5031 if (null != satisfier) {
5032 try {
paulhu0e79d952021-06-09 16:11:35 +08005033 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5034 satisfier.network.getNetId(),
5035 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005036 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005037 } catch (RemoteException e) {
5038 loge("Exception setting network preference default network", e);
5039 }
5040 }
5041 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005042
Junyu Lai00d92df2022-07-05 11:01:52 +08005043 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005044 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005045 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005046
5047 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005048 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005049 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005050 }
5051 }
5052
Chalard Jean0354d8c2021-01-12 10:58:56 +09005053 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5054 // needed for this offer.
5055 for (final NetworkOfferInfo noi : mNetworkOffers) {
5056 for (final NetworkRequest req : nri.mRequests) {
5057 if (req.isRequest() && noi.offer.neededFor(req)) {
5058 noi.offer.onNetworkUnneeded(req);
5059 }
5060 }
5061 }
James Mattisa076c532020-12-02 14:12:41 -08005062 }
5063
James Mattis3ce3d3c2021-02-09 18:18:28 -08005064 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5065 for (final NetworkRequestInfo nri : nris) {
5066 if (mDefaultRequest == nri) {
5067 // Make sure we never remove the default request.
5068 continue;
5069 }
5070 handleRemoveNetworkRequest(nri);
5071 }
5072 }
5073
James Mattisa076c532020-12-02 14:12:41 -08005074 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5075 // listens don't have a singular affected Network. Check all networks to see
5076 // if this listen request applies and remove it.
5077 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5078 nai.removeRequest(req.requestId);
5079 if (req.networkCapabilities.hasSignalStrength()
5080 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5081 updateSignalStrengthThresholds(nai, "RELEASE", req);
5082 }
5083 }
5084 }
5085
5086 /**
5087 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5088 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5089 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5090 */
5091 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5092 boolean wasKept = false;
5093 final NetworkAgentInfo nai = nri.getSatisfier();
5094 if (nai != null) {
5095 final int requestLegacyType = nri.getActiveRequest().legacyType;
5096 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5097 nai.removeRequest(nri.getActiveRequest().requestId);
5098 if (VDBG || DDBG) {
5099 log(" Removing from current network " + nai.toShortString()
5100 + ", leaving " + nai.numNetworkRequests() + " requests.");
5101 }
5102 // If there are still lingered requests on this network, don't tear it down,
5103 // but resume lingering instead.
5104 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005105 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005106 notifyNetworkLosing(nai, now);
5107 }
5108 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5109 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5110 teardownUnneededNetwork(nai);
5111 } else {
5112 wasKept = true;
5113 }
James Mattisa076c532020-12-02 14:12:41 -08005114 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5115 // Went from foreground to background.
5116 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005117 }
5118
Erik Kline0c04b742016-07-07 16:50:58 +09005119 // Maintain the illusion. When this request arrived, we might have pretended
5120 // that a network connected to serve it, even though the network was already
5121 // connected. Now that this request has gone away, we might have to pretend
5122 // that the network disconnected. LegacyTypeTracker will generate that
5123 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005124 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005125 boolean doRemove = true;
5126 if (wasKept) {
5127 // check if any of the remaining requests for this network are for the
5128 // same legacy type - if so, don't remove the nai
5129 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5130 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005131 if (otherRequest.legacyType == requestLegacyType
5132 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005133 if (DBG) log(" still have other legacy request - leaving");
5134 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005135 }
5136 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005137 }
5138
Erik Kline0c04b742016-07-07 16:50:58 +09005139 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005140 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005141 }
5142 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005143 }
5144 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005145
Junyu Lai00d92df2022-07-05 11:01:52 +08005146 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005147 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005148 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5149 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5150 }
5151
Lorenzo Colittid6459092016-07-04 12:55:44 +09005152 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005153 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005154 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005155 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005156 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005157 }
5158
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005159 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005160 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5161 enforceNetworkStackSettingsOrSetup();
5162 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5163 encodeBool(accept), encodeBool(always), network));
5164 }
5165
5166 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005167 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005168 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005169 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5170 }
5171
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005172 @Override
5173 public void setTestAllowBadWifiUntil(long timeMs) {
5174 enforceSettingsPermission();
5175 if (!Build.isDebuggable()) {
5176 throw new IllegalStateException("Does not support in non-debuggable build");
5177 }
5178
5179 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5180 throw new IllegalArgumentException("It should not exceed "
5181 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5182 }
5183
5184 mHandler.sendMessage(
5185 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5186 }
5187
chiachangwange0192a72023-02-06 13:25:01 +00005188 @Override
5189 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5190 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005191
5192 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5193 throw new IllegalArgumentException("Argument should not exceed "
5194 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5195 }
5196
5197 mHandler.sendMessage(
5198 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5199 }
5200
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005201 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5202 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5203 " accept=" + accept + " always=" + always);
5204
5205 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5206 if (nai == null) {
5207 // Nothing to do.
5208 return;
5209 }
5210
Chalard Jean254bd162022-08-25 13:04:51 +09005211 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005212 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005213 return;
5214 }
5215
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005216 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005217 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005218 }
5219
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005220 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5221 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005222 // If network becomes partial connectivity and user already accepted to use this
5223 // network, we should respect the user's option and don't need to popup the
5224 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005225 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005226 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005227 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005228 }
5229
5230 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005231 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005232 }
5233
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005234 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005235 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005236 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005237 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005238 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005239 }
5240
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005241 }
5242
lucaslin2240ef62019-03-12 13:08:03 +08005243 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5244 boolean always) {
5245 if (DBG) {
5246 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5247 + " always=" + always);
5248 }
5249
5250 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5251 if (nai == null) {
5252 // Nothing to do.
5253 return;
5254 }
5255
Chalard Jean254bd162022-08-25 13:04:51 +09005256 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005257 // The network validated while the dialog box was up. Take no action.
5258 return;
5259 }
5260
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005261 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5262 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005263 }
5264
5265 // TODO: Use the current design or save the user choice into IpMemoryStore.
5266 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005267 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005268 }
5269
5270 if (!accept) {
5271 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005272 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005273 // Tear down the network.
5274 teardownUnneededNetwork(nai);
5275 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005276 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5277 // result in a partial connectivity result which will be processed by
5278 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005279 //
5280 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5281 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005282 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005283 }
5284 }
5285
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005286 private void handleSetAvoidUnvalidated(Network network) {
5287 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005288 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005289 // Nothing to do. The network either disconnected or revalidated.
5290 return;
5291 }
Chalard Jean254bd162022-08-25 13:04:51 +09005292 if (0L == nai.getAvoidUnvalidated()) {
5293 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005294 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005295 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005296 }
5297 }
5298
Chalard Jean5fb43c72022-09-08 19:03:14 +09005299 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005300 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005301 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005302 mHandler.sendMessageDelayed(
Chalard Jean5fb43c72022-09-08 19:03:14 +09005303 mHandler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005304 }
5305
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005306 @Override
5307 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005308 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005309 mHandler.post(() -> {
5310 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5311 if (nai == null) return;
5312 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005313 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005314 });
5315 }
5316
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005317 /**
5318 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5319 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005320 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005321 * @param appExtras Bundle to use as intent extras for the captive portal application.
5322 * Must be treated as opaque to avoid preventing the captive portal app to
5323 * update its arguments.
5324 */
5325 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005326 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005327 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5328 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005329
5330 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5331 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005332 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5333 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005334 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5335
lucaslin75ff7022020-12-17 04:14:35 +08005336 final long token = Binder.clearCallingIdentity();
5337 try {
5338 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5339 } finally {
5340 Binder.restoreCallingIdentity(token);
5341 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005342 }
5343
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005344 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5345 private final Network mNetwork;
5346
5347 private CaptivePortalImpl(Network network) {
5348 mNetwork = network;
5349 }
5350
5351 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005352 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005353 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5354 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005355 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5356 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5357 // Since the network will be disconnected, skip notifying NetworkMonitor
5358 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005359 }
5360
Chiachang Wang938bfba2020-01-09 13:50:55 +08005361 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005362 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005363 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005364 }
5365
5366 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005367 public void appRequest(final int request) {
5368 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5369 if (nm == null) return;
5370
5371 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005372 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005373 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005374 }
5375 }
5376
5377 @Nullable
5378 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5379 // getNetworkAgentInfoForNetwork is thread-safe
5380 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5381 if (nai == null) return null;
5382
5383 // nai.networkMonitor() is thread-safe
5384 return nai.networkMonitor();
5385 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005386 }
5387
Hugo Benichic9048bc2016-09-14 23:23:08 +00005388 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005389 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005390 }
5391
Chalard Jean020b93a2022-09-01 13:20:14 +09005392 private boolean activelyPreferBadWifi() {
5393 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5394 }
5395
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005396 /**
5397 * Return whether the device should maintain continuous, working connectivity by switching away
5398 * from WiFi networks having no connectivity.
5399 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5400 */
5401 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005402 if (!checkNetworkStackPermission()) {
5403 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5404 }
5405 return avoidBadWifi();
5406 }
5407
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005408 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005409 ensureRunningOnConnectivityServiceThread();
5410 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005411 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005412 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005413 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005414 if (avoidBadWifi) {
5415 // If the device is now avoiding bad wifi, remove notifications that might have
5416 // been put up when the device didn't.
5417 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5418 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005419 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005420 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5421 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5422 for (final NetworkOfferInfo noi : offersToUpdate) {
5423 updateOfferScore(noi.offer);
5424 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005425 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005426 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005427 }
5428
Erik Kline95ecfee2016-10-02 18:02:14 +09005429 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005430 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005431 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005432 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005433 if (!configRestrict) {
5434 pw.println("Bad Wi-Fi avoidance: unrestricted");
5435 return;
5436 }
5437
5438 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5439 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005440 pw.println("Config restrict: " + configRestrict);
5441 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005442
Chalard Jeane0fdea32022-09-14 21:44:22 +09005443 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005444 String description;
5445 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005446 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005447 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005448 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005449 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005450 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005451 description = "avoid";
5452 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005453 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005454 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005455 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005456
5457 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5458 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005459 if (null == configValue) {
5460 description = "unset";
5461 } else if (configValue) {
5462 description = "force true";
5463 } else {
5464 description = "force false";
5465 }
5466 pw.println("Actively prefer bad wifi conf: " + description);
5467 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005468 pw.println("Network overrides:");
5469 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005470 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005471 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005472 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005473 }
5474 }
5475 pw.decreaseIndent();
5476 pw.decreaseIndent();
5477 }
5478
paulhu7746e4e2020-06-09 19:07:03 +08005479 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5480 // unify the method.
5481 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5482 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5483 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5484 return settingsComponent != null
5485 ? settingsComponent.getPackageName() : "com.android.settings";
5486 }
5487
lucaslinb1e8e382019-01-24 15:55:30 +08005488 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005489 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005490 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005491 switch (type) {
5492 case NO_INTERNET:
5493 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005494 // High priority because it is only displayed for explicitly selected networks.
5495 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005496 break;
lucasline117e2e2019-10-22 18:27:33 +08005497 case PRIVATE_DNS_BROKEN:
5498 action = Settings.ACTION_WIRELESS_SETTINGS;
5499 // High priority because we should let user know why there is no internet.
5500 highPriority = true;
5501 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005502 case LOST_INTERNET:
5503 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005504 // High priority because it could help the user avoid unexpected data usage.
5505 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005506 break;
lucaslin2240ef62019-03-12 13:08:03 +08005507 case PARTIAL_CONNECTIVITY:
5508 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005509 // Don't bother the user with a high-priority notification if the network was not
5510 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005511 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005512 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005513 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005514 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005515 return;
5516 }
5517
5518 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005519 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005520 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005521 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005522 // Some OEMs have their own Settings package. Thus, need to get the current using
5523 // Settings package name instead of just use default name "com.android.settings".
5524 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5525 intent.setClassName(settingsPkgName,
5526 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005527 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005528
paulhu2af50222020-10-11 22:52:27 +08005529 PendingIntent pendingIntent = PendingIntent.getActivity(
5530 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005531 0 /* requestCode */,
5532 intent,
paulhu2af50222020-10-11 22:52:27 +08005533 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005534
Serik Beketayevec8ad212020-12-07 22:43:07 -08005535 mNotifier.showNotification(
5536 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005537 }
5538
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005539 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5540 // Don't prompt if the network is validated, and don't prompt on captive portals
5541 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005542 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005543 return false;
5544 }
5545
5546 // If a network has partial connectivity, always prompt unless the user has already accepted
5547 // partial connectivity and selected don't ask again. This ensures that if the device
5548 // automatically connects to a network that has partial Internet access, the user will
5549 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005550 // because we have prompted them.
5551 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005552 return true;
5553 }
5554
5555 // If a network has no Internet access, only prompt if the network was explicitly selected
5556 // and if the user has not already told us to use the network regardless of whether it
5557 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005558 if (nai.networkAgentConfig.explicitlySelected
5559 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005560 return true;
5561 }
5562
5563 return false;
5564 }
5565
Chalard Jean5fb43c72022-09-08 19:03:14 +09005566 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5567 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005568
Chalard Jean5fb43c72022-09-08 19:03:14 +09005569 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5570 if (null == nai) return;
5571
5572 if (nai.setEvaluated()) {
5573 // If setEvaluated() returned true, the network never had any form of connectivity.
5574 // This may have an impact on request matching if bad WiFi avoidance is off and the
5575 // network was found not to have Internet access.
5576 nai.updateScoreForNetworkAgentUpdate();
5577 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005578
5579 // Also, if this is WiFi and it should be preferred actively, now is the time to
5580 // prompt the user that they walked past and connected to a bad WiFi.
5581 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5582 && !avoidBadWifi()
5583 && activelyPreferBadWifi()) {
5584 // The notification will be removed if the network validates or disconnects.
5585 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5586 return;
5587 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005588 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005589
Chalard Jean5fb43c72022-09-08 19:03:14 +09005590 if (!shouldPromptUnvalidated(nai)) return;
5591
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005592 // Stop automatically reconnecting to this network in the future. Automatically connecting
5593 // to a network that provides no or limited connectivity is not useful, because the user
5594 // cannot use that network except through the notification shown by this method, and the
5595 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005596 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005597
Chalard Jean254bd162022-08-25 13:04:51 +09005598 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005599 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005600 } else {
5601 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5602 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005603 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005604
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005605 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5606 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005607 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005608
lucaslin2240ef62019-03-12 13:08:03 +08005609 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5610 return;
5611 }
5612
5613 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005614 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005615 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005616 }
5617
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005618 @Override
5619 public int getMultipathPreference(Network network) {
5620 enforceAccessPermission();
5621
5622 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005623 if (nai != null && nai.networkCapabilities
5624 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005625 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5626 }
5627
Aaron Huang9a57acf2020-12-08 10:03:29 +08005628 final NetworkPolicyManager netPolicyManager =
5629 mContext.getSystemService(NetworkPolicyManager.class);
5630
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005631 final long token = Binder.clearCallingIdentity();
5632 final int networkPreference;
5633 try {
5634 networkPreference = netPolicyManager.getMultipathPreference(network);
5635 } finally {
5636 Binder.restoreCallingIdentity(token);
5637 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005638 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005639 return networkPreference;
5640 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005641 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5642 }
5643
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005644 @Override
5645 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005646 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005647 }
5648
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005649 private class InternalHandler extends Handler {
5650 public InternalHandler(Looper looper) {
5651 super(looper);
5652 }
5653
5654 @Override
5655 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005656 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005657 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005658 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005659 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005660 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005661 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005662 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005663 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005664 break;
5665 }
Jason Monka69f1b02013-10-10 14:02:51 -04005666 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005667 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5668 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005669 break;
5670 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005671 case EVENT_REGISTER_NETWORK_PROVIDER: {
5672 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005673 break;
5674 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005675 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5676 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005677 break;
5678 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005679 case EVENT_REGISTER_NETWORK_OFFER: {
5680 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5681 break;
5682 }
5683 case EVENT_UNREGISTER_NETWORK_OFFER: {
5684 final NetworkOfferInfo offer =
5685 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5686 if (null != offer) {
5687 handleUnregisterNetworkOffer(offer);
5688 }
5689 break;
5690 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005691 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005692 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5693 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5694 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005695 break;
5696 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005697 case EVENT_REGISTER_NETWORK_REQUEST:
5698 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005699 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005700 break;
5701 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005702 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5703 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005704 handleRegisterNetworkRequestWithIntent(msg);
5705 break;
5706 }
Erik Kline155a59a2015-11-25 12:49:38 +09005707 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5708 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5709 handleTimedOutNetworkRequest(nri);
5710 break;
5711 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005712 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5713 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5714 break;
5715 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005716 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005717 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5718 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005719 break;
5720 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005721 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005722 Network network = (Network) msg.obj;
5723 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005724 break;
5725 }
lucaslin2240ef62019-03-12 13:08:03 +08005726 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5727 Network network = (Network) msg.obj;
5728 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5729 toBool(msg.arg2));
5730 break;
5731 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005732 case EVENT_SET_AVOID_UNVALIDATED: {
5733 handleSetAvoidUnvalidated((Network) msg.obj);
5734 break;
5735 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09005736 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
5737 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005738 break;
5739 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005740 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5741 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005742 break;
5743 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00005744 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
5745 // handler thread.
5746 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005747 mKeepaliveTracker.handleStartKeepalive(msg);
5748 break;
5749 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00005750 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09005751 final AutomaticOnOffKeepalive ki =
5752 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
5753 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005754
chiachangwang676c84e2023-02-14 09:22:05 +00005755 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005756 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005757 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00005758 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005759 for (NetworkAgentInfo n : mNetworkAgentInfos) {
5760 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00005761 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
5762 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005763 }
5764 }
5765
5766 // If the network no longer exists, then the keepalive should have been
5767 // cleaned up already. There is no point trying to resume keepalives.
5768 if (!networkFound) return;
5769
chiachangwang676c84e2023-02-14 09:22:05 +00005770 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005771 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang676c84e2023-02-14 09:22:05 +00005772 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005773 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00005774 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005775 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005776 }
5777 break;
5778 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005779 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005780 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09005781 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
5782 (IBinder) msg.obj);
5783 if (ki == null) {
5784 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00005785 return;
5786 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09005787 final int reason = msg.arg2;
5788 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005789 break;
5790 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005791 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5792 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5793 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005794 break;
5795 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005796 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5797 handlePrivateDnsSettingsChanged();
5798 break;
dalyk1720e542018-03-05 12:42:22 -05005799 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5800 handlePrivateDnsValidationUpdate(
5801 (PrivateDnsValidationUpdate) msg.obj);
5802 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005803 case EVENT_UID_BLOCKED_REASON_CHANGED:
5804 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005805 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005806 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5807 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5808 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005809 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005810 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5811 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005812 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005813 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005814 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005815 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09005816 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
5817 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005818 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005819 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005820 }
lucaslin1193a5d2021-01-21 02:04:15 +08005821 case EVENT_REPORT_NETWORK_ACTIVITY:
5822 mNetworkActivityTracker.handleReportNetworkActivity();
5823 break;
paulhu51f77dc2021-06-07 02:34:20 +00005824 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5825 handleMobileDataPreferredUidsChanged();
5826 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005827 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5828 final long timeMs = ((Long) msg.obj).longValue();
5829 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5830 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005831 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5832 handleIngressRateLimitChanged();
5833 break;
Hansen Kurli55396972022-10-28 03:31:17 +00005834 case EVENT_USER_DOES_NOT_WANT:
5835 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5836 if (nai == null) break;
5837 nai.onPreventAutomaticReconnect();
5838 nai.disconnect();
5839 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00005840 case EVENT_SET_VPN_NETWORK_PREFERENCE:
5841 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
5842 break;
chiachangwange0192a72023-02-06 13:25:01 +00005843 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
5844 final long time = ((Long) msg.obj).longValue();
5845 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
5846 break;
5847 }
Mark Fasheh7501e762023-05-04 20:23:11 +00005848 case EVENT_UID_FROZEN_STATE_CHANGED:
5849 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
5850 handleFrozenUids(args.mUids, args.mFrozenStates);
5851 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005852 }
5853 }
5854 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005855
Lorenzo Colittid6459092016-07-04 12:55:44 +09005856 @Override
markchien5776f962019-12-16 20:15:20 +08005857 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005858 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08005859 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005860 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5861 Context.TETHERING_SERVICE);
5862 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005863 }
5864
Lorenzo Colittid6459092016-07-04 12:55:44 +09005865 @Override
markchien5776f962019-12-16 20:15:20 +08005866 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005867 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08005868 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005869 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5870 Context.TETHERING_SERVICE);
5871 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005872 }
5873
Lorenzo Colittid6459092016-07-04 12:55:44 +09005874 @Override
markchien5776f962019-12-16 20:15:20 +08005875 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005876 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005877 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005878 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5879 Context.TETHERING_SERVICE);
5880 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005881 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005882
markchien5776f962019-12-16 20:15:20 +08005883
Lorenzo Colittid6459092016-07-04 12:55:44 +09005884 @Override
markchien5776f962019-12-16 20:15:20 +08005885 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005886 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005887 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005888 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5889 Context.TETHERING_SERVICE);
5890
5891 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005892 }
5893
Lorenzo Colittid6459092016-07-04 12:55:44 +09005894 @Override
markchien5776f962019-12-16 20:15:20 +08005895 @Deprecated
5896 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08005897 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005898 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5899 Context.TETHERING_SERVICE);
5900
5901 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005902 }
5903
Udam Saini8f7d6a72017-06-07 12:06:28 -07005904 @Override
markchien5776f962019-12-16 20:15:20 +08005905 @Deprecated
5906 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08005907 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005908 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5909 Context.TETHERING_SERVICE);
5910 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005911 }
5912
Robert Greenwalte0b00512014-07-02 09:59:16 -07005913 // Called when we lose the default network and have no replacement yet.
5914 // This will automatically be cleared after X seconds or a new default network
5915 // becomes CONNECTED, whichever happens first. The timer is started by the
5916 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005917 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005918 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005919 if (mNetTransitionWakeLock.isHeld()) {
5920 return;
5921 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005922 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005923 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5924 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005925 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005926 mWakelockLogs.log("ACQUIRE for " + forWhom);
5927 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005928 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005929 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005930 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005931 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005932
Hugo Benichi471b62a2017-03-30 23:18:10 +09005933 // Called when we gain a new default network to release the network transition wakelock in a
5934 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5935 // message is cancelled.
5936 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005937 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005938 if (!mNetTransitionWakeLock.isHeld()) {
5939 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005940 }
5941 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005942 // Cancel self timeout on wakelock hold.
5943 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5944 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5945 mHandler.sendMessageDelayed(msg, 1000);
5946 }
5947
5948 // Called when either message of ensureNetworkTransitionWakelock or
5949 // scheduleReleaseNetworkTransitionWakelock is processed.
5950 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5951 String event = eventName(eventId);
5952 synchronized (this) {
5953 if (!mNetTransitionWakeLock.isHeld()) {
5954 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005955 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005956 return;
5957 }
5958 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005959 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5960 mTotalWakelockDurationMs += lockDuration;
5961 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5962 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005963 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005964 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005965 }
5966
Robert Greenwalt986c7412010-09-08 15:24:47 -07005967 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005968 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005969 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005970 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005971 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005972 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005973 }
5974
Lorenzo Colittid6459092016-07-04 12:55:44 +09005975 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005976 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005977 enforceAccessPermission();
5978 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005979 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005980 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005981
5982 final NetworkAgentInfo nai;
5983 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005984 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005985 } else {
5986 nai = getNetworkAgentInfoForNetwork(network);
5987 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005988
5989 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005990 mHandler.obtainMessage(
5991 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005992 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005993
Hugo Benichid6b510a2017-04-06 17:22:18 +09005994 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005995 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005996 if (nai == null
5997 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005998 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005999 return;
6000 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006001 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006002 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006003 mConnectivityDiagnosticsHandler.sendMessage(
6004 mConnectivityDiagnosticsHandler.obtainMessage(
6005 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6006 new ReportedNetworkConnectivityInfo(
6007 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006008 return;
6009 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006010 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006011 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006012 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006013 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006014 // Validating a network that has not yet connected could result in a call to
6015 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006016 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006017 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006018 }
paulhu7aeba372020-12-30 00:42:19 +08006019 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6020 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006021 return;
6022 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006023
6024 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6025 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6026 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6027 // completed.
6028 mConnectivityDiagnosticsHandler.sendMessage(
6029 mConnectivityDiagnosticsHandler.obtainMessage(
6030 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6031 new ReportedNetworkConnectivityInfo(
6032 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006033 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006034 }
6035
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006036 // TODO: call into netd.
6037 private boolean queryUserAccess(int uid, Network network) {
6038 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6039 if (nai == null) return false;
6040
6041 // Any UID can use its default network.
6042 if (nai == getDefaultNetworkForUid(uid)) return true;
6043
6044 // Privileged apps can use any network.
6045 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6046 return true;
6047 }
6048
6049 // An unprivileged UID can use a VPN iff the VPN applies to it.
6050 if (nai.isVPN()) {
6051 return nai.networkCapabilities.appliesToUid(uid);
6052 }
6053
6054 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6055 // sockets, i.e., if it is the owner.
6056 final NetworkAgentInfo vpn = getVpnForUid(uid);
6057 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6058 && uid != vpn.networkCapabilities.getOwnerUid()) {
6059 return false;
6060 }
6061
6062 // The UID's permission must be at least sufficient for the network. Since the restricted
6063 // permission was already checked above, that just leaves background networks.
6064 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6065 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6066 }
6067
6068 // Unrestricted network. Anyone gets to use it.
6069 return true;
6070 }
6071
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006072 /**
6073 * Returns information about the proxy a certain network is using. If given a null network, it
6074 * it will return the proxy for the bound network for the caller app or the default proxy if
6075 * none.
6076 *
6077 * @param network the network we want to get the proxy information for.
6078 * @return Proxy information if a network has a proxy configured, or otherwise null.
6079 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006080 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006081 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006082 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006083 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006084 if (network == null) {
6085 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006086 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006087 true);
6088 if (activeNetwork == null) {
6089 return null;
6090 }
6091 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006092 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006093 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6094 // caller may not have.
6095 return getLinkPropertiesProxyInfo(network);
6096 }
6097 // No proxy info available if the calling UID does not have network access.
6098 return null;
6099 }
6100
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006101
6102 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006103 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6104 if (nai == null) return null;
6105 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006106 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6107 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006108 }
6109 }
6110
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006111 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006112 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006113 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006114 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006115 }
6116
Chalard Jean777e2e52018-06-07 18:02:37 +09006117 @Override
6118 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006119 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006120 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006121 }
6122
Junyu Lai970963e2022-10-25 15:46:47 +08006123 private void handleApplyDefaultProxy(@Nullable ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04006124 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05006125 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07006126 proxy = null;
6127 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006128 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006129 }
6130
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006131 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6132 // when any network changes proxy.
6133 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6134 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006135 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6136 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006137 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6138
Chalard Jean7d97afc2018-06-07 17:41:29 +09006139 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006140 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006141 }
6142 }
6143
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006144 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006145 final private HashMap<Uri, Integer> mUriEventMap;
6146 final private Context mContext;
6147 final private Handler mHandler;
6148
6149 SettingsObserver(Context context, Handler handler) {
6150 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006151 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006152 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006153 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006154 }
6155
Erik Kline05f2b402015-04-30 12:58:40 +09006156 void observe(Uri uri, int what) {
6157 mUriEventMap.put(uri, what);
6158 final ContentResolver resolver = mContext.getContentResolver();
6159 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006160 }
6161
6162 @Override
6163 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006164 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006165 }
6166
6167 @Override
6168 public void onChange(boolean selfChange, Uri uri) {
6169 final Integer what = mUriEventMap.get(uri);
6170 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006171 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006172 } else {
6173 loge("No matching event to send for URI=" + uri);
6174 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006175 }
6176 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006177
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006178 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006179 Log.d(TAG, s);
6180 }
6181
6182 private static void logw(String s) {
6183 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006184 }
6185
Daniel Brightf9e945b2020-06-15 16:10:01 -07006186 private static void logwtf(String s) {
6187 Log.wtf(TAG, s);
6188 }
6189
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006190 private static void logwtf(String s, Throwable t) {
6191 Log.wtf(TAG, s, t);
6192 }
6193
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006194 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006195 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006196 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006197
Hugo Benichi39621362017-02-11 17:04:43 +09006198 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006199 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006200 }
6201
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006202 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006203 * Return the information of all ongoing VPNs.
6204 *
6205 * <p>This method is used to update NetworkStatsService.
6206 *
6207 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006208 */
junyulai2050bed2021-01-23 09:46:34 +08006209 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006210 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006211 if (mLockdownEnabled) {
6212 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006213 }
junyulai2050bed2021-01-23 09:46:34 +08006214 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006215 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006216 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006217 if (info != null) {
6218 infoList.add(info);
6219 }
6220 }
junyulai2050bed2021-01-23 09:46:34 +08006221 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006222 }
6223
6224 /**
6225 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006226 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006227 */
junyulai2050bed2021-01-23 09:46:34 +08006228 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006229 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006230 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6231 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006232 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6233 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6234 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006235 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6236 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006237 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006238 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006239 }
6240 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006241
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006242 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006243
6244 List<String> interfaces = new ArrayList<>();
6245 for (Network network : underlyingNetworks) {
6246 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6247 if (underlyingNai == null) continue;
6248 LinkProperties lp = underlyingNai.linkProperties;
6249 for (String iface : lp.getAllInterfaceNames()) {
6250 if (!TextUtils.isEmpty(iface)) {
6251 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006252 }
6253 }
Benedict Wong34857f82019-06-12 17:46:15 +00006254 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006255
6256 if (interfaces.isEmpty()) return null;
6257
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006258 // Must be non-null or NetworkStatsService will crash.
6259 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6260 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006261 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006262 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006263
junyulai2050bed2021-01-23 09:46:34 +08006264 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6265 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006266 }
6267
James Mattisd31bdfa2020-12-23 16:37:26 -08006268 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006269 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6270 Network[] underlyingNetworks) {
6271 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006272 if (underlyingNetworks == null && defaultNetwork != null) {
6273 // null underlying networks means to track the default.
6274 underlyingNetworks = new Network[] { defaultNetwork };
6275 }
6276 return underlyingNetworks;
6277 }
6278
6279 // Returns true iff |network| is an underlying network of |nai|.
6280 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6281 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6282 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006283 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006284 final Network[] underlying = underlyingNetworksOrDefault(
6285 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006286 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006287 }
6288
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006289 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006290 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006291 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006292 * When underlying networks change, such networks may have to update capabilities to reflect
6293 * things like the metered bit, their transports, and so on. The capabilities are calculated
6294 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006295 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006296 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006297 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006298 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006299 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006300 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006301 }
6302 }
6303 }
6304
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006305 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6306 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6307 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6308 // a VPN is not up.
6309 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6310 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6311 for (UidRange range : blockedUidRanges) {
6312 if (range.contains(uid)) return true;
6313 }
6314 return false;
6315 }
6316
6317 @Override
6318 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006319 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006320 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6321 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6322 }
6323
6324 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6325 if (DBG) {
6326 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6327 + Arrays.toString(ranges));
6328 }
6329 // Cannot use a Set since the list of UID ranges might contain duplicates.
6330 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6331 for (int i = 0; i < ranges.length; i++) {
6332 if (requireVpn) {
6333 newVpnBlockedUidRanges.add(ranges[i]);
6334 } else {
6335 newVpnBlockedUidRanges.remove(ranges[i]);
6336 }
6337 }
6338
6339 try {
6340 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6341 } catch (RemoteException | ServiceSpecificException e) {
6342 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6343 + Arrays.toString(ranges) + "): netd command failed: " + e);
6344 }
6345
Motomu Utsumib08654c2022-05-11 05:56:26 +00006346 if (SdkLevel.isAtLeastT()) {
6347 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6348 }
6349
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006350 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6351 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006352 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6353 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006354 }
6355
6356 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6357 }
6358
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006359 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006360 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006361 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006362 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006363 }
6364
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006365 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6366 return mLockdownEnabled
6367 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6368 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006369 }
6370
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006371 private NetworkAgentInfo getLegacyLockdownNai() {
6372 if (!mLockdownEnabled) {
6373 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006374 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006375 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006376 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6377 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006378
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006379 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006380 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6381 // a local variable. There is no need to make a copy because its contents cannot change.
6382 final Network[] underlying = nai.declaredUnderlyingNetworks;
6383 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006384 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006385 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006386
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006387 // The legacy lockdown VPN always uses the default network.
6388 // If the VPN's underlying network is no longer the current default network, it means that
6389 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006390 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6391 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006392 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006393 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006394 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006395 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006396
6397 return nai;
6398 };
6399
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006400 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6401 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6402 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006403 private DetailedState getLegacyLockdownState(DetailedState origState) {
6404 if (origState != DetailedState.CONNECTED) {
6405 return origState;
6406 }
6407 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6408 ? DetailedState.CONNECTING
6409 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006410 }
6411
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006412 private void filterForLegacyLockdown(NetworkInfo ni) {
6413 if (!mLockdownEnabled || !ni.isConnected()) return;
6414 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6415 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6416 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6417 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6418 // network, this time with a state of CONNECTED.
6419 //
6420 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6421 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6422 // is not too far off the truth, since an always-on VPN, when not connected, is always
6423 // trying to reconnect.
6424 if (getLegacyLockdownNai() == null) {
6425 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6426 }
6427 }
6428
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006429 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006430 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006431 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006432 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006433 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6434 return;
6435 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006436 final long ident = Binder.clearCallingIdentity();
6437 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006438 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006439 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006440 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006441 } finally {
6442 Binder.restoreCallingIdentity(ident);
6443 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006444 }
Wink Savillecb117d32013-08-29 14:57:08 -07006445
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006446 @Override
6447 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006448 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006449 final long ident = Binder.clearCallingIdentity();
6450 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006451 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006452 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006453 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6454 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006455 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006456 } finally {
6457 Binder.restoreCallingIdentity(ident);
6458 }
6459 }
6460
James Mattis02220e22021-03-13 19:27:21 -08006461 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006462 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6463 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6464 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006465 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006466 }
6467
James Mattis02220e22021-03-13 19:27:21 -08006468 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006469 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006470 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006471 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6472 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006473 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006474 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6475 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6476 }
junyulaid91e7052020-08-28 13:44:33 +08006477 }
6478
James Mattis02220e22021-03-13 19:27:21 -08006479 private void onPackageChanged(@NonNull final String packageName) {
6480 // This is necessary in case a package is added or removed, but also when it's replaced to
6481 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6482 // as one in the preferences, then it should follow the same routing as that other package,
6483 // which means updating the rules is never to be needed in this case (whether it joins or
6484 // leaves a UID with a preference).
6485 if (isMappedInOemNetworkPreference(packageName)) {
6486 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6487 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006488
6489 // Invalidates cache entry when the package is updated.
6490 synchronized (mSelfCertifiedCapabilityCache) {
6491 mSelfCertifiedCapabilityCache.remove(packageName);
6492 }
James Mattis02220e22021-03-13 19:27:21 -08006493 }
6494
6495 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006496 @Override
6497 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006498 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006499 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006500 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006501
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006502 // User should be filled for below intents, check the existence.
6503 if (user == null) {
6504 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6505 return;
6506 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006507
Lorenzo Colitticd675292021-02-04 17:32:07 +09006508 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006509 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006510 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006511 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006512 } else {
junyulaid91e7052020-08-28 13:44:33 +08006513 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006514 }
6515 }
6516 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006517
James Mattis02220e22021-03-13 19:27:21 -08006518 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6519 @Override
6520 public void onReceive(Context context, Intent intent) {
6521 ensureRunningOnConnectivityServiceThread();
6522 switch (intent.getAction()) {
6523 case Intent.ACTION_PACKAGE_ADDED:
6524 case Intent.ACTION_PACKAGE_REMOVED:
6525 case Intent.ACTION_PACKAGE_REPLACED:
6526 onPackageChanged(intent.getData().getSchemeSpecificPart());
6527 break;
6528 default:
6529 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6530 }
6531 }
6532 };
6533
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006534 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006535 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006536
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006537 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006538 public final String name;
6539 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006540 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006541 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006542
lifraf3a3492021-03-10 13:58:14 +08006543 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6544 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006545 this.name = name;
6546 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006547 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006548 mDeathRecipient = deathRecipient;
6549
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006550 if (mDeathRecipient == null) {
6551 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006552 }
6553 }
6554
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006555 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006556 try {
6557 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6558 } catch (RemoteException e) {
6559 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006560 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006561 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006562 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006563
James Mattis4fce5d12020-11-12 15:53:42 -08006564 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6565 for (int i = 0; i < requests.size(); i++) {
6566 ensureNetworkRequestHasType(requests.get(i));
6567 }
6568 }
6569
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006570 private void ensureNetworkRequestHasType(NetworkRequest request) {
6571 if (request.type == NetworkRequest.Type.NONE) {
6572 throw new IllegalArgumentException(
6573 "All NetworkRequests in ConnectivityService must have a type");
6574 }
6575 }
6576
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006577 /**
6578 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006579 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006580 */
James Mattis258ea3c2020-11-15 15:04:40 -08006581 @VisibleForTesting
6582 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006583 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6584 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006585 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006586
James Mattisa076c532020-12-02 14:12:41 -08006587 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6588 void setSatisfier(
6589 @Nullable final NetworkAgentInfo satisfier,
6590 @Nullable final NetworkRequest activeRequest) {
6591 mSatisfier = satisfier;
6592 mActiveRequest = activeRequest;
6593 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006594
James Mattisd31bdfa2020-12-23 16:37:26 -08006595 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006596 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006597 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006598 private NetworkAgentInfo mSatisfier;
6599 NetworkAgentInfo getSatisfier() {
6600 return mSatisfier;
6601 }
6602
6603 // The request in mRequests assigned to a network agent. This is null if none of the
6604 // requests in mRequests can be satisfied. This member has the constraint of only being
6605 // accessible on the handler thread.
6606 @Nullable
6607 private NetworkRequest mActiveRequest;
6608 NetworkRequest getActiveRequest() {
6609 return mActiveRequest;
6610 }
6611
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006612 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006613 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006614 @Nullable
6615 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006616
6617 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006618 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006619 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006620 final int mPid;
6621 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006622 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006623 @Nullable
6624 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006625
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006626 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006627 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006628
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006629 // Effective UID of this request. This is different from mUid when a privileged process
6630 // files a request on behalf of another UID. This UID is used to determine blocked status,
6631 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6632 // maximum limit of registered callbacks per UID.
6633 final int mAsUid;
6634
paulhu48291862021-07-14 14:53:57 +08006635 // Preference order of this request.
6636 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006637
James Mattis3ce3d3c2021-02-09 18:18:28 -08006638 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6639 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6640 // maintained for keying off of. This is only a concern when the original nri
6641 // mNetworkRequests changes which happens currently for apps that register callbacks to
6642 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6643 // that match the per-app default nri that currently tracks the calling app's uid so that
6644 // callbacks are fired at the appropriate time. When the callbacks fire,
6645 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6646 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6647 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6648 @NonNull
6649 private final NetworkRequest mNetworkRequestForCallback;
6650 NetworkRequest getNetworkRequestForCallback() {
6651 return mNetworkRequestForCallback;
6652 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006653
James Mattisd31bdfa2020-12-23 16:37:26 -08006654 /**
6655 * Get the list of UIDs this nri applies to.
6656 */
6657 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006658 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006659 // networkCapabilities.getUids() returns a defensive copy.
6660 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006661 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6662 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006663 }
6664
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006665 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6666 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006667 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006668 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006669 }
6670
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006671 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006672 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006673 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006674 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006675 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006676 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006677 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006678 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006679 mBinder = null;
6680 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006681 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006682 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006683 mPerUidCounter = getRequestCounter(this);
6684 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006685 /**
6686 * Location sensitive data not included in pending intent. Only included in
6687 * {@link NetworkCallback}.
6688 */
6689 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006690 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006691 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006692 }
6693
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006694 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006695 @Nullable final IBinder binder,
6696 @NetworkCallback.Flag int callbackFlags,
6697 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006698 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6699 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006700 }
6701
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006702 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006703 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006704 @Nullable final IBinder binder,
6705 @NetworkCallback.Flag int callbackFlags,
6706 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006707 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006708 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006709 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006710 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006711 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006712 mBinder = binder;
6713 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006714 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006715 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006716 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006717 mPerUidCounter = getRequestCounter(this);
6718 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006719 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006720 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006721 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006722 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006723 }
6724
James Mattis3ce3d3c2021-02-09 18:18:28 -08006725 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6726 @NonNull final List<NetworkRequest> r) {
6727 super();
6728 ensureAllNetworkRequestsHaveType(r);
6729 mRequests = initializeRequests(r);
6730 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006731 final NetworkAgentInfo satisfier = nri.getSatisfier();
6732 if (null != satisfier) {
6733 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6734 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09006735 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006736 // As this code creates a new NRI with a new set of requests, figure out which of
6737 // the list of requests should be the active request. It is always the first
6738 // request of the list that can be satisfied by the satisfier since the order of
6739 // requests is a priority order.
6740 // Note even in the presence of a satisfier there may not be an active request,
6741 // when the satisfier is the no-service network.
6742 NetworkRequest activeRequest = null;
6743 for (final NetworkRequest candidate : r) {
6744 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6745 activeRequest = candidate;
6746 break;
6747 }
6748 }
6749 setSatisfier(satisfier, activeRequest);
6750 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006751 mMessenger = nri.mMessenger;
6752 mBinder = nri.mBinder;
6753 mPid = nri.mPid;
6754 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006755 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006756 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006757 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006758 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006759 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006760 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006761 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006762 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006763 }
6764
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006765 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006766 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006767 }
6768
paulhue9913722021-05-26 15:19:20 +08006769 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006770 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006771 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006772 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006773 }
6774
James Mattis2516da32021-01-31 17:06:19 -08006775 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6776 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6777 // false.
6778 boolean isBeingSatisfied() {
6779 return (null != mSatisfier && null != mActiveRequest);
6780 }
6781
James Mattis3d229892020-11-16 16:46:28 -08006782 boolean isMultilayerRequest() {
6783 return mRequests.size() > 1;
6784 }
6785
James Mattis45d81842021-01-10 14:24:24 -08006786 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6787 // Creating a defensive copy to prevent the sender from modifying the list being
6788 // reflected in the return value of this method.
6789 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006790 return Collections.unmodifiableList(tempRequests);
6791 }
6792
James Mattisb1392002021-03-31 13:57:52 -07006793 void linkDeathRecipient() {
6794 if (null != mBinder) {
6795 try {
6796 mBinder.linkToDeath(this, 0);
6797 } catch (RemoteException e) {
6798 binderDied();
6799 }
6800 }
6801 }
6802
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006803 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006804 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006805 try {
6806 mBinder.unlinkToDeath(this, 0);
6807 } catch (NoSuchElementException e) {
6808 // Temporary workaround for b/194394697 pending analysis of additional logs
6809 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6810 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006811 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006812 }
6813
paulhu48291862021-07-14 14:53:57 +08006814 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6815 // Compare two preference orders.
6816 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006817 }
6818
paulhu48291862021-07-14 14:53:57 +08006819 int getPreferenceOrderForNetd() {
6820 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6821 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6822 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006823 }
paulhu48291862021-07-14 14:53:57 +08006824 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006825 }
6826
James Mattis4fce5d12020-11-12 15:53:42 -08006827 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006828 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09006829 // As an immutable collection, mRequests cannot change by the time the
6830 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6831 // is acceptable. Use handleReleaseNetworkRequest and not directly
6832 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6833 // the app already unregistered the request.
6834 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6835 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006836 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006837
James Mattis4fce5d12020-11-12 15:53:42 -08006838 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006839 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006840 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6841 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006842 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006843 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006844 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006845 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006846 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006847 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006848 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006849 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006850 }
6851
Junyu Lai00d92df2022-07-05 11:01:52 +08006852 // Keep backward compatibility since the ServiceSpecificException is used by
6853 // the API surface, see {@link ConnectivityManager#convertServiceException}.
6854 public static class RequestInfoPerUidCounter extends PerUidCounter {
6855 RequestInfoPerUidCounter(int maxCountPerUid) {
6856 super(maxCountPerUid);
6857 }
6858
6859 @Override
6860 public synchronized void incrementCountOrThrow(int uid) {
6861 try {
6862 super.incrementCountOrThrow(uid);
6863 } catch (IllegalStateException e) {
6864 throw new ServiceSpecificException(
6865 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
6866 "Uid " + uid + " exceeded its allotted requests limit");
6867 }
6868 }
6869
6870 @Override
6871 public synchronized void decrementCountOrThrow(int uid) {
6872 throw new UnsupportedOperationException("Use decrementCount instead.");
6873 }
6874
6875 public synchronized void decrementCount(int uid) {
6876 try {
6877 super.decrementCountOrThrow(uid);
6878 } catch (IllegalStateException e) {
6879 logwtf("Exception when decrement per uid request count: ", e);
6880 }
6881 }
6882 }
6883
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006884 // This checks that the passed capabilities either do not request a
6885 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006886 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006887 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006888 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006889 throw new SecurityException("Insufficient permissions to request a specific SSID");
6890 }
paulhu1a407652019-03-22 16:35:06 +08006891
6892 if (nc.hasSignalStrength()
6893 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6894 throw new SecurityException(
6895 "Insufficient permissions to request a specific signal strength");
6896 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006897 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006898
junyulai2217bec2021-04-14 23:33:31 +08006899 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006900 enforceNetworkFactoryPermission();
6901 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006902 }
6903
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006904 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006905 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006906 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006907 // mNetworkRequests may contain the same value multiple times in case of
6908 // multilayer requests. It won't matter in this case because the thresholds
6909 // will then be the same and be deduplicated as they enter the `thresholds` set.
6910 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006911 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6912 for (final NetworkRequest req : nri.mRequests) {
6913 if (req.networkCapabilities.hasSignalStrength()
6914 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6915 thresholds.add(req.networkCapabilities.getSignalStrength());
6916 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006917 }
6918 }
6919 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006920 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006921 }
6922
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006923 private void updateSignalStrengthThresholds(
6924 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006925 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006926
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006927 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006928 String detail;
6929 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6930 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6931 } else {
6932 detail = reason;
6933 }
6934 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006935 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006936 }
6937
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006938 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006939 }
6940
Chalard Jeandd421992021-12-16 23:16:02 +09006941 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006942 if (nc == null) {
6943 return;
6944 }
6945 NetworkSpecifier ns = nc.getNetworkSpecifier();
6946 if (ns == null) {
6947 return;
6948 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006949 if (ns instanceof MatchAllNetworkSpecifier) {
6950 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6951 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006952 }
6953
Chalard Jeandd421992021-12-16 23:16:02 +09006954 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006955 ensureValidNetworkSpecifier(nc);
6956 if (nc.isPrivateDnsBroken()) {
6957 throw new IllegalArgumentException("Can't request broken private DNS");
6958 }
Chalard Jeande665262022-02-25 16:12:12 +09006959 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09006960 throw new IllegalArgumentException("Can't request access UIDs");
6961 }
lucasline117e2e2019-10-22 18:27:33 +08006962 }
6963
Chalard Jeandd421992021-12-16 23:16:02 +09006964 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6965 ensureListenableCapabilities(nc);
6966 final String badCapability = nc.describeFirstNonRequestableCapability();
6967 if (badCapability != null) {
6968 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6969 }
6970 }
6971
Chiachang Wang3bc52762021-11-25 14:17:57 +08006972 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6973 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006974 private boolean isTargetSdkAtleast(int version, int callingUid,
6975 @NonNull String callingPackageName) {
6976 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006977 final PackageManager pm =
6978 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006979 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006980 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006981 if (callingVersion < version) return false;
6982 } catch (PackageManager.NameNotFoundException e) { }
6983 return true;
6984 }
6985
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006986 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006987 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006988 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006989 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006990 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006991 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006992 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6993 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006994 throw new SecurityException("Insufficient permissions to specify legacy type");
6995 }
markchienfac84a22020-03-18 21:16:15 +08006996 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006997 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006998 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006999 // Privileged callers can track the default network of another UID by passing in a UID.
7000 if (asUid != Process.INVALID_UID) {
7001 enforceSettingsPermission();
7002 } else {
7003 asUid = callingUid;
7004 }
junyulaiad010792021-01-11 16:53:38 +08007005 final NetworkRequest.Type reqType;
7006 try {
7007 reqType = NetworkRequest.Type.values()[reqTypeInt];
7008 } catch (ArrayIndexOutOfBoundsException e) {
7009 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7010 }
7011 switch (reqType) {
7012 case TRACK_DEFAULT:
7013 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007014 // is unused and will be replaced by ones appropriate for the UID (usually, the
7015 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007016 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007017 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007018 enforceAccessPermission();
7019 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007020 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007021 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007022 networkCapabilities = new NetworkCapabilities(defaultNc);
7023 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007024 case BACKGROUND_REQUEST:
7025 enforceNetworkStackOrSettingsPermission();
7026 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007027 case REQUEST:
7028 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7029 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007030 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007031 // TODO: this is incorrect. We mark the request as metered or not depending on
7032 // the state of the app when the request is filed, but we never change the
7033 // request if the app changes network state. http://b/29964605
7034 enforceMeteredApnPolicy(networkCapabilities);
7035 break;
junyulai1b1c8742021-03-12 20:05:08 +08007036 case LISTEN_FOR_BEST:
7037 enforceAccessPermission();
7038 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7039 break;
junyulaiad010792021-01-11 16:53:38 +08007040 default:
7041 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007042 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007043 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007044 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007045 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007046
junyulai1b1c8742021-03-12 20:05:08 +08007047 // Enforce FOREGROUND if the caller does not have permission to use background network.
7048 if (reqType == LISTEN_FOR_BEST) {
7049 restrictBackgroundRequestForCaller(networkCapabilities);
7050 }
7051
7052 // Set the UID range for this request to the single UID of the requester, unless the
7053 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007054 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7055 // are no visible methods to set the UIDs, an app could use reflection to try and get
7056 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007057 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007058 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7059 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007060
Etan Cohen85000162017-02-05 10:42:27 -08007061 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007062 throw new IllegalArgumentException("Bad timeout specified");
7063 }
Etan Cohen9786d922015-11-18 10:56:15 -08007064
James Mattis3ce3d3c2021-02-09 18:18:28 -08007065 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007066 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007067 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007068 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007069 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007070 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007071
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007072 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7073 // copied from the default request above. (This is necessary to ensure, for example, that
7074 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7075 // changes don't alter request matching.
7076 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7077 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007078 throw new IllegalStateException(
7079 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007080 + networkCapabilities + " vs. " + defaultNc);
7081 }
7082
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007083 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007084 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007085 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007086 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007087 }
7088 return networkRequest;
7089 }
7090
James Mattis3ce3d3c2021-02-09 18:18:28 -08007091 /**
7092 * Return the nri to be used when registering a network request. Specifically, this is used with
7093 * requests registered to track the default request. If there is currently a per-app default
7094 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7095 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007096 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7097 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007098 * @param nr the network request for the nri.
7099 * @param msgr the messenger for the nri.
7100 * @param binder the binder for the nri.
7101 * @param callingAttributionTag the calling attribution tag for the nri.
7102 * @return the nri to register.
7103 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007104 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007105 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007106 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007107 @Nullable String callingAttributionTag) {
7108 final List<NetworkRequest> requests;
7109 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7110 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007111 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007112 } else {
7113 requests = Collections.singletonList(nr);
7114 }
Roshan Pius951c0032020-12-22 15:10:42 -08007115 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007116 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007117 }
7118
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007119 private boolean shouldCheckCapabilitiesDeclaration(
7120 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7121 @NonNull final String callingPackageName) {
7122 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7123 // Only run the check if the change is enabled.
7124 if (!mDeps.isChangeEnabled(
7125 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7126 callingPackageName, user)) {
7127 return false;
7128 }
7129
7130 return networkCapabilities.hasCapability(
7131 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7132 || networkCapabilities.hasCapability(
7133 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7134 }
7135
7136 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
7137 @NonNull final NetworkCapabilities networkCapabilities) {
7138 // This check is added to fix the linter error for "current min is 30", which is not going
7139 // to happen because Connectivity service always run in S+.
7140 if (!SdkLevel.isAtLeastS()) {
7141 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7142 return;
7143 }
7144 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007145 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007146 try {
7147 synchronized (mSelfCertifiedCapabilityCache) {
7148 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7149 callerPackageName);
7150 if (applicationNetworkCapabilities == null) {
7151 final PackageManager packageManager = mContext.getPackageManager();
7152 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7153 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7154 callerPackageName
7155 );
7156 final XmlResourceParser parser = packageManager
7157 .getResourcesForApplication(callerPackageName)
7158 .getXml(networkSliceProperty.getResourceId());
7159 applicationNetworkCapabilities =
7160 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7161 mSelfCertifiedCapabilityCache.put(callerPackageName,
7162 applicationNetworkCapabilities);
7163 }
7164
7165 }
7166 } catch (PackageManager.NameNotFoundException ne) {
7167 throw new SecurityException(
7168 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7169 + " property");
7170 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7171 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007172 } finally {
7173 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007174 }
7175
7176 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7177 networkCapabilities);
7178 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007179 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007180 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007181 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7182 callingPackageName)) {
7183 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7184 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007185 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007186 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7187 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7188 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7189 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007190 }
junyulai96bd9fe2022-03-08 17:36:42 +08007191 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007192 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007193 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007194 }
7195 }
7196
fenglu3f357402015-03-20 11:29:56 -07007197 @Override
fenglub00f4882015-04-21 17:12:05 -07007198 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007199 enforceAccessPermission();
7200 NetworkAgentInfo nai = null;
7201 if (network == null) {
7202 return false;
7203 }
7204 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007205 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007206 }
7207 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007208 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007209 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007210 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007211 Integer uidReqs = mBandwidthRequests.get(uid);
7212 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007213 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007214 }
7215 mBandwidthRequests.put(uid, ++uidReqs);
7216 }
fenglu3f357402015-03-20 11:29:56 -07007217 return true;
7218 }
7219 return false;
7220 }
7221
Felipe Leme0a5ae422016-06-20 16:36:29 -07007222 private boolean isSystem(int uid) {
7223 return uid < Process.FIRST_APPLICATION_UID;
7224 }
fenglu3f357402015-03-20 11:29:56 -07007225
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007226 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007227 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007228 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007229 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007230 return;
7231 }
Hugo Benichi39621362017-02-11 17:04:43 +09007232 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7233 // Policy already enforced.
7234 return;
7235 }
paulhuaf50d7d2020-12-24 19:47:34 +08007236 final long ident = Binder.clearCallingIdentity();
7237 try {
7238 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7239 // If UID is restricted, don't allow them to bring up metered APNs.
7240 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7241 }
7242 } finally {
7243 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007244 }
7245 }
7246
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007247 @Override
7248 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007249 PendingIntent operation, @NonNull String callingPackageName,
7250 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007251 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007252 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007253 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007254 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007255 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007256 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007257 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007258 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007259 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007260 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7261 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007262
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007263 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007264 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007265 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7266 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007267 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007268 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7269 nri));
7270 return networkRequest;
7271 }
7272
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007273 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7274 mHandler.sendMessageDelayed(
7275 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007276 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007277 }
7278
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007279 @Override
7280 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007281 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007282 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007283 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007284 }
7285
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007286 // In order to implement the compatibility measure for pre-M apps that call
7287 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7288 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7289 // This ensures it has permission to do so.
7290 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7291 if (nc == null) {
7292 return false;
7293 }
7294 int[] transportTypes = nc.getTransportTypes();
7295 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7296 return false;
7297 }
7298 try {
7299 mContext.enforceCallingOrSelfPermission(
7300 android.Manifest.permission.ACCESS_WIFI_STATE,
7301 "ConnectivityService");
7302 } catch (SecurityException e) {
7303 return false;
7304 }
7305 return true;
7306 }
7307
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007308 @Override
7309 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007310 Messenger messenger, IBinder binder,
7311 @NetworkCallback.Flag int callbackFlags,
7312 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007313 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007314 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7315 enforceAccessPermission();
7316 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007317
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007318 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007319 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007320 Binder.getCallingPid(), callingUid, callingPackageName);
7321 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007322 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7323 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7324 // onLost and onAvailable callbacks when networks move in and out of the background.
7325 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7326 // can't request networks.
7327 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007328 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007329
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007330 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007331 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007332 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007333 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007334 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007335 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007336
7337 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7338 return networkRequest;
7339 }
7340
7341 @Override
7342 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007343 PendingIntent operation, @NonNull String callingPackageName,
7344 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007345 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007346 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007347 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7348 enforceAccessPermission();
7349 }
Chalard Jeandd421992021-12-16 23:16:02 +09007350 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007351 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007352 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007353 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007354 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007355
7356 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007357 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007358 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7359 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007360 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007361
WeiZhang1cc3f172021-06-03 19:02:04 -05007362 mHandler.sendMessage(mHandler.obtainMessage(
7363 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007364 }
7365
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007366 /** Returns the next Network provider ID. */
7367 public final int nextNetworkProviderId() {
7368 return mNextNetworkProviderId.getAndIncrement();
7369 }
7370
Erik Kline0c04b742016-07-07 16:50:58 +09007371 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007372 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007373 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007374 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007375 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007376 }
7377
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007378 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7379 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007380 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7381 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7382 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007383 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007384 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007385 return;
7386 }
7387
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007388 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7389 mNetworkProviderInfos.put(npi.messenger, npi);
7390 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007391 }
7392
7393 @Override
7394 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007395 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007396 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007397 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007398 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007399 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7400 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007401 }
7402
7403 @Override
7404 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007405 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007406 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007407 }
7408
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007409 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007410 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007411 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7412 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007413 Objects.requireNonNull(score);
7414 Objects.requireNonNull(caps);
7415 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007416 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007417 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007418 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7419 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007420 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7421 }
7422
Chalard Jeanbb902a52021-08-18 01:35:19 +09007423 private void updateOfferScore(final NetworkOffer offer) {
7424 final boolean yieldToBadWiFi =
7425 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7426 final NetworkOffer newOffer = new NetworkOffer(
7427 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7428 offer.caps, offer.callback, offer.providerId);
7429 if (offer.equals(newOffer)) return;
7430 handleRegisterNetworkOffer(newOffer);
7431 }
7432
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007433 @Override
7434 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007435 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007436 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7437 }
7438
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007439 private void handleUnregisterNetworkProvider(Messenger messenger) {
7440 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7441 if (npi == null) {
7442 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007443 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007444 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007445 // Unregister all the offers from this provider
7446 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7447 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007448 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007449 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7450 toRemove.add(noi);
7451 }
7452 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007453 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007454 handleUnregisterNetworkOffer(noi);
7455 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007456 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007457 }
7458
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007459 @Override
James Mattisf7027322020-12-13 16:28:14 -08007460 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007461 if (request.hasTransport(TRANSPORT_TEST)) {
7462 enforceNetworkFactoryOrTestNetworksPermission();
7463 } else {
7464 enforceNetworkFactoryPermission();
7465 }
James Mattisf7027322020-12-13 16:28:14 -08007466 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7467 if (nri != null) {
7468 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7469 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7470 mHandler.post(() -> handleReleaseNetworkRequest(
7471 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7472 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007473 }
7474
Paul Jensen1f567382015-02-13 14:18:39 -05007475 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7476 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007477 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007478 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007479 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007480 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007481 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007482
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007483 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007484 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007485 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007486
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007487 // UID ranges for users that are currently blocked by VPNs.
7488 // This array is accessed and iterated on multiple threads without holding locks, so its
7489 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7490 // (on the handler thread).
7491 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7492
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007493 // Must only be accessed on the handler thread
7494 @NonNull
7495 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7496
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007497 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007498 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007499
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007500 // Current OEM network preferences. This object must only be written to on the handler thread.
7501 // Since it is immutable and always non-null, other threads may read it if they only care
7502 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007503 @NonNull
7504 private OemNetworkPreferences mOemNetworkPreferences =
7505 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007506 // Current per-profile network preferences. This object follows the same threading rules as
7507 // the OEM network preferences above.
7508 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007509 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7510 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007511
lucaslin3ba7cc22022-12-19 02:35:33 +00007512 // Current VPN network preferences. This object follows the same threading rules as the OEM
7513 // network preferences above.
7514 @NonNull
7515 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7516 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7517
paulhu51f77dc2021-06-07 02:34:20 +00007518 // A set of UIDs that should use mobile data preferentially if available. This object follows
7519 // the same threading rules as the OEM network preferences above.
7520 @NonNull
7521 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7522
James Mattiscb1e0362021-04-06 17:07:42 -07007523 // OemNetworkPreferences activity String log entries.
7524 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7525 @NonNull
7526 private final LocalLog mOemNetworkPreferencesLogs =
7527 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7528
James Mattis02220e22021-03-13 19:27:21 -08007529 /**
7530 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7531 * @param packageName the package name to check existence of a mapping for.
7532 * @return true if a mapping exists, false otherwise
7533 */
7534 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7535 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7536 }
7537
James Mattise3ef1912020-12-20 11:09:58 -08007538 // The always-on request for an Internet-capable network that apps without a specific default
7539 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007540 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007541 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007542 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007543 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007544 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007545 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007546 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007547
James Mattisd31bdfa2020-12-23 16:37:26 -08007548 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7549 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7550 }
7551
7552 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007553 * Return the default network request currently tracking the given uid.
7554 * @param uid the uid to check.
7555 * @return the NetworkRequestInfo tracking the given uid.
7556 */
7557 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007558 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007559 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007560 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007561 // Checking the first request is sufficient as only multilayer requests will have more
7562 // than one request and for multilayer, all requests will track the same uids.
7563 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007564 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007565 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007566 highestPriorityNri = nri;
7567 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007568 }
7569 }
paulhuaa0743d2021-05-26 21:56:03 +08007570 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007571 }
7572
7573 /**
7574 * Get a copy of the network requests of the default request that is currently tracking the
7575 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007576 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7577 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007578 * @param requestorUid the uid to check the default for.
7579 * @param requestorPackageName the requestor's package name.
7580 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7581 */
7582 @NonNull
7583 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007584 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007585 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007586 getDefaultRequestTrackingUid(asUid).mRequests,
7587 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007588 }
7589
7590 /**
7591 * Copy the given nri's NetworkRequest collection.
7592 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007593 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7594 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007595 * @param requestorUid the uid to set on the copied collection.
7596 * @param requestorPackageName the package name to set on the copied collection.
7597 * @return the copied NetworkRequest collection.
7598 */
7599 @NonNull
7600 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007601 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7602 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007603 final List<NetworkRequest> requests = new ArrayList<>();
7604 for (final NetworkRequest nr : requestsToCopy) {
7605 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007606 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007607 nr.legacyType, nextNetworkRequestId(), nr.type));
7608 }
7609 return requests;
7610 }
7611
7612 @NonNull
7613 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007614 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7615 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007616 // These capabilities are for a TRACK_DEFAULT callback, so:
7617 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7618 // mDefaultRequest and a per-UID default request.
7619 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007620 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007621 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007622 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7623 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007624 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007625 restrictRequestUidsForCallerAndSetRequestorInfo(
7626 netCap, requestorUid, requestorPackageName);
7627 return netCap;
7628 }
7629
7630 /**
7631 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7632 * @param nr the network request to check for equality against.
7633 * @return the nri if one exists, null otherwise.
7634 */
7635 @Nullable
7636 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7637 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7638 if (nri.getNetworkRequestForCallback().equals(nr)) {
7639 return nri;
7640 }
7641 }
7642 return null;
7643 }
7644
7645 /**
7646 * Check if an nri is currently being managed by per-app default networking.
7647 * @param nri the nri to check.
7648 * @return true if this nri is currently being managed by per-app default networking.
7649 */
7650 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7651 // nri.mRequests.get(0) is only different from the original request filed in
7652 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7653 // functionality therefore if these two don't match, it means this particular nri is
7654 // currently being managed by a per-app default.
7655 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7656 }
7657
7658 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007659 * Determine if an nri is a managed default request that disallows default networking.
7660 * @param nri the request to evaluate
7661 * @return true if device-default networking is disallowed
7662 */
7663 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7664 // Check if this nri is a managed default that supports the default network at its
7665 // lowest priority request.
7666 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7667 final NetworkCapabilities lowestPriorityNetCap =
7668 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7669 return isPerAppDefaultRequest(nri)
7670 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7671 lowestPriorityNetCap));
7672 }
7673
Erik Kline05f2b402015-04-30 12:58:40 +09007674 // Request used to optionally keep mobile data active even when higher
7675 // priority networks like Wi-Fi are active.
7676 private final NetworkRequest mDefaultMobileDataRequest;
7677
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007678 // Request used to optionally keep wifi data active even when higher
7679 // priority networks like ethernet are active.
7680 private final NetworkRequest mDefaultWifiRequest;
7681
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007682 // Request used to optionally keep vehicle internal network always active
7683 private final NetworkRequest mDefaultVehicleRequest;
7684
James Mattisd31bdfa2020-12-23 16:37:26 -08007685 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7686 // network with no service. This NAI should never be matched against, nor should any public API
7687 // ever return the associated network. For this reason, this NAI is not in the list of available
7688 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7689 // default requests that don't support using the device default network which will ultimately
7690 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7691 @VisibleForTesting
7692 final NetworkAgentInfo mNoServiceNetwork;
7693
Chalard Jean5b409c72021-02-04 13:12:59 +09007694 // The NetworkAgentInfo currently satisfying the default request, if any.
7695 private NetworkAgentInfo getDefaultNetwork() {
7696 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007697 }
7698
James Mattis2516da32021-01-31 17:06:19 -08007699 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007700 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007701 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7702 // Currently, all network requests will have the same uids therefore checking the first
7703 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007704 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007705 if (null == uids) {
7706 continue;
7707 }
7708 for (final UidRange range : uids) {
7709 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007710 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007711 highestPriorityNri = nri;
7712 }
James Mattis2516da32021-01-31 17:06:19 -08007713 }
7714 }
7715 }
paulhuaa0743d2021-05-26 21:56:03 +08007716 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007717 }
7718
Varun Ananddf569952019-02-06 10:13:38 -08007719 @Nullable
7720 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7721 return nai != null ? nai.network : null;
7722 }
7723
7724 private void ensureRunningOnConnectivityServiceThread() {
7725 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7726 throw new IllegalStateException(
7727 "Not running on ConnectivityService thread: "
7728 + Thread.currentThread().getName());
7729 }
7730 }
7731
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007732 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007733 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7734 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007735 }
7736
Chalard Jean29d06db2018-05-02 21:14:54 +09007737 /**
7738 * Register a new agent with ConnectivityService to handle a network.
7739 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007740 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007741 * @param networkInfo the initial info associated with this network. It can be updated later :
7742 * see {@link #updateNetworkInfo}.
7743 * @param linkProperties the initial link properties of this network. They can be updated
7744 * later : see {@link #updateLinkProperties}.
7745 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007746 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007747 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007748 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007749 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007750 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007751 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007752 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007753 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007754 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7755 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007756 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7757 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7758 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007759 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007760 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007761 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08007762 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007763 } else {
7764 enforceNetworkFactoryPermission();
7765 }
7766
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007767 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007768 final long token = Binder.clearCallingIdentity();
7769 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007770 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007771 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007772 } finally {
7773 Binder.restoreCallingIdentity(token);
7774 }
7775 }
7776
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007777 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007778 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007779 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7780 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007781
Chalard Jeandbc46952022-02-02 00:14:18 +09007782 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
7783 // and mutate them at any time.
7784 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
7785 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
7786 final LinkProperties lpCopy = new LinkProperties(linkProperties);
7787
Chalard Jean366c5252022-01-25 18:27:53 +09007788 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09007789 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09007790 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7791 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007792 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09007793 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007794 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007795 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7796 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007797
Chalard Jeandbc46952022-02-02 00:14:18 +09007798 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09007799 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007800 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007801 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007802 mDeps.getNetworkStack().makeNetworkMonitor(
7803 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007804 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7805 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007806 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007807 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007808 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007809 }
7810
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007811 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007812 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007813 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09007814 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007815 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09007816 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
7817 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
7818 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09007819
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007820 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007821
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007822 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007823 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007824 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007825 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007826
7827 try {
7828 networkMonitor.start();
7829 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007830 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007831 }
Chalard Jean366c5252022-01-25 18:27:53 +09007832
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007833 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007834 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007835 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007836 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007837 }
7838
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007839 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7840 @NonNull public final NetworkOffer offer;
7841
7842 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7843 this.offer = offer;
7844 }
7845
7846 @Override
7847 public void binderDied() {
7848 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7849 }
7850 }
7851
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007852 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7853 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7854 if (npi.providerId == providerId) return true;
7855 }
7856 return false;
7857 }
7858
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007859 /**
7860 * Register or update a network offer.
7861 * @param newOffer The new offer. If the callback member is the same as an existing
7862 * offer, it is an update of that offer.
7863 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007864 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007865 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7866 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007867 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007868 // This may actually happen if a provider updates its score or registers and then
7869 // immediately unregisters. The offer would still be in the handler queue, but the
7870 // provider would have been removed.
7871 if (DBG) log("Received offer from an unregistered provider");
7872 return;
7873 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007874 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7875 if (null != existingOffer) {
7876 handleUnregisterNetworkOffer(existingOffer);
7877 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007878 if (DBG) {
7879 // handleUnregisterNetworkOffer has already logged the old offer
7880 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7881 }
7882 } else {
7883 if (DBG) {
7884 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7885 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007886 }
7887 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7888 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007889 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007890 } catch (RemoteException e) {
7891 noi.binderDied();
7892 return;
7893 }
7894 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007895 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007896 }
7897
7898 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7899 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007900 if (DBG) {
7901 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7902 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007903
7904 // If the provider removes the offer and dies immediately afterwards this
7905 // function may be called twice in a row, but the array will no longer contain
7906 // the offer.
7907 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007908 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007909 }
7910
7911 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7912 @NonNull final INetworkOfferCallback callback) {
7913 ensureRunningOnConnectivityServiceThread();
7914 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007915 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007916 }
7917 return null;
7918 }
7919
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007920 /**
7921 * Called when receiving LinkProperties directly from a NetworkAgent.
7922 * Stores into |nai| any data coming from the agent that might also be written to the network's
7923 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7924 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007925 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007926 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007927 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7928 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007929 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007930 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007931 }
7932
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007933 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08007934 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007935 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007936
Lorenzo Colittid523d142020-04-01 20:16:30 +09007937 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7938 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7939 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007940 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007941
Suprabh Shukla1e312032023-01-24 03:36:37 -08007942 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007943
7944 // update filtering rules, need to happen after the interface update so netd knows about the
7945 // new interface (the interface name -> index map becomes initialized)
7946 updateVpnFiltering(newLp, oldLp, networkAgent);
7947
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007948 updateMtu(newLp, oldLp);
7949 // TODO - figure out what to do for clat
7950// for (LinkProperties lp : newLp.getStackedLinks()) {
7951// updateMtu(lp, null);
7952// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007953 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007954 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7955 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007956
Erik Klineb9888902016-04-05 13:30:49 +09007957 updateRoutes(newLp, oldLp, netId);
7958 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007959 // Make sure LinkProperties represents the latest private DNS status.
7960 // This does not need to be done before updateDnses because the
7961 // LinkProperties are not the source of the private DNS configuration.
7962 // updateDnses will fetch the private DNS configuration from DnsManager.
7963 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007964
Chalard Jean5b409c72021-02-04 13:12:59 +09007965 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007966 handleApplyDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09007967 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007968 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007969 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007970
7971 updateWakeOnLan(newLp);
7972
Hai Shalome58bdc62021-01-11 18:45:34 -08007973 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7974 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7975 // does, it needs to be merged here.
7976 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7977 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007978
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007979 // TODO - move this check to cover the whole function
7980 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007981 synchronized (networkAgent) {
7982 networkAgent.linkProperties = newLp;
7983 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007984 // Start or stop DNS64 detection and 464xlat according to network state.
7985 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08007986 // Notify NSS when relevant events happened. Currently, NSS only cares about
7987 // interface changed to update clat interfaces accounting.
7988 final boolean interfacesChanged = oldLp == null
7989 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
7990 if (interfacesChanged) {
7991 notifyIfacesChangedForNetworkStats();
7992 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007993 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7994 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09007995 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007996 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007997
7998 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007999 }
8000
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09008001 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8002 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8003 }
8004
Hai Shalome58bdc62021-01-11 18:45:34 -08008005 /**
8006 * @param naData captive portal data from NetworkAgent
8007 * @param apiData captive portal data from capport API
8008 */
8009 @Nullable
8010 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8011 CaptivePortalData apiData) {
8012 if (naData == null || apiData == null) {
8013 return naData == null ? apiData : naData;
8014 }
8015 final CaptivePortalData.Builder captivePortalBuilder =
8016 new CaptivePortalData.Builder(naData);
8017
8018 if (apiData.isCaptive()) {
8019 captivePortalBuilder.setCaptive(true);
8020 }
8021 if (apiData.isSessionExtendable()) {
8022 captivePortalBuilder.setSessionExtendable(true);
8023 }
8024 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8025 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8026 // otherwise data would be inconsistent. Prefer the capport API info if present,
8027 // as it can generally be refreshed more often.
8028 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8029 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8030 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8031 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8032 // No source has time / bytes remaining information: surface the newest refresh time
8033 // for other fields
8034 captivePortalBuilder.setRefreshTime(
8035 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8036 }
8037
Hai Shalom7c6ab402021-02-04 19:34:06 -08008038 // Prioritize the user portal URL from the network agent if the source is authenticated.
8039 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8040 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8041 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8042 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008043 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008044 // Prioritize the venue information URL from the network agent if the source is
8045 // authenticated.
8046 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8047 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8048 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8049 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008050 }
8051 return captivePortalBuilder.build();
8052 }
8053
Suprabh Shukla619549f2023-04-26 18:47:36 -07008054 @VisibleForTesting
8055 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008056 // This needs to be kept in sync and backwards compatible with the decoding logic in
8057 // NetdEventListenerService, which is non-mainline code.
8058 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8059 }
8060
Suprabh Shukla63e59342023-04-25 23:15:43 -07008061 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8062 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8063 return true;
8064 }
8065 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8066 return true;
8067 }
8068 return false;
8069 }
8070
Suprabh Shukla1e312032023-01-24 03:36:37 -08008071 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008072 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008073 // marks on unsupported interfaces is harmless.
Suprabh Shukla63e59342023-04-25 23:15:43 -07008074 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008075 return;
8076 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008077
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008078 // Mask/mark of zero will not detect anything interesting.
8079 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskif310a142023-06-05 07:29:28 +00008080 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008081 return;
8082 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008083
Suprabh Shukla1e312032023-01-24 03:36:37 -08008084 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008085 try {
8086 if (add) {
Maciej Żenczykowskif310a142023-06-05 07:29:28 +00008087 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008088 } else {
Maciej Żenczykowskif310a142023-06-05 07:29:28 +00008089 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008090 }
8091 } catch (Exception e) {
8092 loge("Exception modifying wakeup packet monitoring: " + e);
8093 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008094 }
8095
Junyu Lai970963e2022-10-25 15:46:47 +08008096 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008097 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008098 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008099 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008100 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008101 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008102 for (final String iface : interfaceDiff.added) {
8103 try {
8104 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008105 mNetd.networkAddInterface(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008106 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008107 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008108 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008109 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008110 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008111 }
Paul Jensenbff73492014-04-28 10:33:11 -04008112 }
8113 }
Chalard Jean9589e722019-11-19 19:03:53 +09008114 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008115 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008116 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008117 wakeupModifyInterface(iface, nai, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008118 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008119 } catch (Exception e) {
8120 loge("Exception removing interface: " + e);
8121 }
8122 }
8123 }
8124
Tyler Weare4314862019-12-05 14:55:30 -08008125 // TODO: move to frameworks/libs/net.
8126 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
8127 final String nextHop;
8128
8129 switch (route.getType()) {
8130 case RouteInfo.RTN_UNICAST:
8131 if (route.hasGateway()) {
8132 nextHop = route.getGateway().getHostAddress();
8133 } else {
8134 nextHop = INetd.NEXTHOP_NONE;
8135 }
8136 break;
8137 case RouteInfo.RTN_UNREACHABLE:
8138 nextHop = INetd.NEXTHOP_UNREACHABLE;
8139 break;
8140 case RouteInfo.RTN_THROW:
8141 nextHop = INetd.NEXTHOP_THROW;
8142 break;
8143 default:
8144 nextHop = INetd.NEXTHOP_NONE;
8145 break;
8146 }
8147
8148 final RouteInfoParcel rip = new RouteInfoParcel();
8149 rip.ifName = route.getInterface();
8150 rip.destination = route.getDestination().toString();
8151 rip.nextHop = nextHop;
8152 rip.mtu = route.getMtu();
8153
8154 return rip;
8155 }
8156
Paul Jensene0fd4a82014-08-06 15:51:33 -04008157 /**
8158 * Have netd update routes from oldLp to newLp.
8159 * @return true if routes changed between oldLp and newLp
8160 */
Junyu Lai970963e2022-10-25 15:46:47 +08008161 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8162 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008163 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008164 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8165 new CompareOrUpdateResult<>(
8166 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008167 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008168 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008169
8170 // add routes before removing old in case it helps with continuous connectivity
8171
Chalard Jean9dd11612018-06-04 16:52:49 +09008172 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008173 for (RouteInfo route : routeDiff.added) {
8174 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008175 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008176 try {
Tyler Weare4314862019-12-05 14:55:30 -08008177 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008178 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008179 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008180 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008181 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008182 }
8183 }
8184 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008185 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008186 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008187 try {
Tyler Weare4314862019-12-05 14:55:30 -08008188 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008189 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008190 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008191 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008192 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008193 }
8194 }
8195
8196 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008197 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008198 try {
Tyler Weare4314862019-12-05 14:55:30 -08008199 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008200 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08008201 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008202 }
8203 }
Tyler Weare4314862019-12-05 14:55:30 -08008204
8205 for (RouteInfo route : routeDiff.updated) {
8206 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8207 try {
8208 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
8209 } catch (Exception e) {
8210 loge("Exception in networkUpdateRouteParcel: " + e);
8211 }
8212 }
8213 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8214 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008215 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008216
Junyu Lai970963e2022-10-25 15:46:47 +08008217 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8218 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008219 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8220 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008221 }
Erik Klineb9888902016-04-05 13:30:49 +09008222
Erik Kline31b4a9e2018-01-11 21:07:29 +09008223 if (DBG) {
8224 final Collection<InetAddress> dnses = newLp.getDnsServers();
8225 log("Setting DNS servers for network " + netId + " to " + dnses);
8226 }
Erik Klineb9888902016-04-05 13:30:49 +09008227 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008228 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008229 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008230 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008231 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008232 }
Erik Kline54e35c02017-04-07 15:29:29 +09008233 }
8234
Junyu Lai970963e2022-10-25 15:46:47 +08008235 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8236 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008237 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8238 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008239 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8240 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008241
8242 if (!wasFiltering && !needsFiltering) {
8243 // Nothing to do.
8244 return;
8245 }
8246
8247 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8248 // Nothing changed.
8249 return;
8250 }
8251
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008252 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008253 if (ranges == null || ranges.isEmpty()) {
8254 return;
8255 }
8256
Qingxi Libb8da982020-01-17 17:54:27 -08008257 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008258 // TODO: this create a window of opportunity for apps to receive traffic between the time
8259 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008260 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008261 // old rules are being removed.
8262 if (wasFiltering) {
8263 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8264 }
8265 if (needsFiltering) {
8266 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8267 }
8268 }
8269
Valentin Iftime9fa35092019-09-24 13:32:13 +02008270 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008271 if (mWolSupportedInterfaces == null) {
8272 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008273 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008274 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008275 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8276 }
8277
Luke Huangb913c812018-08-24 20:33:16 +08008278 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008279 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008280 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008281 }
8282 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008283 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008284 }
Luke Huangb913c812018-08-24 20:33:16 +08008285 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008286 }
8287
Chalard Jean62edfd82019-12-02 18:39:29 +09008288 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8289 @NonNull final NetworkCapabilities newNc) {
8290 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8291 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008292 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008293 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008294 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008295 } catch (RemoteException | ServiceSpecificException e) {
8296 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008297 }
8298 }
8299 }
8300
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008301 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008302 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008303 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008304 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008305 underlyingNetworks = underlyingNetworksOrDefault(
8306 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008307 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008308 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8309 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008310 // metered if any underlying is metered, or originally declared metered by the agent.
8311 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008312 boolean roaming = false; // roaming if any underlying is roaming
8313 boolean congested = false; // congested if any underlying is congested
8314 boolean suspended = true; // suspended if all underlying are suspended
8315
8316 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008317 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008318 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008319 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008320 for (Network underlyingNetwork : underlyingNetworks) {
8321 final NetworkAgentInfo underlying =
8322 getNetworkAgentInfoForNetwork(underlyingNetwork);
8323 if (underlying == null) continue;
8324
8325 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8326 hadUnderlyingNetworks = true;
8327 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008328 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008329 }
8330
8331 // Merge capabilities of this underlying network. For bandwidth, assume the
8332 // worst case.
8333 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8334 underlyingCaps.getLinkDownstreamBandwidthKbps());
8335 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8336 underlyingCaps.getLinkUpstreamBandwidthKbps());
8337 // If this underlying network is metered, the VPN is metered (it may cost money
8338 // to send packets on this network).
8339 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8340 // If this underlying network is roaming, the VPN is roaming (the billing structure
8341 // is different than the usual, local one).
8342 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8343 // If this underlying network is congested, the VPN is congested (the current
8344 // condition of the network affects the performance of this network).
8345 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8346 // If this network is not suspended, the VPN is not suspended (the VPN
8347 // is able to transfer some data).
8348 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008349 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008350 }
8351 }
8352 if (!hadUnderlyingNetworks) {
8353 // No idea what the underlying networks are; assume reasonable defaults
8354 metered = true;
8355 roaming = false;
8356 congested = false;
8357 suspended = false;
8358 }
8359
Chalard Jean1d420b32022-10-12 16:39:37 +09008360 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008361 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8362 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8363 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8364 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8365 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8366 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008367 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008368 }
8369
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008370 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008371 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8372 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8373 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008374 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008375 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008376 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008377 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008378 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8379 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008380 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008381 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008382 if (nai.everConnected()
8383 && !nai.isVPN()
8384 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008385 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008386 // does not cause any request (that is not a listen) currently matching that agent to
8387 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008388 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008389 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008390 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008391 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008392 }
8393
Paul Jensen53f08952015-06-16 14:27:36 -04008394 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008395 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008396 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008397 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008398 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008399 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008400 }
Chalard Jean254bd162022-08-25 13:04:51 +09008401 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008402 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008403 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008404 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008405 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008406 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008407 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008408 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008409 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008410 }
Chalard Jean254bd162022-08-25 13:04:51 +09008411 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008412 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8413 } else {
8414 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8415 }
lucasline117e2e2019-10-22 18:27:33 +08008416 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008417
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008418 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008419 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8420 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008421 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008422 }
8423
Lorenzo Colittibd079452021-07-02 11:47:57 +09008424 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008425 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008426 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008427 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008428 }
8429
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008430 return newNc;
8431 }
8432
Lorenzo Colitti44840702021-01-11 22:27:57 +09008433 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8434 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8435 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8436 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8437 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8438 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8439 if (prevSuspended != suspended) {
8440 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8441 // onResumed have been removed.
8442 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8443 : ConnectivityManager.CALLBACK_RESUMED);
8444 }
8445 if (prevSuspended != suspended || prevRoaming != roaming) {
8446 // updateNetworkInfo will mix in the suspended info from the capabilities and
8447 // take appropriate action for the network having possibly changed state.
8448 updateNetworkInfo(nai, nai.networkInfo);
8449 }
8450 }
8451
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008452 /**
8453 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8454 *
8455 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8456 * capabilities we manage and store in {@code nai}, such as validated status and captive
8457 * portal status)
8458 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8459 * potentially triggers rematches.
8460 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8461 * change.)
8462 *
8463 * @param oldScore score of the network before any of the changes that prompted us
8464 * to call this function.
8465 * @param nai the network having its capabilities updated.
8466 * @param nc the new network capabilities.
8467 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008468 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008469 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008470 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008471 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008472 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8473 if (null != differences) {
8474 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8475 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008476 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008477 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008478
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008479 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008480 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008481 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008482
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008483 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008484 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8485 // the change we're processing can't affect any requests, it can only affect the listens
8486 // on this network. We might have been called by rematchNetworkAndRequests when a
8487 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008488 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008489 } else {
8490 // If the requestable capabilities have changed or the score changed, we can't have been
8491 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008492 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008493 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008494 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008495 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008496
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008497 final boolean oldMetered = prevNc.isMetered();
8498 final boolean newMetered = newNc.isMetered();
8499 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008500
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008501 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008502 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8503 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008504 }
junyulaif2c67e42018-08-07 19:50:45 +08008505
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008506 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8507 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008508
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008509 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008510 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008511 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008512 }
8513
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008514 // This network might have been underlying another network. Propagate its capabilities.
8515 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008516
8517 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008518 mDnsManager.updateTransportsForNetwork(
8519 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008520 }
lucaslin53e8a262021-06-08 01:43:59 +08008521
8522 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008523 }
8524
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008525 /** Convenience method to update the capabilities for a given network. */
8526 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008527 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008528 }
8529
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008530 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008531 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008532 *
8533 * Ingress interface filtering enforces that all apps under the given network can only receive
8534 * packets from the network's interface (and loopback). This is important for VPNs because
8535 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8536 * non-VPN interfaces.
8537 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008538 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008539 * 1. the network is an app VPN (not legacy VPN)
8540 * 2. the VPN does not allow bypass
8541 * 3. the VPN is fully-routed
8542 * 4. the VPN interface is non-null
8543 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008544 * @see INetd#firewallAddUidInterfaceRules
8545 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008546 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008547 @Nullable
8548 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008549 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008550 if (nc == null || lp == null) return null;
8551 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008552 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008553 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008554 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008555 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008556 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008557 && !lp.hasExcludeRoute()) {
8558 return lp.getInterfaceName();
8559 }
8560 return null;
8561 }
8562
8563 /**
8564 * Returns whether we need to set interface filtering rule or not
8565 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008566 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008567 String isolationIface) {
8568 // Allow rules are always needed if VPN isolation is enabled.
8569 if (isolationIface != null) return true;
8570
8571 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8572 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8573 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
8574 return SdkLevel.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008575 }
8576
Chiachang Wang28afaff2020-12-10 22:24:47 +08008577 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8578 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8579 int index = 0;
8580 for (UidRange range : ranges) {
8581 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8582 index++;
8583 }
8584 return stableRanges;
8585 }
8586
Chalard Jeane6c95272022-01-25 21:04:21 +09008587 private static UidRangeParcel[] intsToUidRangeStableParcels(
8588 final @NonNull ArraySet<Integer> uids) {
8589 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8590 int index = 0;
8591 for (int uid : uids) {
8592 stableRanges[index] = new UidRangeParcel(uid, uid);
8593 index++;
8594 }
8595 return stableRanges;
8596 }
8597
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008598 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8599 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8600 for (int i = 0; i < ranges.length; i++) {
8601 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8602 }
8603 return stableRanges;
8604 }
8605
Motomu Utsumia20f7602023-03-16 17:04:21 +09008606 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
8607 Set<Integer> exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08008608 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8609 try {
Motomu Utsumia20f7602023-03-16 17:04:21 +09008610 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008611 } catch (Exception e) {
8612 loge("Exception in socket destroy: ", e);
8613 }
8614 }
8615 }
8616
paulhuaa0743d2021-05-26 21:56:03 +08008617 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumia20f7602023-03-16 17:04:21 +09008618 final Set<Integer> exemptUids = new ArraySet<>();
Ken Chen5e65a852020-12-24 12:59:10 +08008619 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8620 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8621 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumia20f7602023-03-16 17:04:21 +09008622 exemptUids.add(VPN_UID);
8623 exemptUids.add(nai.networkCapabilities.getOwnerUid());
Ken Chen5e65a852020-12-24 12:59:10 +08008624 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8625
Motomu Utsumi6345e462023-03-13 13:24:50 +09008626 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumia20f7602023-03-16 17:04:21 +09008627 maybeCloseSockets(nai, uidRanges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008628 try {
8629 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008630 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008631 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008632 } else {
paulhu0e79d952021-06-09 16:11:35 +08008633 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008634 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008635 }
8636 } catch (Exception e) {
8637 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8638 " on netId " + nai.network.netId + ". " + e);
8639 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09008640 // Close sockets that established connection while requesting netd.
Motomu Utsumia20f7602023-03-16 17:04:21 +09008641 maybeCloseSockets(nai, uidRanges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008642 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008643
lucaslin53e8a262021-06-08 01:43:59 +08008644 private boolean isProxySetOnAnyDefaultNetwork() {
8645 ensureRunningOnConnectivityServiceThread();
8646 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8647 final NetworkAgentInfo nai = nri.getSatisfier();
8648 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8649 return true;
8650 }
8651 }
8652 return false;
8653 }
8654
8655 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8656 NetworkCapabilities newNc) {
8657 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8658 // the proxy might be changed since the default network satisfied by the apps might also
8659 // changed.
8660 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8661 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008662 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8663 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008664 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008665 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8666 mProxyTracker.sendProxyBroadcast();
8667 }
8668 }
8669
Chalard Jeane6c95272022-01-25 21:04:21 +09008670 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8671 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008672 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8673 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008674 if (null == prevRanges) prevRanges = new ArraySet<>();
8675 if (null == newRanges) newRanges = new ArraySet<>();
8676 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8677
8678 prevRanges.removeAll(newRanges);
8679 newRanges.removeAll(prevRangesCopy);
8680
8681 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008682 // When updating the VPN uid routing rules, add the new range first then remove the old
8683 // range. If old range were removed first, there would be a window between the old
8684 // range being removed and the new range being added, during which UIDs contained
8685 // in both ranges are not subject to any VPN routing rules. Adding new range before
8686 // removing old range works because, unlike the filtering rules below, it's possible to
8687 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008688 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8689 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8690 // [1-5] & [1-2],[4-5] == [3]
8691 // Then we can do:
8692 // maybeCloseSockets([3])
8693 // mNetd.networkAddUidRanges([1-2],[4-5])
8694 // mNetd.networkRemoveUidRanges([1-5])
8695 // maybeCloseSockets([3])
8696 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8697 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008698 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008699 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008700 }
8701 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008702 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008703 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00008704 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
8705 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008706 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
8707 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008708 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008709 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008710 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8711 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8712 // were added first and then newRanges got removed later, there would be only one uid
8713 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8714 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8715 // Note that this is in contrast with the (more robust) update of VPN routing rules
8716 // above, where the addition of new ranges happens before the removal of old ranges.
8717 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8718 // to be removed will never overlap with the new range to be added.
8719 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008720 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
8721 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008722 }
8723 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008724 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008725 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008726 } catch (Exception e) {
8727 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008728 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008729 }
8730 }
8731
Chalard Jeande665262022-02-25 16:12:12 +09008732 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09008733 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8734 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09008735 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
8736 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09008737 if (prevEmpty && newEmpty) return;
8738
8739 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09008740 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008741 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09008742 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008743
8744 if (prevUids.equals(newUids)) return;
8745
8746 // This implementation is very simple and vastly faster for sets of Integers than
8747 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8748 // a key computed from the value and has storage for that.
8749 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8750 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8751 toRemove.removeAll(newUids);
8752 toAdd.removeAll(prevUids);
8753
8754 try {
8755 if (!toAdd.isEmpty()) {
8756 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8757 nai.network.netId,
8758 intsToUidRangeStableParcels(toAdd),
8759 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8760 }
8761 if (!toRemove.isEmpty()) {
8762 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8763 nai.network.netId,
8764 intsToUidRangeStableParcels(toRemove),
8765 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8766 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008767 } catch (ServiceSpecificException e) {
8768 // Has the interface disappeared since the network was built ?
8769 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008770 } catch (RemoteException e) {
8771 // Netd died. This usually causes a runtime restart anyway.
8772 }
8773 }
8774
Junyu Lai2ed7d412022-10-07 16:52:21 +08008775 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
8776 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008777 ensureRunningOnConnectivityServiceThread();
8778
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008779 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008780 // Ignore updates for disconnected networks
8781 return;
8782 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008783 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008784 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09008785 + "; created=" + nai.getCreatedTime()
8786 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00008787 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008788 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8789 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008790 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008791 }
8792
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008793 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8794 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008795 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008796 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008797 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008798 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8799 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8800 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008801 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8802 // need to be sent as a separate extra.
8803 final NetworkRequest req = nri.isMultilayerRequest()
8804 ? nri.getActiveRequest()
8805 // Non-multilayer listen requests do not have an active request
8806 : nri.mRequests.get(0);
8807 if (req == null) {
8808 Log.wtf(TAG, "No request in NRI " + nri);
8809 }
8810 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008811 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008812 sendIntent(nri.mPendingIntent, intent);
8813 }
8814 // else not handled
8815 }
8816
Michael Groover73f69482023-01-27 11:01:25 -06008817 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
8818 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008819 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8820 mPendingIntentWakeLock.acquire();
8821 try {
8822 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00008823 final BroadcastOptions options = BroadcastOptions.makeBasic();
8824 if (SdkLevel.isAtLeastT()) {
8825 // Explicitly disallow the receiver from starting activities, to prevent apps from
8826 // utilizing the PendingIntent as a backdoor to do this.
8827 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
8828 }
8829 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
8830 null /* requiredPermission */,
8831 SdkLevel.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008832 } catch (PendingIntent.CanceledException e) {
8833 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8834 mPendingIntentWakeLock.release();
8835 releasePendingNetworkRequest(pendingIntent);
8836 }
8837 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8838 }
8839
8840 @Override
8841 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8842 String resultData, Bundle resultExtras) {
8843 if (DBG) log("Finished sending " + pendingIntent);
8844 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008845 // Release with a delay so the receiving client has an opportunity to put in its
8846 // own request.
8847 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008848 }
8849
Chalard Jean46bfbf02022-02-02 00:56:25 +09008850 // networkAgent is only allowed to be null if notificationType is
8851 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
8852 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08008853 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09008854 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08008855 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008856 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008857 // Default request has no msgr. Also prevents callbacks from being invoked for
8858 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8859 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8860 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008861 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008862 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008863 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008864 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008865 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008866 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008867 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008868 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8869 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008870 }
Roshan Pius951c0032020-12-22 15:10:42 -08008871 final boolean includeLocationSensitiveInfo =
8872 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008873 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008874 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008875 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08008876 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09008877 networkCapabilitiesRestrictedForCallerPermissions(
8878 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
8879 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008880 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09008881 nri.mCallingAttributionTag);
8882 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008883 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8884 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008885 // For this notification, arg1 contains the blocked status.
8886 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008887 break;
8888 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008889 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008890 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008891 break;
8892 }
8893 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008894 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008895 final NetworkCapabilities netCap =
8896 networkCapabilitiesRestrictedForCallerPermissions(
8897 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8898 putParcelable(
8899 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008900 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008901 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008902 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008903 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008904 break;
8905 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008906 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008907 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8908 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008909 break;
8910 }
junyulaif2c67e42018-08-07 19:50:45 +08008911 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008912 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008913 msg.arg1 = arg1;
8914 break;
8915 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008916 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008917 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008918 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008919 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008920 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008921 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008922 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008923 }
James Mattis45d81842021-01-10 14:24:24 -08008924 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008925 } catch (RemoteException e) {
8926 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008927 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008928 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008929 }
8930
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008931 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8932 bundle.putParcelable(t.getClass().getSimpleName(), t);
8933 }
8934
Chalard Jean0702f982021-09-16 21:50:07 +09008935 /**
8936 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8937 *
8938 * When a request should be assigned to a new network, it is normally lingered to give
8939 * time for apps to gracefully migrate their connections. When both networks are on the same
8940 * radio, but that radio can't do time-sharing efficiently, this may end up being
8941 * counter-productive because any traffic on the old network may drastically reduce the
8942 * performance of the new network.
8943 * The stack supports a configuration to let modem vendors state that their radio can't
8944 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8945 * from one cell network to another can't be done gracefully.
8946 *
8947 * @param oldNai the old network serving the request
8948 * @param newNai the new network serving the request
8949 * @return whether the switch can be graceful
8950 */
8951 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8952 @NonNull final NetworkAgentInfo newSatisfier) {
8953 if (mCellularRadioTimesharingCapable) return true;
8954 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8955 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8956 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8957 }
8958
Paul Jensenaf94b982014-09-30 15:37:41 -04008959 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008960 if (nai.numRequestNetworkRequests() != 0) {
8961 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8962 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008963 // Ignore listening and track default requests.
8964 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008965 loge("Dead network still had at least " + nr);
8966 break;
8967 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008968 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008969 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008970 }
8971
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008972 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8973 if (oldNetwork == null) {
8974 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8975 return;
8976 }
Chalard Jean49707572019-12-10 21:07:02 +09008977 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008978
8979 // If we get here it means that the last linger timeout for this network expired. So there
8980 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008981 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008982
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008983 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008984 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008985 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008986 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008987 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008988 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008989 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008990 }
8991
James Mattise3ef1912020-12-20 11:09:58 -08008992 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8993 boolean isDefaultChanged = false;
8994 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8995 final NetworkReassignment.RequestReassignment reassignment =
8996 changes.getReassignment(defaultRequestInfo);
8997 if (null == reassignment) {
8998 continue;
8999 }
9000 // reassignment only contains those instances where the satisfying network changed.
9001 isDefaultChanged = true;
9002 // Notify system services of the new default.
9003 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9004 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009005
James Mattise3ef1912020-12-20 11:09:58 -08009006 if (isDefaultChanged) {
9007 // Hold a wakelock for a short time to help apps in migrating to a new default.
9008 scheduleReleaseNetworkTransitionWakelock();
9009 }
9010 }
9011
9012 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9013 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9014 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9015 if (DBG) {
9016 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9017 }
Chalard Jean8e382112019-12-03 20:45:30 +09009018
James Mattisd31bdfa2020-12-23 16:37:26 -08009019 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9020 if (newDefaultNetwork != null) {
9021 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009022 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009023
James Mattisd31bdfa2020-12-23 16:37:26 -08009024 // Set an app level managed default and return since further processing only applies to the
9025 // default network.
9026 if (mDefaultRequest != nri) {
9027 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9028 return;
9029 }
9030
9031 makeDefaultNetwork(newDefaultNetwork);
9032
James Mattise3ef1912020-12-20 11:09:58 -08009033 if (oldDefaultNetwork != null) {
9034 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9035 }
9036 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009037 handleApplyDefaultProxy(null != newDefaultNetwork
9038 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
9039 updateTcpBufferSizes(null != newDefaultNetwork
9040 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009041 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009042 }
9043
James Mattisd31bdfa2020-12-23 16:37:26 -08009044 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9045 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9046 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9047 try {
9048 if (VDBG) {
9049 log("Setting default network for " + nri
9050 + " using UIDs " + nri.getUids()
9051 + " with old network " + (oldDefaultNetwork != null
9052 ? oldDefaultNetwork.network().getNetId() : "null")
9053 + " and new network " + (newDefaultNetwork != null
9054 ? newDefaultNetwork.network().getNetId() : "null"));
9055 }
9056 if (nri.getUids().isEmpty()) {
9057 throw new IllegalStateException("makeDefaultForApps called without specifying"
9058 + " any applications to set as the default." + nri);
9059 }
9060 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009061 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009062 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009063 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009064 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009065 }
9066 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009067 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009068 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009069 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009070 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009071 }
9072 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009073 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009074 }
9075 }
9076
Junyu Lai35665cc2022-12-19 17:37:48 +08009077 /**
9078 * Collect restricted uid ranges for the given network and UserHandle, these uids
9079 * are not restricted for matched enterprise networks but being restricted for non-matched
9080 * enterprise networks and non-enterprise networks.
9081 */
9082 @NonNull
9083 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9084 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9085 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9086 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9087 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9088
9089 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9090 // The NC is built from a `ProfileNetworkPreference` which has only one
9091 // enterprise ID, so it's guaranteed to have exactly one.
9092 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9093 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9094 continue;
9095 }
9096 }
9097
9098 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9099 pref.capabilities.getUidRanges())) {
9100 throw new IllegalArgumentException(
9101 "Overlapping uid range in preference: " + pref);
9102 }
9103 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9104 }
9105 return restrictedUidRanges;
9106 }
9107
9108 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009109 // Netd command is not implemented before U.
9110 if (!SdkLevel.isAtLeastU()) return;
9111
Junyu Lai35665cc2022-12-19 17:37:48 +08009112 ensureRunningOnConnectivityServiceThread();
9113 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9114 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9115 .getUserHandles(true /* excludeDying */);
9116 if (users.isEmpty()) {
9117 throw new IllegalStateException("No user is available");
9118 }
9119
9120 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9121 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9122 for (final UserHandle user : users) {
9123 final ArraySet<UidRange> restrictedUidRanges =
9124 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9125 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9126 UidRange.createForUser(user), restrictedUidRanges));
9127 }
9128
9129 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9130 configs.add(new NativeUidRangeConfig(
9131 nai.network.netId, rangesParcel, 0 /* subPriority */));
9132 }
9133
9134 // The netd API replaces the previous configs with the current configs.
9135 // Thus, for network disconnection or preference removal, no need to
9136 // unset previous config. Instead, collecting all currently needed
9137 // configs and issue to netd.
9138 try {
9139 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9140 } catch (ServiceSpecificException e) {
9141 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009142 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009143 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009144 // Netd died. This will cause a runtime restart anyway.
9145 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009146 }
9147 }
9148
James Mattisd31bdfa2020-12-23 16:37:26 -08009149 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9150 try {
9151 if (null != newDefaultNetwork) {
9152 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9153 } else {
9154 mNetd.networkClearDefault();
9155 }
9156 } catch (RemoteException | ServiceSpecificException e) {
9157 loge("Exception setting default network :" + e);
9158 }
9159 }
9160
Chalard Jean05cbe972019-12-09 11:50:38 +09009161 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009162 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009163 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009164 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009165 processNewlySatisfiedListenRequests(nai);
9166 }
9167
9168 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009169 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9170 if (nri.isMultilayerRequest()) {
9171 continue;
9172 }
9173 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009174 if (!nr.isListen()) continue;
9175 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009176 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009177 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9178 }
9179 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009180 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009181
Chalard Jeancd397a22019-11-22 22:33:33 +09009182 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009183 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9184 if (nri.isMultilayerRequest()) {
9185 continue;
9186 }
9187 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009188 if (!nr.isListen()) continue;
9189 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9190 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009191 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009192 }
9193 }
9194 }
9195
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009196 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009197 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009198 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009199 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009200 @Nullable public final NetworkRequest mOldNetworkRequest;
9201 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009202 @Nullable public final NetworkAgentInfo mOldNetwork;
9203 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009204 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009205 @Nullable final NetworkRequest oldNetworkRequest,
9206 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009207 @Nullable final NetworkAgentInfo oldNetwork,
9208 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009209 mNetworkRequestInfo = networkRequestInfo;
9210 mOldNetworkRequest = oldNetworkRequest;
9211 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009212 mOldNetwork = oldNetwork;
9213 mNewNetwork = newNetwork;
9214 }
Chalard Jean49707572019-12-10 21:07:02 +09009215
9216 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009217 final NetworkRequest requestToShow = null != mNewNetworkRequest
9218 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9219 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009220 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9221 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009222 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009223 }
9224
Chalard Jean46a62372019-12-10 21:25:24 +09009225 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009226
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009227 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009228 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009229 }
9230
9231 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009232 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009233 // The code is never supposed to add two reassignments of the same request. Make
9234 // sure this stays true, but without imposing this expensive check on all
9235 // reassignments on all user devices.
9236 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009237 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009238 throw new IllegalStateException("Trying to reassign ["
9239 + reassignment + "] but already have ["
9240 + existing + "]");
9241 }
9242 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009243 }
Chalard Jean46a62372019-12-10 21:25:24 +09009244 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009245 }
9246
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009247 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009248 // the passed request.
9249 @Nullable
9250 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009251 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009252 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009253 }
9254 return null;
9255 }
Chalard Jean49707572019-12-10 21:07:02 +09009256
9257 public String toString() {
9258 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9259 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009260 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009261 for (final RequestReassignment rr : getRequestReassignments()) {
9262 sj.add(rr.toString());
9263 }
9264 return sj.toString();
9265 }
9266
9267 public String debugString() {
9268 final StringBuilder sb = new StringBuilder();
9269 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009270 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009271 for (final RequestReassignment rr : getRequestReassignments()) {
9272 sb.append("\n ").append(rr);
9273 }
9274 return sb.append("\n").toString();
9275 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009276 }
9277
Chalard Jean24344d72019-12-04 13:32:31 +09009278 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009279 @Nullable final NetworkRequest previousRequest,
9280 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009281 @Nullable final NetworkAgentInfo previousSatisfier,
9282 @Nullable final NetworkAgentInfo newSatisfier,
9283 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009284 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009285 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009286 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009287 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009288 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09009289 }
James Mattisa076c532020-12-02 14:12:41 -08009290 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009291 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009292 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009293 // If this network switch can't be supported gracefully, the request is not
9294 // lingered. This allows letting go of the network sooner to reclaim some
9295 // performance on the new network, since the radio can't do both at the same
9296 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009297 //
9298 // Also don't linger the request if the old network has been destroyed.
9299 // A destroyed network does not provide actual network connectivity, so
9300 // lingering it is not useful. In particular this ensures that a destroyed
9301 // network is outscored by its replacement,
9302 // then it is torn down immediately instead of being lingered, and any apps that
9303 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009304 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9305 }
Chalard Jean24344d72019-12-04 13:32:31 +09009306 } else {
9307 if (VDBG || DDBG) log(" accepting network in place of null");
9308 }
junyulai0ac374f2020-12-14 18:41:52 +08009309
9310 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9311 // and immediately satisfies a request then remove the timer. This will happen for
9312 // all networks except in the case of an underlying network for a VCN.
9313 if (newSatisfier.isNascent()) {
9314 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009315 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009316 }
9317
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009318 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009319 newSatisfier.unlingerRequest(newRequest.requestId);
9320 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009321 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009322 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009323 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009324 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009325 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009326 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009327 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009328 }
James Mattisa076c532020-12-02 14:12:41 -08009329 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009330 }
James Mattisa076c532020-12-02 14:12:41 -08009331 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009332 }
9333
James Mattisa076c532020-12-02 14:12:41 -08009334 /**
9335 * This function is triggered when something can affect what network should satisfy what
9336 * request, and it computes the network reassignment from the passed collection of requests to
9337 * network match to the one that the system should now have. That data is encoded in an
9338 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9339 * satisfier.
9340 *
9341 * After the reassignment is computed, it is applied to the state objects.
9342 *
9343 * @param networkRequests the nri objects to evaluate for possible network reassignment
9344 * @return NetworkReassignment listing of proposed network assignment changes
9345 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009346 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009347 private NetworkReassignment computeNetworkReassignment(
9348 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009349 final NetworkReassignment changes = new NetworkReassignment();
9350
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009351 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009352 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009353 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009354 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009355 }
Chalard Jean857a1712019-12-10 21:08:07 +09009356
James Mattisa076c532020-12-02 14:12:41 -08009357 for (final NetworkRequestInfo nri : networkRequests) {
9358 // Non-multilayer listen requests can be ignored.
9359 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9360 continue;
9361 }
9362 NetworkAgentInfo bestNetwork = null;
9363 NetworkRequest bestRequest = null;
9364 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009365 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009366 // Stop evaluating as the highest possible priority request is satisfied.
9367 if (null != bestNetwork) {
9368 bestRequest = req;
9369 break;
9370 }
9371 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009372 if (null == bestNetwork && isDefaultBlocked(nri)) {
9373 // Remove default networking if disallowed for managed default requests.
9374 bestNetwork = mNoServiceNetwork;
9375 }
9376 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009377 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009378 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009379 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009380 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009381 }
9382 return changes;
9383 }
9384
James Mattisa076c532020-12-02 14:12:41 -08009385 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9386 return new HashSet<>(mNetworkRequests.values());
9387 }
9388
Paul Jensenc88b39b2015-06-16 14:27:36 -04009389 /**
James Mattisa076c532020-12-02 14:12:41 -08009390 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009391 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009392 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009393 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009394 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9395 }
9396
9397 /**
9398 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9399 * being disconnected.
9400 */
9401 private void rematchNetworksAndRequests(
9402 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9403 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009404 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009405 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009406 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009407 final long computed = SystemClock.elapsedRealtime();
9408 applyNetworkReassignment(changes, start);
9409 final long applied = SystemClock.elapsedRealtime();
9410 issueNetworkNeeds();
9411 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009412 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009413 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9414 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009415 log(changes.debugString());
9416 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009417 // Shorter form, only one line of log
9418 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9419 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009420 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009421 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009422
Chalard Jeand7f762d2019-12-10 19:01:29 +09009423 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009424 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009425 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009426
9427 // Since most of the time there are only 0 or 1 background networks, it would probably
9428 // be more efficient to just use an ArrayList here. TODO : measure performance
9429 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9430 for (final NetworkAgentInfo nai : nais) {
9431 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9432 }
9433
Chalard Jeand7f762d2019-12-10 19:01:29 +09009434 // First, update the lists of satisfied requests in the network agents. This is necessary
9435 // because some code later depends on this state to be correct, most prominently computing
9436 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009437 for (final NetworkReassignment.RequestReassignment event :
9438 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009439 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9440 event.mOldNetworkRequest, event.mNewNetworkRequest,
9441 event.mOldNetwork, event.mNewNetwork,
9442 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009443 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009444
James Mattise3ef1912020-12-20 11:09:58 -08009445 // Process default network changes if applicable.
9446 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009447
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009448 // Notify requested networks are available after the default net is switched, but
9449 // before LegacyTypeTracker sends legacy broadcasts
9450 for (final NetworkReassignment.RequestReassignment event :
9451 changes.getRequestReassignments()) {
9452 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009453 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009454 } else {
James Mattisa076c532020-12-02 14:12:41 -08009455 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009456 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009457 }
9458 }
9459
junyulai0ac374f2020-12-14 18:41:52 +08009460 // Update the inactivity state before processing listen callbacks, because the background
9461 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009462 // just yet though, because they have to be sent after the listens are processed to keep
9463 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009464 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009465 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009466 // Rematching may have altered the inactivity state of some networks, so update all
9467 // inactivity timers. updateInactivityState reads the state from the network agent
9468 // and does nothing if the state has not changed : the source of truth is controlled
9469 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9470 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009471 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009472 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009473 }
9474 }
9475
Chalard Jeanb10ab412019-12-11 14:12:30 +09009476 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009477 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009478 // Process listen requests and update capabilities if the background state has
9479 // changed for this network. For consistency with previous behavior, send onLost
9480 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009481 processNewlyLostListenRequests(nai);
9482 if (oldBackground != nai.isBackgroundNetwork()) {
9483 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009484 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009485 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009486 }
9487
junyulai0ac374f2020-12-14 18:41:52 +08009488 for (final NetworkAgentInfo nai : inactiveNetworks) {
9489 // For nascent networks, if connecting with no foreground request, skip broadcasting
9490 // LOSING for backward compatibility. This is typical when mobile data connected while
9491 // wifi connected with mobile data always-on enabled.
9492 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009493 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009494 }
9495
James Mattise3ef1912020-12-20 11:09:58 -08009496 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009497
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009498 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009499 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009500 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009501 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009502 // This network has active linger timers and no requests, but is not
9503 // lingering. Linger it.
9504 //
9505 // One way (the only way?) this can happen if this network is unvalidated
9506 // and became unneeded due to another network improving its score to the
9507 // point where this network will no longer be able to satisfy any requests
9508 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009509 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009510 notifyNetworkLosing(nai, now);
9511 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009512 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009513 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009514 teardownUnneededNetwork(nai);
9515 }
9516 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009517 }
9518 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009519
Chalard Jean62edfd82019-12-02 18:39:29 +09009520 /**
9521 * Apply a change in background state resulting from rematching networks with requests.
9522 *
9523 * During rematch, a network may change background states by starting to satisfy or stopping
9524 * to satisfy a foreground request. Listens don't count for this. When a network changes
9525 * background states, its capabilities need to be updated and callbacks fired for the
9526 * capability change.
9527 *
9528 * @param nai The network that changed background states
9529 */
9530 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
9531 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
9532 if (Objects.equals(nai.networkCapabilities, newNc)) return;
9533 updateNetworkPermissions(nai, newNc);
9534 nai.getAndSetNetworkCapabilities(newNc);
9535 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
9536 }
9537
Chalard Jeanf0344532019-11-19 19:23:38 +09009538 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08009539 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009540 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09009541 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
9542 changes.getReassignment(mDefaultRequest);
9543 final NetworkAgentInfo oldDefaultNetwork =
9544 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
9545 final NetworkAgentInfo newDefaultNetwork =
9546 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08009547
Chalard Jean5b409c72021-02-04 13:12:59 +09009548 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009549 // Maintain the illusion : since the legacy API only understands one network at a time,
9550 // if the default network changed, apps should see a disconnected broadcast for the
9551 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009552 if (oldDefaultNetwork != null) {
9553 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9554 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009555 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009556 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009557 // The new default network can be newly null if and only if the old default
9558 // network doesn't satisfy the default request any more because it lost a
9559 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009560 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009561 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009562 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009563 }
9564 }
9565
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009566 // Now that all the callbacks have been sent, send the legacy network broadcasts
9567 // as needed. This is necessary so that legacy requests correctly bind dns
9568 // requests to this network. The legacy users are listening for this broadcast
9569 // and will generally do a dns request so they can ensureRouteToHost and if
9570 // they do that before the callbacks happen they'll use the default network.
9571 //
9572 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
9573 // callbacks, but if apps can receive the broadcast before the callback, they still might
9574 // have an inconsistent view of networking.
9575 //
9576 // This *does* introduce a race where if the user uses the new api
9577 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
9578 // they may get old info. Reverse this after the old startUsing api is removed.
9579 // This is on top of the multiple intent sequencing referenced in the todo above.
9580 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09009581 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009582 addNetworkToLegacyTypeTracker(nai);
9583 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08009584 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009585 }
9586
Chalard Jean0354d8c2021-01-12 10:58:56 +09009587 private void issueNetworkNeeds() {
9588 ensureRunningOnConnectivityServiceThread();
9589 for (final NetworkOfferInfo noi : mNetworkOffers) {
9590 issueNetworkNeeds(noi);
9591 }
9592 }
9593
9594 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
9595 ensureRunningOnConnectivityServiceThread();
9596 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9597 informOffer(nri, noi.offer, mNetworkRanker);
9598 }
9599 }
9600
9601 /**
9602 * Inform a NetworkOffer about any new situation of a request.
9603 *
9604 * This function handles updates to offers. A number of events may happen that require
9605 * updating the registrant for this offer about the situation :
9606 * • The offer itself was updated. This may lead the offer to no longer being able
9607 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
9608 * or conversely being strengthened enough to beat the satisfier (and therefore
9609 * start being needed)
9610 * • The network satisfying a request changed (including cases where the request
9611 * starts or stops being satisfied). The new network may be a stronger or weaker
9612 * match than the old one, possibly affecting whether the offer is needed.
9613 * • The network satisfying a request updated their score. This may lead the offer
9614 * to no longer be able to beat it if the current satisfier got better, or
9615 * conversely start being a good choice if the current satisfier got weaker.
9616 *
9617 * @param nri The request
9618 * @param offer The offer. This may be an updated offer.
9619 */
9620 private static void informOffer(@NonNull NetworkRequestInfo nri,
9621 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9622 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9623 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009624
9625 // Multi-layer requests have a currently active request, the one being satisfied.
9626 // Since the system will try to bring up a better network than is currently satisfying
9627 // the request, NetworkProviders need to be told the offers matching the requests *above*
9628 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9629 // not needed, and the offer is needed for the active request iff the offer can beat
9630 // the satisfier.
9631 // For non-multilayer requests, the logic above gracefully degenerates to only the
9632 // last case.
9633 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9634 // providers that the offer is needed for this request, until the active request is found.
9635 // In a second phase, deal with the currently active request. In a third phase, inform
9636 // the providers that offer is unneeded for the remaining requests.
9637
9638 // First phase : inform providers of all requests above the active request.
9639 int i;
9640 for (i = 0; nri.mRequests.size() > i; ++i) {
9641 final NetworkRequest request = nri.mRequests.get(i);
9642 if (activeRequest == request) break; // Found the active request : go to phase 2
9643 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9644 // Since this request is higher-priority than the one currently satisfied, if the
9645 // offer can satisfy it, the provider should try and bring up the network for sure ;
9646 // no need to even ask the ranker – an offer that can satisfy is always better than
9647 // no network. Hence tell the provider so unless it already knew.
9648 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9649 offer.onNetworkNeeded(request);
9650 }
9651 }
9652
9653 // Second phase : deal with the active request (if any)
9654 if (null != activeRequest && activeRequest.isRequest()) {
9655 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009656 // If an offer can satisfy the request, it is considered needed if it is currently
9657 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009658 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009659 && satisfier.factorySerialNumber == offer.providerId
9660 && activeRequest.canBeSatisfiedBy(offer.caps);
9661 final boolean newNeeded = currentlyServing
9662 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009663 if (newNeeded != oldNeeded) {
9664 if (newNeeded) {
9665 offer.onNetworkNeeded(activeRequest);
9666 } else {
9667 // The offer used to be able to beat the satisfier. Now it can't.
9668 offer.onNetworkUnneeded(activeRequest);
9669 }
9670 }
9671 }
9672
9673 // Third phase : inform the providers that the offer isn't needed for any request
9674 // below the active one.
9675 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
9676 final NetworkRequest request = nri.mRequests.get(i);
9677 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9678 // Since this request is lower-priority than the one currently satisfied, if the
9679 // offer can satisfy it, the provider should not try and bring up the network.
9680 // Hence tell the provider so unless it already knew.
9681 if (offer.neededFor(request)) {
9682 offer.onNetworkUnneeded(request);
9683 }
9684 }
9685 }
9686
Chalard Jean61c79252019-11-07 23:07:32 +09009687 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
9688 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9689 NetworkRequest nr = nai.requestAt(i);
9690 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
9691 // legacy type tracker filters out repeat adds
9692 mLegacyTypeTracker.add(nr.legacyType, nai);
9693 }
9694 }
9695
9696 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09009697 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09009698 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
9699 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
9700 if (nai.isVPN()) {
9701 mLegacyTypeTracker.add(TYPE_VPN, nai);
9702 }
9703 }
9704
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009705 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04009706 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +09009707 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09009708 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04009709 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09009710 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009711
Chalard Jean254bd162022-08-25 13:04:51 +09009712 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009713 // Don't repeat publish.
9714 if (newInetCondition == mDefaultInetConditionPublished) return;
9715
9716 mDefaultInetConditionPublished = newInetCondition;
9717 sendInetConditionBroadcast(nai.networkInfo);
9718 }
9719
Chalard Jeand61375d2020-01-14 22:46:36 +09009720 @NonNull
9721 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
9722 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009723 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09009724 final boolean suspended =
9725 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9726 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
9727 // Only override the state with SUSPENDED if the network is currently in CONNECTED
9728 // state. This is because the network could have been suspended before connecting,
9729 // or it could be disconnecting while being suspended, and in both these cases
9730 // the state should not be overridden. Note that the only detailed state that
9731 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
9732 // worry about multiple different substates of CONNECTED.
9733 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
9734 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009735 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
9736 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
9737 // network agent is created, then goes to suspended, then goes out of suspended without
9738 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +09009739 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009740 ? NetworkInfo.DetailedState.CONNECTED
9741 : NetworkInfo.DetailedState.CONNECTING,
9742 info.getReason(),
9743 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09009744 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009745 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09009746 return newInfo;
9747 }
9748
9749 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
9750 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
9751
Erik Kline99f301b2017-02-15 19:59:17 +09009752 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009753 NetworkInfo oldInfo = null;
9754 synchronized (networkAgent) {
9755 oldInfo = networkAgent.networkInfo;
9756 networkAgent.networkInfo = newInfo;
9757 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009758
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009759 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009760 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
9761 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009762 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009763
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09009764 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009765 // A network that has just connected has zero requests and is thus a foreground network.
9766 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
9767
Luke Huangfdd11f82019-04-09 18:41:49 +08009768 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09009769
9770 networkAgent.setCreated();
9771
9772 // If the network is created immediately on register, then apply the LinkProperties now.
9773 // Otherwise, this is done further down when the network goes into connected state.
9774 // Applying the LinkProperties means that the network is ready to carry traffic -
9775 // interfaces and routing rules have been added, DNS servers programmed, etc.
9776 // For VPNs, this must be done before the capabilities are updated, because as soon as
9777 // that happens, UIDs are routed to the network.
9778 if (shouldCreateNetworksImmediately()) {
9779 applyInitialLinkProperties(networkAgent);
9780 }
9781
9782 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
9783 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +09009784 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009785 // Initialize the network's capabilities to their starting values according to the
9786 // underlying networks. This ensures that the capabilities are correct before
9787 // anything happens to the network.
9788 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009789 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009790 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +09009791 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +08009792 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009793 }
9794
Chalard Jean254bd162022-08-25 13:04:51 +09009795 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
9796 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009797
lucaslin45e639b2019-04-03 17:09:28 +08009798 // NetworkCapabilities need to be set before sending the private DNS config to
9799 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009800 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9801
Erik Kline9a62f012018-03-21 07:18:33 -07009802 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09009803 if (!shouldCreateNetworksImmediately()) {
9804 applyInitialLinkProperties(networkAgent);
9805 } else {
9806 // The network was created when the agent registered, and the LinkProperties are
9807 // already up-to-date. However, updateLinkProperties also makes some changes only
9808 // when the network connects. Apply those changes here. On T and below these are
9809 // handled by the applyInitialLinkProperties call just above.
9810 // TODO: stop relying on updateLinkProperties(..., null) to do this.
9811 // If something depends on both LinkProperties and connected state, it should be in
9812 // this method as well.
9813 networkAgent.clatd.update();
9814 updateProxy(networkAgent.linkProperties, null);
9815 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009816
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +01009817 // If a rate limit has been configured and is applicable to this network (network
9818 // provides internet connectivity), apply it. The tc police filter cannot be attached
9819 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
9820 // updateInterfaces -> INetd#networkAddInterface.
9821 // Note: in case of a system server crash, the NetworkController constructor in netd
9822 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
9823 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9824 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9825 mIngressRateLimit);
9826 }
9827
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009828 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9829 // command must be sent after updating LinkProperties to maximize chances of
9830 // NetworkMonitor seeing the correct LinkProperties when starting.
9831 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009832 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009833 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009834 }
Chalard Jeand4900722022-02-06 12:25:38 +09009835 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9836 params.networkAgentConfig = networkAgent.networkAgentConfig;
9837 params.networkCapabilities = networkAgent.networkCapabilities;
9838 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9839 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +09009840 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
9841 // newer callback even before T. However getInterfaceVersion is a synchronized binder
9842 // call that would cause a Log.wtf to be emitted from the system_server process, and
9843 // in the absence of a satisfactory, scalable solution which follows an easy/standard
9844 // process to check the interface version, just use an SDK check. NetworkStack will
9845 // always be new enough when running on T+.
9846 if (SdkLevel.isAtLeastT()) {
9847 networkAgent.networkMonitor().notifyNetworkConnected(params);
9848 } else {
9849 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
9850 params.networkCapabilities);
9851 }
Chalard Jeane63c42f2022-09-16 19:31:45 +09009852 final long delay = activelyPreferBadWifi()
9853 ? ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS
9854 : DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
9855 scheduleEvaluationTimeout(networkAgent.network, delay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009856
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009857 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9858 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9859 // capabilities, so it only needs to be done once on initial connect, not every time the
9860 // network's capabilities change. Note that we do this before rematching the network,
9861 // so we could decide to tear it down immediately afterwards. That's fine though - on
9862 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9863 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009864 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009865
junyulai0ac374f2020-12-14 18:41:52 +08009866 // Before first rematching networks, put an inactivity timer without any request, this
9867 // allows {@code updateInactivityState} to update the state accordingly and prevent
9868 // tearing down for any {@code unneeded} evaluation in this period.
9869 // Note that the timer will not be rescheduled since the expiry time is
9870 // fixed after connection regardless of the network satisfying other requests or not.
9871 // But it will be removed as soon as the network satisfies a request for the first time.
9872 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9873 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009874 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009875
Paul Jensen05e85ee2014-09-11 11:00:39 -04009876 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009877 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009878
9879 // This has to happen after matching the requests, because callbacks are just requests.
9880 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009881 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009882 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009883 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009884 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009885 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009886 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009887 if (networkAgent.isVPN()) {
9888 // As the active or bound network changes for apps, broadcast the default proxy, as
9889 // apps may need to update their proxy data. This is called after disconnecting from
9890 // VPN to make sure we do not broadcast the old proxy data.
9891 // TODO(b/122649188): send the broadcast only to VPN users.
9892 mProxyTracker.sendProxyBroadcast();
9893 }
Chalard Jean254bd162022-08-25 13:04:51 +09009894 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
9895 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009896 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009897 }
9898 }
9899
Chalard Jean28018572020-12-21 18:36:52 +09009900 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009901 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9902 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009903 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009904 }
9905
Erik Kline99f301b2017-02-15 19:59:17 +09009906 // Notify only this one new request of the current state. Transfer all the
9907 // current state by calling NetworkCapabilities and LinkProperties callbacks
9908 // so that callers can be guaranteed to have as close to atomicity in state
9909 // transfer as can be supported by this current API.
9910 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009911 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009912 if (nri.mPendingIntent != null) {
9913 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9914 // Attempt no subsequent state pushes where intents are involved.
9915 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009916 }
Erik Kline99f301b2017-02-15 19:59:17 +09009917
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009918 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009919 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009920 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9921 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9922 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009923 }
9924
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009925 // Notify the requests on this NAI that the network is now lingered.
9926 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009927 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009928 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9929 }
9930
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009931 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9932 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9933 return vpnBlocked
9934 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9935 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9936 }
9937
9938 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9939 if (blockedReasons == BLOCKED_REASON_NONE) {
9940 mUidBlockedReasons.delete(uid);
9941 } else {
9942 mUidBlockedReasons.put(uid, blockedReasons);
9943 }
9944 }
9945
junyulaif2c67e42018-08-07 19:50:45 +08009946 /**
9947 * Notify of the blocked state apps with a registered callback matching a given NAI.
9948 *
9949 * Unlike other callbacks, blocked status is different between each individual uid. So for
9950 * any given nai, all requests need to be considered according to the uid who filed it.
9951 *
9952 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009953 * @param oldMetered True if the previous network capabilities were metered.
9954 * @param newMetered True if the current network capabilities are metered.
9955 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9956 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009957 */
9958 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009959 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9960 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009961
9962 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9963 NetworkRequest nr = nai.requestAt(i);
9964 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009965
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009966 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9967 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9968 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009969 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009970 : oldVpnBlocked;
9971
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009972 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9973 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9974 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009975 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009976 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009977 }
9978 }
9979 }
9980
9981 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009982 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009983 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009984 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009985 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009986 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009987 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009988 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009989 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009990
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009991 final int oldBlockedState = getBlockedState(
9992 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9993 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9994 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009995 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009996 }
junyulaif2c67e42018-08-07 19:50:45 +08009997 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9998 NetworkRequest nr = nai.requestAt(i);
9999 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010000 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010001 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10002 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010003 }
10004 }
10005 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010006 }
10007
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010008 @VisibleForTesting
10009 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010010 // The NetworkInfo we actually send out has no bearing on the real
10011 // state of affairs. For example, if the default connection is mobile,
10012 // and a request for HIPRI has just gone away, we need to pretend that
10013 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10014 // the state to DISCONNECTED, even though the network is of type MOBILE
10015 // and is still connected.
10016 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10017 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010018 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010019 if (state != DetailedState.DISCONNECTED) {
10020 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010021 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010022 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010023 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010024 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10025 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10026 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10027 if (info.isFailover()) {
10028 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10029 nai.networkInfo.setFailover(false);
10030 }
10031 if (info.getReason() != null) {
10032 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10033 }
10034 if (info.getExtraInfo() != null) {
10035 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10036 }
10037 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010038 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010039 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010040 if (newDefaultAgent != null) {
10041 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10042 newDefaultAgent.networkInfo);
10043 } else {
10044 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10045 }
10046 }
10047 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10048 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010049 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010050 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010051 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010052 }
10053 }
10054 }
10055
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010056 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010057 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010058 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010059 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010060 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010061 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10062 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010063 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10064 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010065 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010066 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010067 } else {
10068 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10069 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010070 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010071 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010072
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010073 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10074 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10075 }
10076
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010077 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010078 * Returns the list of all interfaces that could be used by network traffic that does not
10079 * explicitly specify a network. This includes the default network, but also all VPNs that are
10080 * currently connected.
10081 *
10082 * Must be called on the handler thread.
10083 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010084 @NonNull
10085 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010086 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010087 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010088 final Set<Integer> activeNetIds = new ArraySet<>();
10089 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10090 if (nri.isBeingSatisfied()) {
10091 activeNetIds.add(nri.getSatisfier().network().netId);
10092 }
10093 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010094 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010095 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010096 defaultNetworks.add(nai.network);
10097 }
10098 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010099 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010100 }
10101
10102 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010103 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10104 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010105 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010106 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010107 ensureRunningOnConnectivityServiceThread();
10108 String activeIface = null;
10109 LinkProperties activeLinkProperties = getActiveLinkProperties();
10110 if (activeLinkProperties != null) {
10111 activeIface = activeLinkProperties.getInterfaceName();
10112 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010113
junyulai2050bed2021-01-23 09:46:34 +080010114 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010115 try {
junyulaide41fc22021-01-22 22:46:01 +080010116 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010117 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010118 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10119 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010120 } catch (Exception ignored) {
10121 }
10122 }
10123
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010124 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010125 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010126 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010127 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010128 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010129
10130 if (!TextUtils.isEmpty(settingUrl)) {
10131 return settingUrl;
10132 }
10133
10134 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010135 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010136 if (!TextUtils.isEmpty(settingUrl)) {
10137 return settingUrl;
10138 }
10139
10140 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010141 }
10142
10143 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010144 public void startNattKeepalive(Network network, int intervalSeconds,
10145 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010146 enforceKeepalivePermission();
10147 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010148 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010149 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10150 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010151 // false and set the underpinned network to null because there is no way and no
10152 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10153 // deprecated method.
10154 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010155 }
10156
10157 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010158 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010159 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010160 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010161 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010162 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010163 mKeepaliveTracker.startNattKeepalive(
10164 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010165 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10166 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010167 } finally {
10168 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10169 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010170 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10171 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010172 }
10173 }
junyulaid05a1922019-01-15 11:32:44 +080010174 }
10175
10176 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010177 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010178 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010179 try {
10180 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010181 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010182 mKeepaliveTracker.startTcpKeepalive(
10183 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10184 } finally {
10185 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10186 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010187 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10188 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010189 }
10190 }
junyulai0835a1e2019-01-08 20:04:33 +080010191 }
10192
10193 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010194 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010195 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010196 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10197 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010198 }
10199
10200 @Override
Remi NGUYEN VAN6ca02962023-02-20 20:10:09 +090010201 public int[] getSupportedKeepalives() {
10202 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10203 // Backwards compatibility with CTS 13
10204 android.Manifest.permission.QUERY_ALL_PACKAGES);
10205
10206 return BinderUtils.withCleanCallingIdentity(() ->
10207 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10208 }
10209
10210 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010211 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010212 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010213
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010214 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010215 final long token = Binder.clearCallingIdentity();
10216 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010217 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10218 UserHandle.getUserHandleForUid(uid))) {
10219 return;
10220 }
10221
Heemin Seogdb8489d2019-06-12 09:21:44 -070010222 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10223 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010224
10225 // Turn airplane mode off
10226 setAirplaneMode(false);
10227
10228 // restore private DNS settings to default mode (opportunistic)
10229 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10230 UserHandle.getUserHandleForUid(uid))) {
10231 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10232 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10233 }
10234
10235 Settings.Global.putString(mContext.getContentResolver(),
10236 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010237 } finally {
10238 Binder.restoreCallingIdentity(token);
10239 }
Stuart Scottd5463642015-04-02 18:00:02 -070010240 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010241
Ricky Wai7097cc92018-01-23 04:09:45 +000010242 @Override
10243 public byte[] getNetworkWatchlistConfigHash() {
10244 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10245 if (nwm == null) {
10246 loge("Unable to get NetworkWatchlistManager");
10247 return null;
10248 }
10249 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10250 return nwm.getWatchlistConfigHash();
10251 }
10252
Hugo Benichibe0c7652016-05-31 16:28:06 +090010253 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010254 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010255 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010256 }
Hugo Benichif4210292017-04-21 15:07:12 +090010257
10258 private static boolean toBool(int encodedBoolean) {
10259 return encodedBoolean != 0; // Only 0 means false.
10260 }
10261
10262 private static int encodeBool(boolean b) {
10263 return b ? 1 : 0;
10264 }
mswest4632928412018-03-12 10:34:34 -070010265
10266 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010267 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10268 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10269 @NonNull String[] args) {
10270 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10271 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010272 }
10273
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010274 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010275 @Override
10276 public int onCommand(String cmd) {
10277 if (cmd == null) {
10278 return handleDefaultCommands(cmd);
10279 }
10280 final PrintWriter pw = getOutPrintWriter();
10281 try {
10282 switch (cmd) {
10283 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010284 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
10285 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070010286 final String action = getNextArg();
10287 if ("enable".equals(action)) {
10288 setAirplaneMode(true);
10289 return 0;
10290 } else if ("disable".equals(action)) {
10291 setAirplaneMode(false);
10292 return 0;
10293 } else if (action == null) {
10294 final ContentResolver cr = mContext.getContentResolver();
10295 final int enabled = Settings.Global.getInt(cr,
10296 Settings.Global.AIRPLANE_MODE_ON);
10297 pw.println(enabled == 0 ? "disabled" : "enabled");
10298 return 0;
10299 } else {
10300 onHelp();
10301 return -1;
10302 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010303 case "reevaluate":
10304 // Usage : adb shell cmd connectivity reevaluate <netId>
10305 // If netId is omitted, then reevaluate the default network
10306 final String netId = getNextArg();
10307 final NetworkAgentInfo nai;
10308 if (null == netId) {
10309 // Note that the command is running on the wrong thread to call this,
10310 // so this could in principle return stale data. But it can't crash.
10311 nai = getDefaultNetwork();
10312 } else {
10313 // If netId can't be parsed, this throws NumberFormatException, which
10314 // is passed back to adb who prints it.
10315 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10316 }
10317 if (null == nai) {
10318 pw.println("Unknown network (net ID not found or no default network)");
10319 return 0;
10320 }
10321 Log.d(TAG, "Reevaluating network " + nai.network);
10322 reportNetworkConnectivity(nai.network, !nai.isValidated());
10323 return 0;
mswest4632928412018-03-12 10:34:34 -070010324 default:
10325 return handleDefaultCommands(cmd);
10326 }
10327 } catch (Exception e) {
10328 pw.println(e);
10329 }
10330 return -1;
10331 }
10332
10333 @Override
10334 public void onHelp() {
10335 PrintWriter pw = getOutPrintWriter();
10336 pw.println("Connectivity service commands:");
10337 pw.println(" help");
10338 pw.println(" Print this help text.");
10339 pw.println(" airplane-mode [enable|disable]");
10340 pw.println(" Turn airplane mode on or off.");
10341 pw.println(" airplane-mode");
10342 pw.println(" Get airplane mode.");
10343 }
10344 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010345
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010346 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010347 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10348 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10349 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010350 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010351 }
10352
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010353 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10354 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010355 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10356 final TransportInfo newInfo = nc.getTransportInfo();
10357 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10358 return;
10359 }
10360 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010361 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010362 }
10363 }
10364
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010365 /**
10366 * @param connectionInfo the connection to resolve.
10367 * @return {@code uid} if the connection is found and the app has permission to observe it
10368 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10369 * connection is not found.
10370 */
10371 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010372 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10373 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10374 }
10375
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010376 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010377 connectionInfo.local, connectionInfo.remote);
10378
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010379 if (uid == INVALID_UID) return uid; // Not found.
10380
10381 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10382 // VPN, if any, that applies to the UID that owns the connection.
10383 if (checkNetworkStackPermission()) return uid;
10384
10385 final NetworkAgentInfo vpn = getVpnForUid(uid);
10386 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010387 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010388 return INVALID_UID;
10389 }
10390
10391 return uid;
10392 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010393
Benedict Wong493e04b2018-11-09 14:45:34 -080010394 /**
10395 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10396 *
10397 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10398 */
10399 @Override
10400 public IBinder startOrGetTestNetworkService() {
10401 synchronized (mTNSLock) {
10402 TestNetworkService.enforceTestNetworkPermissions(mContext);
10403
10404 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010405 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010406 }
10407
10408 return mTNS;
10409 }
10410 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010411
Cody Kesting73708bf2019-12-18 10:57:50 -080010412 /**
10413 * Handler used for managing all Connectivity Diagnostics related functions.
10414 *
10415 * @see android.net.ConnectivityDiagnosticsManager
10416 *
10417 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10418 */
10419 @VisibleForTesting
10420 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010421 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10422
Cody Kesting73708bf2019-12-18 10:57:50 -080010423 /**
10424 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10425 * android.net.ConnectivityDiagnosticsManager}.
10426 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10427 * NetworkRequestInfo to be registered
10428 */
10429 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10430
10431 /**
10432 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10433 * android.net.ConnectivityDiagnosticsManager}.
10434 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10435 * arg1 = the uid of the caller
10436 */
10437 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10438
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010439 /**
10440 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010441 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010442 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10443 * NetworkMonitor.
10444 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010445 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010446 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010447
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010448 /**
10449 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10450 * been detected on the network.
10451 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10452 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10453 * arg2 = NetID.
10454 * data = PersistableBundle of extras passed from NetworkMonitor.
10455 */
10456 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10457
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010458 /**
10459 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10460 * the platform. This event will invoke {@link
10461 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10462 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070010463 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010464 */
10465 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
10466
Cody Kesting73708bf2019-12-18 10:57:50 -080010467 private ConnectivityDiagnosticsHandler(Looper looper) {
10468 super(looper);
10469 }
10470
10471 @Override
10472 public void handleMessage(Message msg) {
10473 switch (msg.what) {
10474 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10475 handleRegisterConnectivityDiagnosticsCallback(
10476 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
10477 break;
10478 }
10479 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10480 handleUnregisterConnectivityDiagnosticsCallback(
10481 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
10482 break;
10483 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010484 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010485 final ConnectivityReportEvent reportEvent =
10486 (ConnectivityReportEvent) msg.obj;
10487
Aaron Huang959d3642021-01-21 15:47:41 +080010488 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010489 break;
10490 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010491 case EVENT_DATA_STALL_SUSPECTED: {
10492 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080010493 final Pair<Long, PersistableBundle> arg =
10494 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010495 if (nai == null) break;
10496
Aaron Huang959d3642021-01-21 15:47:41 +080010497 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010498 break;
10499 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010500 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070010501 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010502 break;
10503 }
10504 default: {
10505 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
10506 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010507 }
10508 }
10509 }
10510
10511 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
10512 @VisibleForTesting
10513 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
10514 @NonNull private final IConnectivityDiagnosticsCallback mCb;
10515 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010516 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010517
10518 @VisibleForTesting
10519 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010520 @NonNull IConnectivityDiagnosticsCallback cb,
10521 @NonNull NetworkRequestInfo nri,
10522 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010523 mCb = cb;
10524 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010525 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010526 }
10527
10528 @Override
10529 public void binderDied() {
10530 log("ConnectivityDiagnosticsCallback IBinder died.");
10531 unregisterConnectivityDiagnosticsCallback(mCb);
10532 }
10533 }
10534
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010535 /**
10536 * Class used for sending information from {@link
10537 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
10538 */
10539 private static class NetworkTestedResults {
10540 private final int mNetId;
10541 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010542 @Nullable private final String mRedirectUrl;
10543
10544 private NetworkTestedResults(
10545 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
10546 mNetId = netId;
10547 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010548 mRedirectUrl = redirectUrl;
10549 }
10550 }
10551
10552 /**
10553 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
10554 * ConnectivityDiagnosticsHandler}.
10555 */
10556 private static class ConnectivityReportEvent {
10557 private final long mTimestampMillis;
10558 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080010559 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010560
Aaron Huang959d3642021-01-21 15:47:41 +080010561 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
10562 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010563 mTimestampMillis = timestampMillis;
10564 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080010565 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010566 }
10567 }
10568
Cody Kestingf1120be2020-08-03 18:01:40 -070010569 /**
10570 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
10571 * ConnectivityDiagnosticsHandler}.
10572 */
10573 private static class ReportedNetworkConnectivityInfo {
10574 public final boolean hasConnectivity;
10575 public final boolean isNetworkRevalidating;
10576 public final int reporterUid;
10577 @NonNull public final NetworkAgentInfo nai;
10578
10579 private ReportedNetworkConnectivityInfo(
10580 boolean hasConnectivity,
10581 boolean isNetworkRevalidating,
10582 int reporterUid,
10583 @NonNull NetworkAgentInfo nai) {
10584 this.hasConnectivity = hasConnectivity;
10585 this.isNetworkRevalidating = isNetworkRevalidating;
10586 this.reporterUid = reporterUid;
10587 this.nai = nai;
10588 }
10589 }
10590
Cody Kesting73708bf2019-12-18 10:57:50 -080010591 private void handleRegisterConnectivityDiagnosticsCallback(
10592 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
10593 ensureRunningOnConnectivityServiceThread();
10594
10595 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080010596 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010597 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
10598
James Mattis64b8b0f2020-11-24 17:40:49 -080010599 // Connectivity Diagnostics are meant to be used with a single network request. It would be
10600 // confusing for these networks to change when an NRI is satisfied in another layer.
10601 if (nri.isMultilayerRequest()) {
10602 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
10603 + "network requests.");
10604 }
10605
Cody Kesting73708bf2019-12-18 10:57:50 -080010606 // This means that the client registered the same callback multiple times. Do
10607 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080010608 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010609 if (VDBG) log("Diagnostics callback is already registered");
10610
10611 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10612 // incremented when the NetworkRequestInfo is created as part of
10613 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010614 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080010615 return;
10616 }
10617
Cody Kesting31f1ff62020-03-05 10:46:02 -080010618 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080010619
10620 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080010621 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010622 } catch (RemoteException e) {
10623 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080010624 return;
10625 }
10626
10627 // Once registered, provide ConnectivityReports for matching Networks
10628 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
10629 synchronized (mNetworkForNetId) {
10630 for (int i = 0; i < mNetworkForNetId.size(); i++) {
10631 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080010632 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
10633 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080010634 matchingNetworks.add(nai);
10635 }
10636 }
10637 }
10638 for (final NetworkAgentInfo nai : matchingNetworks) {
10639 final ConnectivityReport report = nai.getConnectivityReport();
10640 if (report == null) {
10641 continue;
10642 }
10643 if (!checkConnectivityDiagnosticsPermissions(
10644 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10645 continue;
10646 }
10647
10648 try {
10649 cb.onConnectivityReportAvailable(report);
10650 } catch (RemoteException e) {
10651 // Exception while sending the ConnectivityReport. Move on to the next network.
10652 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010653 }
10654 }
10655
10656 private void handleUnregisterConnectivityDiagnosticsCallback(
10657 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
10658 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010659 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010660
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010661 final ConnectivityDiagnosticsCallbackInfo cbInfo =
10662 mConnectivityDiagnosticsCallbacks.remove(iCb);
10663 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010664 if (VDBG) log("Removing diagnostics callback that is not currently registered");
10665 return;
10666 }
10667
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010668 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080010669
Cody Kesting70fa2b22020-12-02 12:16:56 -080010670 // Caller's UID must either be the registrants (if they are unregistering) or the System's
10671 // (if the Binder died)
10672 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
10673 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080010674 return;
10675 }
10676
Cody Kesting46cb1672020-03-04 13:35:20 -080010677 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10678 // incremented when the NetworkRequestInfo is created as part of
10679 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010680 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080010681
Cody Kesting31f1ff62020-03-05 10:46:02 -080010682 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010683 }
10684
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010685 private void handleNetworkTestedWithExtras(
10686 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
10687 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080010688 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010689 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010690 final ConnectivityReport report =
10691 new ConnectivityReport(
10692 reportEvent.mNai.network,
10693 reportEvent.mTimestampMillis,
10694 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010695 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010696 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080010697 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070010698
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010699 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010700 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010701 for (final IConnectivityDiagnosticsCallback cb : results) {
10702 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080010703 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010704 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070010705 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010706 }
10707 }
10708 }
10709
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010710 private void handleDataStallSuspected(
10711 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
10712 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080010713 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010714 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010715 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080010716 new DataStallReport(
10717 nai.network,
10718 timestampMillis,
10719 detectionMethod,
10720 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010721 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080010722 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010723 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010724 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010725 for (final IConnectivityDiagnosticsCallback cb : results) {
10726 try {
10727 cb.onDataStallSuspected(report);
10728 } catch (RemoteException ex) {
10729 loge("Error invoking onDataStallSuspected", ex);
10730 }
10731 }
10732 }
10733
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010734 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070010735 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
10736 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
10737 final ConnectivityReport cachedReport = nai.getConnectivityReport();
10738
10739 // If the Network is being re-validated as a result of this call to
10740 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
10741 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010742 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010743 getMatchingPermissionedCallbacks(
10744 nai,
10745 reportedNetworkConnectivityInfo.isNetworkRevalidating
10746 ? Process.INVALID_UID
10747 : reportedNetworkConnectivityInfo.reporterUid);
10748
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010749 for (final IConnectivityDiagnosticsCallback cb : results) {
10750 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070010751 cb.onNetworkConnectivityReported(
10752 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010753 } catch (RemoteException ex) {
10754 loge("Error invoking onNetworkConnectivityReported", ex);
10755 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010756
10757 // If the Network isn't re-validating, also provide the cached report. If there is no
10758 // cached report, the Network is still being validated and a report will be sent once
10759 // validation is complete. Note that networks which never undergo validation will still
10760 // have a cached ConnectivityReport with RESULT_SKIPPED.
10761 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
10762 try {
10763 cb.onConnectivityReportAvailable(cachedReport);
10764 } catch (RemoteException ex) {
10765 loge("Error invoking onConnectivityReportAvailable", ex);
10766 }
10767 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010768 }
10769 }
10770
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010771 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090010772 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
10773 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010774 sanitized.setUids(null);
10775 sanitized.setAdministratorUids(new int[0]);
10776 sanitized.setOwnerUid(Process.INVALID_UID);
10777 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080010778 }
10779
Cody Kestingf1120be2020-08-03 18:01:40 -070010780 /**
10781 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
10782 *
10783 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
10784 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010785 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070010786 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010787 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010788 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010789 mConnectivityDiagnosticsCallbacks.entrySet()) {
10790 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
10791 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070010792
James Mattis64b8b0f2020-11-24 17:40:49 -080010793 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070010794 if (!nai.satisfies(nri.mRequests.get(0))) {
10795 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010796 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010797
10798 // UID for this callback must either be:
10799 // - INVALID_UID (which sends callbacks to all UIDs), or
10800 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
10801 // notified as a result)
10802 if (uid != Process.INVALID_UID && uid != nri.mUid) {
10803 continue;
10804 }
10805
10806 if (!checkConnectivityDiagnosticsPermissions(
10807 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10808 continue;
10809 }
10810
10811 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010812 }
10813 return results;
10814 }
10815
Cody Kesting7474f672021-05-11 14:22:40 -070010816 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
10817 @NonNull NetworkAgentInfo nai) {
10818 // TODO(b/188483916): replace with a transport-agnostic location-aware check
10819 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
10820 }
10821
Cody Kesting160ef392021-05-05 13:17:22 -070010822 private boolean hasLocationPermission(String packageName, int uid) {
10823 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
10824 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
10825 // call in a try-catch.
10826 try {
10827 if (!mLocationPermissionChecker.checkLocationPermission(
10828 packageName, null /* featureId */, uid, null /* message */)) {
10829 return false;
10830 }
10831 } catch (SecurityException e) {
10832 return false;
10833 }
10834
10835 return true;
10836 }
10837
10838 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
10839 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090010840 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070010841 && virtual.networkCapabilities.getOwnerUid() == uid
10842 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
10843 return true;
10844 }
10845 }
10846
10847 return false;
10848 }
10849
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010850 @VisibleForTesting
10851 boolean checkConnectivityDiagnosticsPermissions(
10852 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
10853 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
10854 return true;
10855 }
10856
Cody Kesting160ef392021-05-05 13:17:22 -070010857 // Administrator UIDs also contains the Owner UID
10858 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10859 if (!CollectionUtils.contains(administratorUids, callbackUid)
10860 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010861 return false;
10862 }
10863
Cody Kesting7474f672021-05-11 14:22:40 -070010864 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10865 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010866 }
10867
Cody Kestingd199a9d2019-12-17 12:55:28 -080010868 @Override
10869 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010870 @NonNull IConnectivityDiagnosticsCallback callback,
10871 @NonNull NetworkRequest request,
10872 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010873 Objects.requireNonNull(callback, "callback must not be null");
10874 Objects.requireNonNull(request, "request must not be null");
10875 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10876
Cody Kesting73708bf2019-12-18 10:57:50 -080010877 if (request.legacyType != TYPE_NONE) {
10878 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10879 + " Please use NetworkCapabilities instead.");
10880 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010881 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010882 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010883
10884 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10885 // and administrator uids to be safe.
10886 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010887 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010888
10889 final NetworkRequest requestWithId =
10890 new NetworkRequest(
10891 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10892
10893 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10894 //
10895 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10896 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10897 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010898 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010899 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010900 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010901
10902 mConnectivityDiagnosticsHandler.sendMessage(
10903 mConnectivityDiagnosticsHandler.obtainMessage(
10904 ConnectivityDiagnosticsHandler
10905 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10906 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010907 }
10908
10909 @Override
10910 public void unregisterConnectivityDiagnosticsCallback(
10911 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010912 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010913 mConnectivityDiagnosticsHandler.sendMessage(
10914 mConnectivityDiagnosticsHandler.obtainMessage(
10915 ConnectivityDiagnosticsHandler
10916 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010917 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010918 0,
10919 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010920 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010921
Yan Yanfe96dde2022-12-05 23:00:01 +000010922 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
10923 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
10924 if (underlyingNetworks == null) return false;
10925
10926 for (Network network : underlyingNetworks) {
10927 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
10928 return true;
10929 }
10930 }
10931 return false;
10932 }
10933
Cody Kestingf53a0752020-04-15 12:33:28 -070010934 @Override
10935 public void simulateDataStall(int detectionMethod, long timestampMillis,
10936 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010937 Objects.requireNonNull(network, "network must not be null");
10938 Objects.requireNonNull(extras, "extras must not be null");
10939
paulhu3ffffe72021-09-16 10:15:22 +080010940 enforceAnyPermissionOf(mContext,
10941 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070010942 android.Manifest.permission.NETWORK_STACK);
10943 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000010944 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
10945 throw new SecurityException(
10946 "Data Stall simulation is only possible for test networks or networks built on"
10947 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010948 }
10949
10950 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000010951 if (nai == null
10952 || (nai.creatorUid != mDeps.getCallingUid()
10953 && nai.creatorUid != Process.SYSTEM_UID)) {
10954 throw new SecurityException(
10955 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070010956 }
10957
Cody Kesting652e3ec2020-05-21 12:08:21 -070010958 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10959 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10960 // Data Stall information as a DataStallReportParcelable and passing to
10961 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10962 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010963 final DataStallReportParcelable p = new DataStallReportParcelable();
10964 p.timestampMillis = timestampMillis;
10965 p.detectionMethod = detectionMethod;
10966
10967 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10968 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10969 }
10970 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10971 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10972 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10973 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10974 }
10975
Serik Beketayevec8ad212020-12-07 22:43:07 -080010976 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010977 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010978
lucaslin66f44212021-02-23 01:12:55 +080010979 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10980 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010981 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010982 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010983 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010984 }
lucaslin37a16d92021-01-21 19:48:09 +080010985
10986 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010987 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010988 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010989 nai.clatd.interfaceLinkStateChanged(iface, up);
10990 }
10991 }
10992
10993 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010994 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010995 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010996 nai.clatd.interfaceRemoved(iface);
10997 }
lucaslin66f44212021-02-23 01:12:55 +080010998 }
10999 }
11000
lucaslin1a8b4c62021-01-21 02:02:55 +080011001 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11002
11003 /**
11004 * Class used for updating network activity tracking with netd and notify network activity
11005 * changes.
11006 */
11007 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011008 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011009 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011010 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080011011 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11012 new RemoteCallbackList<>();
11013 // Indicate the current system default network activity is active or not.
11014 @GuardedBy("mActiveIdleTimers")
11015 private boolean mNetworkActive;
11016 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090011017 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080011018 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080011019
Chalard Jean46bfbf02022-02-02 00:56:25 +090011020 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011021 public final int timeout;
11022 public final int transportType;
11023
11024 IdleTimerParams(int timeout, int transport) {
11025 this.timeout = timeout;
11026 this.transportType = transport;
11027 }
11028 }
11029
11030 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080011031 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011032 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011033 mNetd = netd;
11034 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080011035 }
11036
lucaslin66f44212021-02-23 01:12:55 +080011037 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
11038 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
11039 synchronized (mActiveIdleTimers) {
11040 mNetworkActive = active;
11041 // If there are no idle timers, it means that system is not monitoring
11042 // activity, so the system default network for those default network
11043 // unspecified apps is always considered active.
11044 //
11045 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
11046 // any network activity change event. Whenever this event is received,
11047 // the mActiveIdleTimers should be always not empty. The legacy behavior
11048 // is no-op. Remove to refer to mNetworkActive only.
11049 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
11050 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
11051 }
11052 }
11053 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011054
lucaslin1193a5d2021-01-21 02:04:15 +080011055 // The network activity should only be updated from ConnectivityService handler thread
11056 // when mActiveIdleTimers lock is held.
11057 @GuardedBy("mActiveIdleTimers")
11058 private void reportNetworkActive() {
11059 final int length = mNetworkActivityListeners.beginBroadcast();
11060 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
11061 try {
11062 for (int i = 0; i < length; i++) {
11063 try {
11064 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
11065 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011066 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080011067 }
11068 }
11069 } finally {
11070 mNetworkActivityListeners.finishBroadcast();
11071 }
11072 }
11073
11074 @GuardedBy("mActiveIdleTimers")
11075 public void handleReportNetworkActivity() {
11076 synchronized (mActiveIdleTimers) {
11077 reportNetworkActive();
11078 }
11079 }
11080
lucaslin1a8b4c62021-01-21 02:02:55 +080011081 // This is deprecated and only to support legacy use cases.
11082 private int transportTypeToLegacyType(int type) {
11083 switch (type) {
11084 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011085 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080011086 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011087 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080011088 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011089 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080011090 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011091 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080011092 default:
11093 loge("Unexpected transport in transportTypeToLegacyType: " + type);
11094 }
11095 return ConnectivityManager.TYPE_NONE;
11096 }
11097
11098 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
11099 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
11100 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
11101 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
11102 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
11103 final long ident = Binder.clearCallingIdentity();
11104 try {
11105 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
11106 RECEIVE_DATA_ACTIVITY_CHANGE,
11107 null /* resultReceiver */,
11108 null /* scheduler */,
11109 0 /* initialCode */,
11110 null /* initialData */,
11111 null /* initialExtra */);
11112 } finally {
11113 Binder.restoreCallingIdentity(ident);
11114 }
11115 }
11116
11117 /**
11118 * Setup data activity tracking for the given network.
11119 *
11120 * Every {@code setupDataActivityTracking} should be paired with a
11121 * {@link #removeDataActivityTracking} for cleanup.
11122 */
11123 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
11124 final String iface = networkAgent.linkProperties.getInterfaceName();
11125
11126 final int timeout;
11127 final int type;
11128
11129 if (networkAgent.networkCapabilities.hasTransport(
11130 NetworkCapabilities.TRANSPORT_CELLULAR)) {
11131 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011132 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080011133 10);
11134 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11135 } else if (networkAgent.networkCapabilities.hasTransport(
11136 NetworkCapabilities.TRANSPORT_WIFI)) {
11137 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011138 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080011139 15);
11140 type = NetworkCapabilities.TRANSPORT_WIFI;
11141 } else {
11142 return; // do not track any other networks
11143 }
11144
lucaslinb961efc2021-01-21 02:03:17 +080011145 updateRadioPowerState(true /* isActive */, type);
11146
lucaslin1a8b4c62021-01-21 02:02:55 +080011147 if (timeout > 0 && iface != null) {
11148 try {
lucaslin1193a5d2021-01-21 02:04:15 +080011149 synchronized (mActiveIdleTimers) {
11150 // Networks start up.
11151 mNetworkActive = true;
11152 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
11153 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
11154 reportNetworkActive();
11155 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011156 } catch (Exception e) {
11157 // You shall not crash!
11158 loge("Exception in setupDataActivityTracking " + e);
11159 }
11160 }
11161 }
11162
11163 /**
11164 * Remove data activity tracking when network disconnects.
11165 */
11166 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
11167 final String iface = networkAgent.linkProperties.getInterfaceName();
11168 final NetworkCapabilities caps = networkAgent.networkCapabilities;
11169
lucaslinb961efc2021-01-21 02:03:17 +080011170 if (iface == null) return;
11171
11172 final int type;
11173 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
11174 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11175 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
11176 type = NetworkCapabilities.TRANSPORT_WIFI;
11177 } else {
11178 return; // do not track any other networks
11179 }
11180
11181 try {
11182 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080011183 synchronized (mActiveIdleTimers) {
11184 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
11185 // The call fails silently if no idle timer setup for this interface
11186 mNetd.idletimerRemoveInterface(iface, params.timeout,
11187 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080011188 }
lucaslinb961efc2021-01-21 02:03:17 +080011189 } catch (Exception e) {
11190 // You shall not crash!
11191 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080011192 }
11193 }
11194
11195 /**
11196 * Update data activity tracking when network state is updated.
11197 */
11198 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
11199 NetworkAgentInfo oldNetwork) {
11200 if (newNetwork != null) {
11201 setupDataActivityTracking(newNetwork);
11202 }
11203 if (oldNetwork != null) {
11204 removeDataActivityTracking(oldNetwork);
11205 }
11206 }
lucaslinb961efc2021-01-21 02:03:17 +080011207
11208 private void updateRadioPowerState(boolean isActive, int transportType) {
11209 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
11210 switch (transportType) {
11211 case NetworkCapabilities.TRANSPORT_CELLULAR:
11212 bs.reportMobileRadioPowerState(isActive, NO_UID);
11213 break;
11214 case NetworkCapabilities.TRANSPORT_WIFI:
11215 bs.reportWifiRadioPowerState(isActive, NO_UID);
11216 break;
11217 default:
11218 logw("Untracked transport type:" + transportType);
11219 }
11220 }
lucaslin1193a5d2021-01-21 02:04:15 +080011221
11222 public boolean isDefaultNetworkActive() {
11223 synchronized (mActiveIdleTimers) {
11224 // If there are no idle timers, it means that system is not monitoring activity,
11225 // so the default network is always considered active.
11226 //
11227 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
11228 // tracking is disabled (negative idle timer value configured), or no active default
11229 // network. In the latter case, this reports active but it should report inactive.
11230 return mNetworkActive || mActiveIdleTimers.isEmpty();
11231 }
11232 }
11233
11234 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
11235 mNetworkActivityListeners.register(l);
11236 }
11237
11238 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
11239 mNetworkActivityListeners.unregister(l);
11240 }
lucaslin012f7a12021-01-21 02:04:35 +080011241
11242 public void dump(IndentingPrintWriter pw) {
11243 synchronized (mActiveIdleTimers) {
11244 pw.print("mNetworkActive="); pw.println(mNetworkActive);
11245 pw.println("Idle timers:");
11246 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
11247 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
11248 final IdleTimerParams params = ent.getValue();
11249 pw.print(" timeout="); pw.print(params.timeout);
11250 pw.print(" type="); pw.println(params.transportType);
11251 }
11252 }
11253 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011254 }
James Mattis47db0582021-01-01 14:13:35 -080011255
Daniel Brightf9e945b2020-06-15 16:10:01 -070011256 /**
11257 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
11258 *
11259 * @param socketInfo the socket information
11260 * @param callback the callback to register
11261 */
11262 @Override
11263 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
11264 @NonNull final IQosCallback callback) {
11265 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
11266 if (nai == null || nai.networkCapabilities == null) {
11267 try {
11268 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
11269 } catch (final RemoteException ex) {
11270 loge("registerQosCallbackInternal: RemoteException", ex);
11271 }
11272 return;
11273 }
11274 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
11275 }
11276
11277 /**
11278 * Register a {@link IQosCallback} with base {@link QosFilter}.
11279 *
11280 * @param filter the filter to register
11281 * @param callback the callback to register
11282 * @param nai the agent information related to the filter's network
11283 */
11284 @VisibleForTesting
11285 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
11286 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011287 Objects.requireNonNull(filter, "filter must be non-null");
11288 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011289
11290 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080011291 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
11292 // on this network is unregistered when the app loses permission or b) no QoS
11293 // callbacks are sent for restricted networks unless the app currently has permission
11294 // to access restricted networks.
11295 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070011296 }
11297 mQosCallbackTracker.registerCallback(callback, filter, nai);
11298 }
11299
11300 /**
11301 * Unregisters the given callback.
11302 *
11303 * @param callback the callback to unregister
11304 */
11305 @Override
11306 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011307 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011308 mQosCallbackTracker.unregisterCallback(callback);
11309 }
James Mattis47db0582021-01-01 14:13:35 -080011310
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011311 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
11312 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
11313 // Enterprise device can be fully managed like device owner and such use case
11314 // also should be supported. Calling app check for work profile and fully managed device
11315 // is already done in DevicePolicyManager.
11316 // This check is an extra caution to be sure device is fully managed or not.
11317 final UserManager um = mContext.getSystemService(UserManager.class);
11318 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
11319 if (um.isManagedProfile(profile.getIdentifier())) {
11320 return true;
11321 }
11322 if (SdkLevel.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
11323 return false;
11324 }
11325
James Mattis45d81842021-01-10 14:24:24 -080011326 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011327 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011328 *
11329 * See the documentation for the individual preferences for a description of the supported
11330 * behaviors.
11331 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011332 * @param profile If the device owner is set, any profile is allowed.
11333 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011334 * @param preferences the list of profile network preferences for the
11335 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011336 * @param listener an optional listener to listen for completion of the operation.
11337 */
11338 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011339 public void setProfileNetworkPreferences(
11340 @NonNull final UserHandle profile,
11341 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090011342 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011343 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011344 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011345
11346 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011347 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11348 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11349 .build();
11350 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011351 }
11352
paulhu3ffffe72021-09-16 10:15:22 +080011353 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011354 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011355 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011356 }
11357 if (profile.getIdentifier() < 0) {
11358 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11359 + "UserHandle.CURRENT not supported)");
11360 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011361 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11362 throw new IllegalArgumentException("Profile must be a managed profile "
11363 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011364 }
paulhuaa0743d2021-05-26 21:56:03 +080011365
Chalard Jean0606fc82022-12-14 20:34:43 +090011366 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011367 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011368 for (final ProfileNetworkPreference preference : preferences) {
11369 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011370 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011371 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011372 switch (preference.getPreference()) {
11373 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11374 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011375 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011376 if (preference.getPreferenceEnterpriseId() != 0) {
11377 throw new IllegalArgumentException(
11378 "Invalid enterprise identifier in setProfileNetworkPreferences");
11379 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011380 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011381 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11382 blockingNonEnterprise = true;
11383 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011384 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11385 allowFallback = false;
11386 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011387 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011388 // This code is needed even though there is a check later on,
11389 // because isRangeAlreadyInPreferenceList assumes that every preference
11390 // has a UID list.
11391 if (hasDefaultPreference) {
11392 throw new IllegalArgumentException(
11393 "Default profile preference should not be set along with other "
11394 + "preference");
11395 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011396 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11397 throw new IllegalArgumentException(
11398 "Invalid enterprise identifier in setProfileNetworkPreferences");
11399 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011400 final Set<UidRange> uidRangeSet =
11401 getUidListToBeAppliedForNetworkPreference(profile, preference);
11402 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11403 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11404 } else {
11405 throw new IllegalArgumentException(
11406 "Overlapping uid range in setProfileNetworkPreferences");
11407 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011408 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011409 nc.addEnterpriseId(
11410 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011411 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11412 break;
11413 default:
11414 throw new IllegalArgumentException(
11415 "Invalid preference in setProfileNetworkPreferences");
11416 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011417 preferenceList.add(new ProfileNetworkPreferenceInfo(
11418 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011419 if (hasDefaultPreference && preferenceList.size() > 1) {
11420 throw new IllegalArgumentException(
11421 "Default profile preference should not be set along with other preference");
11422 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011423 }
11424 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011425 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011426 }
11427
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011428 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
11429 @NonNull final UserHandle profile,
11430 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
11431 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080011432 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
11433 profileNetworkPreference.getIncludedUids());
11434
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011435 if (uidRangeSet.size() > 0) {
11436 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
11437 throw new IllegalArgumentException(
11438 "Allow uid range is outside the uid range of profile.");
11439 }
11440 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080011441 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011442 profileNetworkPreference.getExcludedUids());
11443 if (disallowUidRangeSet.size() > 0) {
11444 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
11445 throw new IllegalArgumentException(
11446 "disallow uid range is outside the uid range of profile.");
11447 }
11448 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
11449 disallowUidRangeSet);
11450 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011451 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011452 uidRangeSet.add(profileUids);
11453 }
11454 }
11455 return uidRangeSet;
11456 }
11457
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011458 private boolean isEnterpriseIdentifierValid(
11459 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011460 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011461 return true;
11462 }
11463 return false;
11464 }
11465
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011466 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090011467 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011468 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090011469 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011470 // The NRI for a user should contain the request for capabilities.
11471 // If fallback to default network is needed then NRI should include
11472 // the request for the default network. Create an image of it to
11473 // have the correct UIDs in it (also a request can only be part of one NRI, because
11474 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011475 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
11476 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011477 if (pref.allowFallback) {
11478 nrs.add(createDefaultInternetRequestForTransport(
11479 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11480 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011481 if (VDBG) {
11482 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
11483 pref.capabilities.getUids()));
11484 }
11485
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011486 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080011487 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080011488 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011489 result.add(nri);
11490 }
11491 return result;
11492 }
11493
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011494 /**
11495 * Compare if the given UID range sets have the same UIDs.
11496 *
11497 */
11498 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090011499 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011500 @NonNull Set<UidRange> uidRangeSet) {
11501 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
11502 return false;
11503 }
Chalard Jean0606fc82022-12-14 20:34:43 +090011504 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011505 if (UidRangeUtils.doesRangeSetOverlap(
11506 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
11507 return true;
11508 }
11509 }
11510 return false;
11511 }
11512
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011513 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090011514 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011515 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011516 /*
11517 * handleSetProfileNetworkPreference is always called for single user.
11518 * preferenceList only contains preferences for different uids within the same user
11519 * (enforced by getUidListToBeAppliedForNetworkPreference).
11520 * Clear all the existing preferences for the user before applying new preferences.
11521 *
11522 */
Chalard Jean0606fc82022-12-14 20:34:43 +090011523 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
11524 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011525 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
11526 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011527
paulhu74128522021-09-28 02:29:03 +000011528 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
11529 addPerAppDefaultNetworkRequests(
11530 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080011531 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080011532
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011533 // Finally, rematch.
11534 rematchAllNetworksAndRequests();
11535
11536 if (null != listener) {
11537 try {
11538 listener.onComplete();
11539 } catch (RemoteException e) {
11540 loge("Listener for setProfileNetworkPreference has died");
11541 }
11542 }
11543 }
11544
paulhu51f77dc2021-06-07 02:34:20 +000011545 @VisibleForTesting
11546 @NonNull
11547 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
11548 @NonNull final Set<Integer> uids) {
11549 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11550 if (uids.size() == 0) {
11551 // Should not create NetworkRequestInfo if no preferences. Without uid range in
11552 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
11553 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
11554 return nris;
11555 }
11556
11557 final List<NetworkRequest> requests = new ArrayList<>();
11558 // The NRI should be comprised of two layers:
11559 // - The request for the mobile network preferred.
11560 // - The request for the default network, for fallback.
11561 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090011562 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000011563 requests.add(createDefaultInternetRequestForTransport(
11564 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11565 final Set<UidRange> ranges = new ArraySet<>();
11566 for (final int uid : uids) {
11567 ranges.add(new UidRange(uid, uid));
11568 }
11569 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080011570 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080011571 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000011572 return nris;
11573 }
11574
11575 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000011576 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000011577 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
11578 addPerAppDefaultNetworkRequests(
11579 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000011580 // Finally, rematch.
11581 rematchAllNetworksAndRequests();
11582 }
11583
Patrick Rohr2857ac42022-01-21 14:58:16 +010011584 private void handleIngressRateLimitChanged() {
11585 final long oldIngressRateLimit = mIngressRateLimit;
11586 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
11587 mContext);
11588 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
11589 if (canNetworkBeRateLimited(networkAgent)) {
11590 // If rate limit has previously been enabled, remove the old limit first.
11591 if (oldIngressRateLimit >= 0) {
11592 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
11593 }
11594 if (mIngressRateLimit >= 0) {
11595 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
11596 mIngressRateLimit);
11597 }
11598 }
11599 }
11600 }
11601
11602 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090011603 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
11604 if (!SdkLevel.isAtLeastT()) return false;
11605
Patrick Rohrff3b3f82022-02-09 15:15:52 +010011606 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
11607 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
11608 // internet connectivity can be rate limited.
11609 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
11610 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010011611 return false;
11612 }
11613
11614 final String iface = networkAgent.linkProperties.getInterfaceName();
11615 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010011616 // This may happen in tests, but if there is no interface then there is nothing that
11617 // can be rate limited.
11618 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010011619 return false;
11620 }
11621 return true;
11622 }
11623
James Mattis45d81842021-01-10 14:24:24 -080011624 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080011625 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
11626 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080011627 }
11628
11629 /**
11630 * Used by automotive devices to set the network preferences used to direct traffic at an
11631 * application level as per the given OemNetworkPreferences. An example use-case would be an
11632 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
11633 * vehicle via a particular network.
11634 *
11635 * Calling this will overwrite the existing preference.
11636 *
James Mattisda32cfe2021-01-26 16:23:52 -080011637 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090011638 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080011639 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080011640 */
James Mattis47db0582021-01-01 14:13:35 -080011641 @Override
James Mattis45d81842021-01-10 14:24:24 -080011642 public void setOemNetworkPreference(
11643 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011644 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080011645
James Mattisfa270db2021-05-31 17:11:10 -070011646 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11647 // Only bypass the permission/device checks if this is a valid test request.
11648 if (isValidTestOemNetworkPreference(preference)) {
11649 enforceManageTestNetworksPermission();
11650 } else {
11651 enforceAutomotiveDevice();
11652 enforceOemNetworkPreferencesPermission();
11653 validateOemNetworkPreferences(preference);
11654 }
James Mattis45d81842021-01-10 14:24:24 -080011655
James Mattis45d81842021-01-10 14:24:24 -080011656 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
11657 new Pair<>(preference, listener)));
11658 }
11659
James Mattisfa270db2021-05-31 17:11:10 -070011660 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000011661 * Sets the specified UIDs to get/receive the VPN as the only default network.
11662 *
11663 * Calling this will overwrite the existing network preference for this session, and the
11664 * specified UIDs won't get any default network when no VPN is connected.
11665 *
11666 * @param session The VPN session which manages the passed UIDs.
11667 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
11668 * setting for this session if the array is empty. Null is not allowed, the
11669 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
11670 * @hide
11671 */
11672 @Override
11673 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
11674 Objects.requireNonNull(ranges);
11675 enforceNetworkStackOrSettingsPermission();
11676 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
11677 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
11678 throw new IllegalArgumentException(
11679 "setVpnNetworkPreference: Passed UID ranges overlap");
11680 }
11681
11682 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
11683 new VpnNetworkPreferenceInfo(session,
11684 new ArraySet<UidRange>(Arrays.asList(ranges)))));
11685 }
11686
11687 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
11688 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
11689
11690 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
11691 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
11692
11693 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
11694 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
11695 // Finally, rematch.
11696 rematchAllNetworksAndRequests();
11697 }
11698
11699 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
11700 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
11701 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11702 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
11703 final List<NetworkRequest> requests = new ArrayList<>();
11704 // Request VPN only, so other networks won't be the fallback options when VPN is not
11705 // connected temporarily.
11706 requests.add(createVpnRequest());
11707 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
11708 setNetworkRequestUids(requests, uidRanges);
11709 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
11710 }
11711 return nris;
11712 }
11713
11714 /**
James Mattisfa270db2021-05-31 17:11:10 -070011715 * Check the validity of an OEM network preference to be used for testing purposes.
11716 * @param preference the preference to validate
11717 * @return true if this is a valid OEM network preference test request.
11718 */
11719 private boolean isValidTestOemNetworkPreference(
11720 @NonNull final OemNetworkPreferences preference) {
11721 // Allow for clearing of an existing OemNetworkPreference used for testing.
11722 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
11723 // changes after this check is complete. This is an unlikely scenario as calling of this API
11724 // is controlled by the OEM therefore the added complexity is not worth adding given those
11725 // circumstances. That said, it is an edge case to be aware of hence this comment.
11726 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
11727 && isTestOemNetworkPreference(mOemNetworkPreferences);
11728 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
11729 }
11730
11731 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
11732 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
11733 return prefMap.size() == 1
11734 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
11735 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
11736 }
11737
James Mattis45d81842021-01-10 14:24:24 -080011738 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
11739 for (@OemNetworkPreferences.OemNetworkPreference final int pref
11740 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070011741 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
11742 throw new IllegalArgumentException(
11743 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
11744 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080011745 }
11746 }
11747 }
11748
11749 private void handleSetOemNetworkPreference(
11750 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011751 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080011752 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11753 if (DBG) {
11754 log("set OEM network preferences :" + preference.toString());
11755 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011756
James Mattiscb1e0362021-04-06 17:07:42 -070011757 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000011758 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
11759 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
11760 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080011761 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080011762
11763 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011764 try {
11765 listener.onComplete();
11766 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080011767 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011768 }
James Mattis45d81842021-01-10 14:24:24 -080011769 }
11770 }
11771
paulhu74128522021-09-28 02:29:03 +000011772 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080011773 // Skip the requests which are set by other network preference. Because the uid range rules
11774 // should stay in netd.
11775 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080011776 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080011777 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080011778 }
11779
James Mattis3ce3d3c2021-02-09 18:18:28 -080011780 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
11781 ensureRunningOnConnectivityServiceThread();
11782 mDefaultNetworkRequests.addAll(nris);
11783 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
11784 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080011785 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000011786 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
11787 nrisToRegister.addAll(
11788 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
11789 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011790 }
11791
11792 /**
11793 * All current requests that are tracking the default network need to be assessed as to whether
11794 * or not the current set of per-application default requests will be changing their default
11795 * network. If so, those requests will need to be updated so that they will send callbacks for
11796 * default network changes at the appropriate time. Additionally, those requests tracking the
11797 * default that were previously updated by this flow will need to be reassessed.
11798 * @return the nris which will need to be updated.
11799 */
11800 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
11801 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
11802 // Get the distinct nris to check since for multilayer requests, it is possible to have the
11803 // same nri in the map's values for each of its NetworkRequest objects.
11804 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080011805 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011806 // Include this nri if it is currently being tracked.
11807 if (isPerAppTrackedNri(nri)) {
11808 defaultCallbackRequests.add(nri);
11809 continue;
11810 }
11811 // We only track callbacks for requests tracking the default.
11812 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
11813 continue;
11814 }
11815 // Include this nri if it will be tracked by the new per-app default requests.
11816 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011817 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080011818 if (isNriGoingToBeTracked) {
11819 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080011820 }
11821 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080011822 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080011823 }
11824
James Mattis3ce3d3c2021-02-09 18:18:28 -080011825 /**
11826 * Create nris for those network requests that are currently tracking the default network that
11827 * are being controlled by a per-application default.
11828 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
11829 * foundation when creating the nri. Important items include the calling uid's original
11830 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
11831 * requests are assumed to have already been validated as needing to be updated.
11832 * @return the Set of nris to use when registering network requests.
11833 */
11834 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
11835 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
11836 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
11837 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
11838 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011839 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011840
Chalard Jean9473c982021-07-29 20:03:04 +090011841 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080011842 if (trackingNri == mDefaultRequest) {
11843 callbackRequestsToRegister.add(new NetworkRequestInfo(
11844 callbackRequest,
11845 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
11846 continue;
11847 }
11848
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011849 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011850 callbackRequestsToRegister.add(new NetworkRequestInfo(
11851 callbackRequest,
11852 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011853 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090011854 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080011855 }
11856 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080011857 }
11858
Chalard Jean17215832021-03-01 14:06:28 +090011859 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
11860 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090011861 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011862 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090011863 }
11864 }
11865
James Mattis45d81842021-01-10 14:24:24 -080011866 /**
11867 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
11868 */
11869 @VisibleForTesting
11870 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011871 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080011872 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011873 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080011874 final SparseArray<Set<Integer>> uids =
11875 createUidsFromOemNetworkPreferences(preference);
11876 for (int i = 0; i < uids.size(); i++) {
11877 final int key = uids.keyAt(i);
11878 final Set<Integer> value = uids.valueAt(i);
11879 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
11880 // No need to add an nri without any requests.
11881 if (0 == nri.mRequests.size()) {
11882 continue;
11883 }
11884 nris.add(nri);
11885 }
11886
11887 return nris;
11888 }
11889
11890 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
11891 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070011892 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080011893 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080011894 final List<UserHandle> users =
11895 mContext.getSystemService(UserManager.class).getUserHandles(true);
11896 if (null == users || users.size() == 0) {
11897 if (VDBG || DDBG) {
11898 log("No users currently available for setting the OEM network preference.");
11899 }
James Mattisb6b6a432021-06-01 22:30:36 -070011900 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080011901 }
James Mattis45d81842021-01-10 14:24:24 -080011902 for (final Map.Entry<String, Integer> entry :
11903 preference.getNetworkPreferences().entrySet()) {
11904 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070011905 // Add the rules for all users as this policy is device wide.
11906 for (final UserHandle user : users) {
11907 try {
11908 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
11909 if (!prefToUids.contains(pref)) {
11910 prefToUids.put(pref, new ArraySet<>());
11911 }
11912 prefToUids.get(pref).add(uid);
11913 } catch (PackageManager.NameNotFoundException e) {
11914 // Although this may seem like an error scenario, it is ok that uninstalled
11915 // packages are sent on a network preference as the system will watch for
11916 // package installations associated with this network preference and update
11917 // accordingly. This is done to minimize race conditions on app install.
11918 continue;
James Mattis45d81842021-01-10 14:24:24 -080011919 }
James Mattis45d81842021-01-10 14:24:24 -080011920 }
11921 }
James Mattisb6b6a432021-06-01 22:30:36 -070011922 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080011923 }
11924
11925 private NetworkRequestInfo createNriFromOemNetworkPreferences(
11926 @OemNetworkPreferences.OemNetworkPreference final int preference,
11927 @NonNull final Set<Integer> uids) {
11928 final List<NetworkRequest> requests = new ArrayList<>();
11929 // Requests will ultimately be evaluated by order of insertion therefore it matters.
11930 switch (preference) {
11931 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
11932 requests.add(createUnmeteredNetworkRequest());
11933 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070011934 requests.add(createDefaultInternetRequestForTransport(
11935 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080011936 break;
11937 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
11938 requests.add(createUnmeteredNetworkRequest());
11939 requests.add(createOemPaidNetworkRequest());
11940 break;
11941 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
11942 requests.add(createOemPaidNetworkRequest());
11943 break;
11944 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
11945 requests.add(createOemPrivateNetworkRequest());
11946 break;
James Mattisfa270db2021-05-31 17:11:10 -070011947 case OEM_NETWORK_PREFERENCE_TEST:
11948 requests.add(createUnmeteredNetworkRequest());
11949 requests.add(createTestNetworkRequest());
11950 requests.add(createDefaultRequest());
11951 break;
11952 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
11953 requests.add(createTestNetworkRequest());
11954 break;
James Mattis45d81842021-01-10 14:24:24 -080011955 default:
11956 // This should never happen.
11957 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
11958 + " called with invalid preference of " + preference);
11959 }
11960
James Mattisfa270db2021-05-31 17:11:10 -070011961 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090011962 for (final int uid : uids) {
11963 ranges.add(new UidRange(uid, uid));
11964 }
11965 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080011966 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080011967 }
11968
11969 private NetworkRequest createUnmeteredNetworkRequest() {
11970 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11971 .addCapability(NET_CAPABILITY_NOT_METERED)
11972 .addCapability(NET_CAPABILITY_VALIDATED);
11973 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
11974 }
11975
11976 private NetworkRequest createOemPaidNetworkRequest() {
11977 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11978 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11979 .addCapability(NET_CAPABILITY_OEM_PAID)
11980 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11981 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11982 }
11983
11984 private NetworkRequest createOemPrivateNetworkRequest() {
11985 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
11986 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11987 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
11988 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11989 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11990 }
11991
11992 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070011993 final NetworkCapabilities netcap = new NetworkCapabilities();
11994 netcap.addCapability(NET_CAPABILITY_INTERNET);
11995 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
11996 return netcap;
11997 }
11998
11999 private NetworkRequest createTestNetworkRequest() {
12000 final NetworkCapabilities netcap = new NetworkCapabilities();
12001 netcap.clearAll();
12002 netcap.addTransportType(TRANSPORT_TEST);
12003 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080012004 }
James Mattis47db0582021-01-01 14:13:35 -080012005 }
markchien738ad912021-12-09 18:15:45 +080012006
12007 @Override
12008 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
12009 enforceNetworkStackOrSettingsPermission();
12010
12011 try {
12012 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012013 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012014 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012015 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012016 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012017 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012018 throw new IllegalStateException(e);
12019 }
12020 }
12021
12022 @Override
12023 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
12024 enforceNetworkStackOrSettingsPermission();
12025
12026 try {
12027 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012028 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012029 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012030 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012031 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012032 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012033 throw new IllegalStateException(e);
12034 }
12035 }
markchiene1561fa2021-12-09 22:00:56 +080012036
12037 @Override
markchien3c04e662022-03-22 16:29:56 +080012038 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080012039 enforceNetworkStackOrSettingsPermission();
12040
markchien3c04e662022-03-22 16:29:56 +080012041 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
12042 int firewallRule = getFirewallRuleType(chain, rule);
12043
12044 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
12045 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
12046 }
12047
markchiene1561fa2021-12-09 22:00:56 +080012048 try {
markchien3c04e662022-03-22 16:29:56 +080012049 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012050 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080012051 throw new IllegalStateException(e);
12052 }
12053 }
markchien98a6f952022-01-13 23:43:53 +080012054
Motomu Utsumi900b8062023-01-19 16:16:49 +090012055 @Override
12056 public int getUidFirewallRule(final int chain, final int uid) {
12057 enforceNetworkStackOrSettingsPermission();
12058 return mBpfNetMaps.getUidRule(chain, uid);
12059 }
12060
markchien3c04e662022-03-22 16:29:56 +080012061 private int getFirewallRuleType(int chain, int rule) {
12062 final int defaultRule;
12063 switch (chain) {
12064 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000012065 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
12066 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000012067 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080012068 defaultRule = FIREWALL_RULE_ALLOW;
12069 break;
12070 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
12071 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
12072 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
12073 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
12074 defaultRule = FIREWALL_RULE_DENY;
12075 break;
12076 default:
12077 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
12078 }
12079 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
12080
12081 return rule;
12082 }
12083
Motomu Utsumied1848c2023-03-28 18:08:12 +090012084 private void closeSocketsForFirewallChainLocked(final int chain)
12085 throws ErrnoException, SocketException, InterruptedIOException {
12086 if (mBpfNetMaps.isFirewallAllowList(chain)) {
12087 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
12088 // So, close all non-system socket owned by uids that are not explicitly allowed
12089 Set<Range<Integer>> ranges = new ArraySet<>();
12090 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
12091 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
12092 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
12093 } else {
12094 // Denylist means the firewall allows all by default, uids must be explicitly denied
12095 // So, close socket owned by uids that are explicitly denied
12096 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
12097 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
12098 }
12099 }
12100
markchien98a6f952022-01-13 23:43:53 +080012101 @Override
12102 public void setFirewallChainEnabled(final int chain, final boolean enable) {
12103 enforceNetworkStackOrSettingsPermission();
12104
12105 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012106 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012107 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080012108 throw new IllegalStateException(e);
12109 }
Motomu Utsumied1848c2023-03-28 18:08:12 +090012110
12111 if (SdkLevel.isAtLeastU() && enable) {
12112 try {
12113 closeSocketsForFirewallChainLocked(chain);
12114 } catch (ErrnoException | SocketException | InterruptedIOException e) {
12115 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
12116 }
12117 }
markchien98a6f952022-01-13 23:43:53 +080012118 }
12119
markchien00a0bed2022-01-13 23:46:13 +080012120 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012121 public boolean getFirewallChainEnabled(final int chain) {
12122 enforceNetworkStackOrSettingsPermission();
12123
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000012124 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012125 }
12126
12127 @Override
markchien00a0bed2022-01-13 23:46:13 +080012128 public void replaceFirewallChain(final int chain, final int[] uids) {
12129 enforceNetworkStackOrSettingsPermission();
12130
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000012131 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080012132 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080012133
12134 @Override
12135 public IBinder getCompanionDeviceManagerProxyService() {
12136 enforceNetworkStackPermission(mContext);
12137 return mCdmps;
12138 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070012139}