blob: f5790936cf31b2f5a623b1e14fec796ac860fff3 [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;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700321import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700322import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900323import java.net.InetSocketAddress;
Motomu Utsumia20f7602023-03-16 17:04:21 +0900324import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700325import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700326import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700327import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700328import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800329import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900330import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800331import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700332import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700333import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700334import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700335import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900336import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700337import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900338import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600339import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900340import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600341import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900342import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800343
344/**
345 * @hide
346 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800347public class ConnectivityService extends IConnectivityManager.Stub
348 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900349 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800350
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900351 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900352 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900353 private static final String NETWORK_ARG = "networks";
354 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800355 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900356
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900357 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900358 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
359 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800360
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900361 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700362
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100363 /**
364 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
365 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800366 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100367 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
368 * (preferably via runtime resource overlays).
369 */
370 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
371 "http://connectivitycheck.gstatic.com/generate_204";
372
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700373 // TODO: create better separation between radio types and network types
374
Robert Greenwalt2034b912009-08-12 16:08:25 -0700375 // how long to wait before switching back to a radio's default network
376 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
377 // system property that can override the above value
378 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
379 "android.telephony.apn-restore";
380
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900381 // How long to wait before putting up a "This network doesn't have an Internet connection,
382 // connect anyway?" dialog after the user selects a network that doesn't validate.
383 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
384
Chalard Jean5fb43c72022-09-08 19:03:14 +0900385 // How long to wait before considering that a network is bad in the absence of any form
386 // of connectivity (valid, partial, captive portal). If none has been detected after this
387 // delay, the stack considers this network bad, which may affect how it's handled in ranking
388 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900389 // Timeout in case the "actively prefer bad wifi" feature is on
390 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
391 // Timeout in case the "actively prefer bad wifi" feature is off
392 private static final int DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900393
junyulai0ac374f2020-12-14 18:41:52 +0800394 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900395 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
396 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800397 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700398
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800399 // Delimiter used when creating the broadcast delivery group for sending
400 // CONNECTIVITY_ACTION broadcast.
401 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
402
he_won.hwang881307a2022-03-15 21:23:52 +0900403 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900404 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900405
Daniel Brightf9e945b2020-06-15 16:10:01 -0700406 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900407 @VisibleForTesting
408 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700409
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900410 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700411 @VisibleForTesting
412 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900413
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900414 @VisibleForTesting
415 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800416 @VisibleForTesting
417 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900418 // True if the cell radio of the device is capable of time-sharing.
419 @VisibleForTesting
420 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900421
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800422 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800423 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800424 private final int mReleasePendingIntentDelayMs;
425
Chalard Jean46bfbf02022-02-02 00:56:25 +0900426 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900427
Motomu Utsumif360aa62023-01-30 17:52:20 +0900428 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700429
Chalard Jean9473c982021-07-29 20:03:04 +0900430 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800431 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700432 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800433 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700434
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900435 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700436
junyulaif2c67e42018-08-07 19:50:45 +0800437 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000438 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
439 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800440 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900441 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800442
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900443 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900444 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000445 // The Context is created for UserHandle.ALL.
446 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900447 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900448 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700449 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700450 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800451
Chenbo Feng15416292018-11-08 17:36:21 -0800452 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800453 protected IDnsResolver mDnsResolver;
454 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800455 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700456 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900457 private final NetworkStatsManager mStatsManager;
458 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800459 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700460
Benedict Wong493e04b2018-11-09 14:45:34 -0800461 /**
462 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
463 * instances.
464 */
465 @GuardedBy("mTNSLock")
466 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800467 private final CompanionDeviceManagerProxyService mCdmps;
Benedict Wong493e04b2018-11-09 14:45:34 -0800468
469 private final Object mTNSLock = new Object();
470
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700471 private String mCurrentTcpBufferSizes;
472
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900473 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000474 new Class[] {
475 ConnectivityService.class,
476 NetworkAgent.class,
477 NetworkAgentInfo.class,
478 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900479
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500480 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400481 // Tear down networks that have no chance (e.g. even if validated) of becoming
482 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500483 // all networks have been rematched against all NetworkRequests.
484 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400485 // Don't reap networks. This should be passed when some networks have not yet been
486 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500487 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900488 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500489
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900490 private enum UnneededFor {
491 LINGER, // Determine whether this network is unneeded and should be lingered.
492 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
493 }
494
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700495 /**
paulhuaa0743d2021-05-26 21:56:03 +0800496 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800497 * should have priority. The order is passed to netd which will use it together
498 * with UID ranges to generate the corresponding IP rule. This serves to
499 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800500 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800501 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000502 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800503 *
paulhu48291862021-07-14 14:53:57 +0800504 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
505 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800506 */
paulhu48291862021-07-14 14:53:57 +0800507 // Used when sending to netd to code for "no order".
508 static final int PREFERENCE_ORDER_NONE = 0;
509 // Order for requests that don't code for a per-app preference. As it is
510 // out of the valid range, the corresponding order should be
511 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800512 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800513 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800514 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800515 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
516 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800517 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800518 static final int PREFERENCE_ORDER_OEM = 10;
519 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800520 // See {@link #setProfileNetworkPreference}.
521 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800522 static final int PREFERENCE_ORDER_PROFILE = 20;
523 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800524 // better scores are connected.
525 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800526 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800527 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900528 // Preference order that signifies the network shouldn't be set as a default network for
529 // the UIDs, only give them access to it. TODO : replace this with a boolean
530 // in NativeUidRangeConfig
531 @VisibleForTesting
532 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
533 // Bound for the lowest valid preference order.
534 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800535
536 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700537 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700538 * from one net to another. Clear happens when we get a new
539 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
540 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700541 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700542 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700543
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700544 /**
545 * used internally to reload global proxy settings
546 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700547 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700548
Robert Greenwalt34848c02011-03-25 13:09:25 -0700549 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400550 * PAC manager has received new port.
551 */
552 private static final int EVENT_PROXY_HAS_CHANGED = 16;
553
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700554 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900555 * used internally when registering NetworkProviders
556 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700557 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900558 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700559
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700560 /**
561 * used internally when registering NetworkAgents
562 * obj = Messenger
563 */
564 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
565
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700566 /**
567 * used to add a network request
568 * includes a NetworkRequestInfo
569 */
570 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
571
572 /**
573 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900574 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700575 * cancel it.
576 * includes a NetworkRequestInfo
577 */
578 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
579
580 /**
581 * used to add a network listener - no request
582 * includes a NetworkRequestInfo
583 */
584 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
585
586 /**
587 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400588 * arg1 = UID of caller
589 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700590 */
591 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
592
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700593 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900594 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700595 * obj = Messenger
596 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900597 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700598
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700599 /**
600 * used internally to expire a wakelock when transitioning
601 * from one net to another. Expire happens when we fail to find
602 * a new network (typically after 1 minute) -
603 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
604 * a replacement network.
605 */
606 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
607
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700608 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800609 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400610 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800611 */
612 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
613
614 /**
615 * used to remove a pending intent and its associated network request.
616 * arg1 = UID of caller
617 * obj = PendingIntent
618 */
619 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
620
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900621 /**
622 * used to specify whether a network should be used even if unvalidated.
623 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
624 * arg2 = whether to remember this choice in the future (1 or 0)
625 * obj = network
626 */
627 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
628
629 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700630 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900631 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700632 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900633
Paul Jensenc8873fc2015-06-17 14:15:39 -0400634 /**
635 * used to add a network listener with a pending intent
636 * obj = NetworkRequestInfo
637 */
638 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
639
Hugo Benichid6b510a2017-04-06 17:22:18 +0900640 /**
641 * used to specify whether a network should not be penalized when it becomes unvalidated.
642 */
643 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
644
645 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700646 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900647 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700648 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900649
Erik Kline31b4a9e2018-01-11 21:07:29 +0900650 // Handle changes in Private DNS settings.
651 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
652
dalyk1720e542018-03-05 12:42:22 -0500653 // Handle private DNS validation status updates.
654 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
655
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900656 /**
657 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
658 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800659 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
660 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
661 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900662 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900663 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900664
665 /**
666 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
667 * config was resolved.
668 * obj = PrivateDnsConfig
669 * arg2 = netid
670 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900671 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900672
673 /**
674 * Request ConnectivityService display provisioning notification.
675 * arg1 = Whether to make the notification visible.
676 * arg2 = NetID.
677 * obj = Intent to be launched when notification selected by user, null if !arg1.
678 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900679 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900680
681 /**
lucaslin2240ef62019-03-12 13:08:03 +0800682 * Used to specify whether a network should be used even if connectivity is partial.
683 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
684 * false)
685 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
686 * obj = network
687 */
lucaslin444d43a2020-02-20 16:56:59 +0800688 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800689
690 /**
lucasline117e2e2019-10-22 18:27:33 +0800691 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
692 * Both of the arguments are bitmasks, and the value of bits come from
693 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900694 * arg1 = unused
695 * arg2 = netId
696 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800697 */
lucaslin444d43a2020-02-20 16:56:59 +0800698 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800699
700 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900701 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
702 * arg1 = unused
703 * arg2 = netId
704 * obj = captive portal data
705 */
lucaslin444d43a2020-02-20 16:56:59 +0800706 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900707
708 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900709 * Used by setRequireVpnForUids.
710 * arg1 = whether the specified UID ranges are required to use a VPN.
711 * obj = Array of UidRange objects.
712 */
713 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
714
715 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900716 * Used internally when setting the default networks for OemNetworkPreferences.
717 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800718 */
719 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
720
721 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800722 * Used to indicate the system default network becomes active.
723 */
724 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
725
726 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900727 * Used internally when setting a network preference for a user profile.
728 * obj = Pair<ProfileNetworkPreference, Listener>
729 */
730 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
731
732 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000733 * Event to specify that reasons for why an uid is blocked changed.
734 * arg1 = uid
735 * arg2 = blockedReasons
736 */
737 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
738
739 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900740 * Event to register a new network offer
741 * obj = NetworkOffer
742 */
743 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
744
745 /**
746 * Event to unregister an existing network offer
747 * obj = INetworkOfferCallback
748 */
749 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
750
751 /**
paulhu51f77dc2021-06-07 02:34:20 +0000752 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
753 */
754 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
755
756 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800757 * Event to set temporary allow bad wifi within a limited time to override
758 * {@code config_networkAvoidBadWifi}.
759 */
760 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
761
762 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100763 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
764 */
765 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
766
767 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900768 * The initial evaluation period is over for this network.
769 *
770 * If no form of connectivity has been found on this network (valid, partial, captive portal)
771 * then the stack will now consider it to have been determined bad.
772 */
773 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
774
775 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000776 * Used internally when the user does not want the network from captive portal app.
777 * obj = Network
778 */
779 private static final int EVENT_USER_DOES_NOT_WANT = 58;
780
781 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000782 * Event to set VPN as preferred network for specific apps.
783 * obj = VpnNetworkPreferenceInfo
784 */
785 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
786
787 /**
chiachangwange0192a72023-02-06 13:25:01 +0000788 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
789 */
790 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
791
792 /**
Mark Fasheh7501e762023-05-04 20:23:11 +0000793 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
794 */
795 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
796
797 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900798 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
799 * should be shown.
800 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900801 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900802
803 /**
804 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
805 * should be hidden.
806 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900807 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900808
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800809 /**
810 * The maximum alive time to allow bad wifi configuration for testing.
811 */
812 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
813
Patrick Rohr2857ac42022-01-21 14:58:16 +0100814 /**
chiachangwange0192a72023-02-06 13:25:01 +0000815 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
816 * testing.
817 */
818 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
819
820 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100821 * The priority of the tc police rate limiter -- smaller value is higher priority.
822 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
823 */
824 private static final short TC_PRIO_POLICE = 1;
825
826 /**
827 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
828 */
829 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700830 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100831
Hugo Benichi47011212017-03-30 10:46:05 +0900832 private static String eventName(int what) {
833 return sMagicDecoderRing.get(what, Integer.toString(what));
834 }
835
paulhua10d8212020-11-10 15:32:56 +0800836 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900837 final DnsResolverServiceManager dsm = context.getSystemService(
838 DnsResolverServiceManager.class);
839 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800840 }
841
Cody Kesting73708bf2019-12-18 10:57:50 -0800842 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900843 @VisibleForTesting
844 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700845 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700846 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700847 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700848 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800849 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
850 @VisibleForTesting
851 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
852
Erik Kline32120082017-12-13 19:40:49 +0900853 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900854 @VisibleForTesting
855 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700856
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400857 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800858 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400859
Chalard Jean46bfbf02022-02-02 00:56:25 +0900860 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800861 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700862
Chalard Jean5d70ba42018-06-07 16:44:04 +0900863 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
864 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000865 @VisibleForTesting
866 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400867
Erik Kline05f2b402015-04-30 12:58:40 +0900868 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700869
Chalard Jean46bfbf02022-02-02 00:56:25 +0900870 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400871
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700872 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900873 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700874
Valentin Iftime9fa35092019-09-24 13:32:13 +0200875 private Set<String> mWolSupportedInterfaces;
876
Roshan Pius08c94fb2020-01-16 12:17:17 -0800877 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800878 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800879 private final AppOpsManager mAppOpsManager;
880
881 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400882
chiachangwang3d60bac2023-01-17 14:38:08 +0000883 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900884 private final QosCallbackTracker mQosCallbackTracker;
885 private final NetworkNotificationManager mNotifier;
886 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900887
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700888 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800889 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700890
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900891 // Sequence number for NetworkProvider IDs.
892 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
893 NetworkProvider.FIRST_PROVIDER_ID);
894
Erik Klineedf878b2015-07-09 18:24:03 +0900895 // NetworkRequest activity String log entries.
896 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
897 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
898
Hugo Benichid159fdd2016-07-11 11:05:12 +0900899 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900900 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900901 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
902
Hugo Benichi47011212017-03-30 10:46:05 +0900903 private static final int MAX_WAKELOCK_LOGS = 20;
904 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900905 private int mTotalWakelockAcquisitions = 0;
906 private int mTotalWakelockReleases = 0;
907 private long mTotalWakelockDurationMs = 0;
908 private long mMaxWakelockDurationMs = 0;
909 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900910
Hugo Benichi208c0102016-07-28 17:53:06 +0900911 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900912
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700913 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900914 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700915
Erik Kline95ecfee2016-10-02 18:02:14 +0900916 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900917 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900918
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900919 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800920 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
921 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800922
Patrick Rohr2857ac42022-01-21 14:58:16 +0100923 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
924 // configured via {@link
925 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
926 // Only the handler thread is allowed to access this field.
927 private long mIngressRateLimit = -1;
928
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900929 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
930 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900931 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900932 @GuardedBy("mSelfCertifiedCapabilityCache")
933 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
934 mSelfCertifiedCapabilityCache = new HashMap<>();
935
Robert Greenwalt802c1102014-06-02 15:32:02 -0700936 /**
937 * Implements support for the legacy "one network per network type" model.
938 *
939 * We used to have a static array of NetworkStateTrackers, one for each
940 * network type, but that doesn't work any more now that we can have,
941 * for example, more that one wifi network. This class stores all the
942 * NetworkAgentInfo objects that support a given type, but the legacy
943 * API will only see the first one.
944 *
945 * It serves two main purposes:
946 *
947 * 1. Provide information about "the network for a given type" (since this
948 * API only supports one).
949 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
950 * the first network for a given type changes, or if the default network
951 * changes.
952 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900953 @VisibleForTesting
954 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900955
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900956 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900957 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900958
Robert Greenwalt802c1102014-06-02 15:32:02 -0700959 /**
960 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
961 * Each list holds references to all NetworkAgentInfos that are used to
962 * satisfy requests for that network type.
963 *
964 * This array is built out at startup such that an unsupported network
965 * doesn't get an ArrayList instance, making this a tristate:
966 * unsupported, supported but not active and active.
967 *
968 * The actual lists are populated when we scan the network types that
969 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900970 *
971 * Threading model:
972 * - addSupportedType() is only called in the constructor
973 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
974 * They are therefore not thread-safe with respect to each other.
975 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
976 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900977 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900978 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700979 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900980 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900981 @NonNull
982 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700983
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900984 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
985 // an entry have no timer (equivalent to -1). Lazily loaded.
986 @NonNull
987 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
988
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900989 LegacyTypeTracker(@NonNull ConnectivityService service) {
990 mService = service;
991 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700992 }
993
Chiachang Wang3bc52762021-11-25 14:17:57 +0800994 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
995 // addressed.
996 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900997 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
998 final PackageManager pm = ctx.getPackageManager();
999 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1000 addSupportedType(TYPE_WIFI);
1001 }
1002 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1003 addSupportedType(TYPE_WIFI_P2P);
1004 }
1005 if (tm.isDataCapable()) {
1006 // Telephony does not have granular support for these types: they are either all
1007 // supported, or none is supported
1008 addSupportedType(TYPE_MOBILE);
1009 addSupportedType(TYPE_MOBILE_MMS);
1010 addSupportedType(TYPE_MOBILE_SUPL);
1011 addSupportedType(TYPE_MOBILE_DUN);
1012 addSupportedType(TYPE_MOBILE_HIPRI);
1013 addSupportedType(TYPE_MOBILE_FOTA);
1014 addSupportedType(TYPE_MOBILE_IMS);
1015 addSupportedType(TYPE_MOBILE_CBS);
1016 addSupportedType(TYPE_MOBILE_IA);
1017 addSupportedType(TYPE_MOBILE_EMERGENCY);
1018 }
1019 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1020 addSupportedType(TYPE_BLUETOOTH);
1021 }
1022 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1023 // TYPE_PROXY is only used on Wear
1024 addSupportedType(TYPE_PROXY);
1025 }
1026 // Ethernet is often not specified in the configs, although many devices can use it via
1027 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001028 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001029 addSupportedType(TYPE_ETHERNET);
1030 }
1031
1032 // Always add TYPE_VPN as a supported type
1033 addSupportedType(TYPE_VPN);
1034 }
1035
1036 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001037 if (mTypeLists[type] != null) {
1038 throw new IllegalStateException(
1039 "legacy list for type " + type + "already initialized");
1040 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001041 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001042 }
1043
Robert Greenwalt802c1102014-06-02 15:32:02 -07001044 public boolean isTypeSupported(int type) {
1045 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1046 }
1047
1048 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001049 synchronized (mTypeLists) {
1050 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1051 return mTypeLists[type].get(0);
1052 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001053 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001054 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001055 }
1056
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001057 public int getRestoreTimerForType(int type) {
1058 synchronized (mTypeLists) {
1059 if (mRestoreTimers == null) {
1060 mRestoreTimers = loadRestoreTimers();
1061 }
1062 return mRestoreTimers.getOrDefault(type, -1);
1063 }
1064 }
1065
1066 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1067 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001068 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001069 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1070 for (final String config : configs) {
1071 final String[] splits = TextUtils.split(config, ",");
1072 if (splits.length != 2) {
1073 logwtf("Invalid restore timer token count: " + config);
1074 continue;
1075 }
1076 try {
1077 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1078 } catch (NumberFormatException e) {
1079 logwtf("Invalid restore timer number format: " + config, e);
1080 }
1081 }
1082 return ret;
1083 }
1084
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001085 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001086 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001087 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001088 log("Sending " + state
1089 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001090 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001091 }
1092 }
1093
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001094 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1095 // network type, to preserve previous behaviour.
1096 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1097 if (vpnNai != mService.getLegacyLockdownNai()) return;
1098
1099 if (vpnNai.declaredUnderlyingNetworks == null
1100 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1101 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1102 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1103 return;
1104 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001105 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001106 vpnNai.declaredUnderlyingNetworks[0]);
1107 if (underlyingNai == null) return;
1108
1109 final int type = underlyingNai.networkInfo.getType();
1110 final DetailedState state = DetailedState.CONNECTED;
1111 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1112 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1113 }
1114
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001115 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001116 public void add(int type, NetworkAgentInfo nai) {
1117 if (!isTypeSupported(type)) {
1118 return; // Invalid network type.
1119 }
1120 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1121
1122 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1123 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001124 return;
1125 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001126 synchronized (mTypeLists) {
1127 list.add(nai);
1128 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001129
Chalard Jean5b409c72021-02-04 13:12:59 +09001130 // Send a broadcast if this is the first network of its type or if it's the default.
1131 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001132
1133 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1134 // to preserve previous behaviour.
1135 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001136 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001137 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1138 mService.sendLegacyNetworkBroadcast(nai, state, type);
1139 }
1140
1141 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1142 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001143 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001144 }
1145
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001146 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001147 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001148 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1149 if (list == null || list.isEmpty()) {
1150 return;
1151 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001152 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001153
Hugo Benichi389633f2016-06-21 09:48:07 +09001154 synchronized (mTypeLists) {
1155 if (!list.remove(nai)) {
1156 return;
1157 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001158 }
1159
Lorenzo Colitti49767722015-05-01 00:30:10 +09001160 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001161 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1162 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001163 }
1164
1165 if (!list.isEmpty() && wasFirstNetwork) {
1166 if (DBG) log("Other network available for type " + type +
1167 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001168 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001169 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001170 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001171 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001172 }
1173 }
1174
1175 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001176 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1177 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001178 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001179 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001180 }
1181 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001182
Chalard Jean46bfbf02022-02-02 00:56:25 +09001183 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001184 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001185 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001186 final DetailedState state = nai.networkInfo.getDetailedState();
1187 for (int type = 0; type < mTypeLists.length; type++) {
1188 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001189 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001190 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001191 if (isFirst || contains && isDefault) {
1192 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001193 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001194 }
1195 }
1196 }
1197
Robert Greenwalt94e22142014-07-30 16:31:24 -07001198 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001199 pw.println("mLegacyTypeTracker:");
1200 pw.increaseIndent();
1201 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001202 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001203 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001204 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001205 pw.println();
1206 pw.println("Current state:");
1207 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001208 synchronized (mTypeLists) {
1209 for (int type = 0; type < mTypeLists.length; type++) {
1210 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1211 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001212 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001213 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001214 }
1215 }
1216 pw.decreaseIndent();
1217 pw.decreaseIndent();
1218 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001219 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001220 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001221 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001222
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001223 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001224 /**
1225 * Helper class which parses out priority arguments and dumps sections according to their
1226 * priority. If priority arguments are omitted, function calls the legacy dump command.
1227 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001228 private class LocalPriorityDump {
1229 private static final String PRIORITY_ARG = "--dump-priority";
1230 private static final String PRIORITY_ARG_HIGH = "HIGH";
1231 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1232
1233 LocalPriorityDump() {}
1234
1235 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1236 doDump(fd, pw, new String[] {DIAG_ARG});
1237 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001238 }
1239
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001240 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1241 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001242 }
1243
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001244 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1245 if (args == null) {
1246 dumpNormal(fd, pw, args);
1247 return;
1248 }
1249
1250 String priority = null;
1251 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1252 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1253 argIndex++;
1254 priority = args[argIndex];
1255 }
1256 }
1257
1258 if (PRIORITY_ARG_HIGH.equals(priority)) {
1259 dumpHigh(fd, pw);
1260 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1261 dumpNormal(fd, pw, args);
1262 } else {
1263 // ConnectivityService publishes binder service using publishBinderService() with
1264 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001265 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1266 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001267 // TODO: Integrate into signal dump.
1268 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001269 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001270 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001271 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001272
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001273 /**
1274 * Dependencies of ConnectivityService, for injection in tests.
1275 */
1276 @VisibleForTesting
1277 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001278 public int getCallingUid() {
1279 return Binder.getCallingUid();
1280 }
1281
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001282 /**
1283 * Get system properties to use in ConnectivityService.
1284 */
1285 public MockableSystemProperties getSystemProperties() {
1286 return new MockableSystemProperties();
1287 }
1288
1289 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001290 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1291 */
1292 public ConnectivityResources getResources(@NonNull Context ctx) {
1293 return new ConnectivityResources(ctx);
1294 }
1295
1296 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001297 * Create a HandlerThread to use in ConnectivityService.
1298 */
1299 public HandlerThread makeHandlerThread() {
1300 return new HandlerThread("ConnectivityServiceThread");
1301 }
1302
1303 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001304 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001305 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001306 public NetworkStackClientBase getNetworkStack() {
1307 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001308 }
1309
1310 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001311 * @see ProxyTracker
1312 */
1313 public ProxyTracker makeProxyTracker(@NonNull Context context,
1314 @NonNull Handler connServiceHandler) {
1315 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1316 }
1317
1318 /**
1319 * @see NetIdManager
1320 */
1321 public NetIdManager makeNetIdManager() {
1322 return new NetIdManager();
1323 }
1324
1325 /**
1326 * @see NetworkUtils#queryUserAccess(int, int)
1327 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001328 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1329 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001330 }
1331
1332 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001333 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1334 * requires CAP_NET_ADMIN, which the unit tests do not have.
1335 */
1336 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1337 InetSocketAddress remote) {
1338 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1339 }
1340
1341 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001342 * @see MultinetworkPolicyTracker
1343 */
1344 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1345 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1346 return new MultinetworkPolicyTracker(c, h, r);
1347 }
1348
Aaron Huang330a4c02020-10-27 03:36:19 +08001349 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001350 * @see AutomaticOnOffKeepaliveTracker
1351 */
1352 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1353 @NonNull Context c, @NonNull Handler h) {
1354 return new AutomaticOnOffKeepaliveTracker(c, h);
1355 }
1356
1357 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001358 * @see BatteryStatsManager
1359 */
1360 public void reportNetworkInterfaceForTransports(Context context, String iface,
1361 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001362 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001363 context.getSystemService(BatteryStatsManager.class);
1364 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1365 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001366
1367 public boolean getCellular464XlatEnabled() {
1368 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1369 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001370
1371 /**
1372 * @see PendingIntent#intentFilterEquals
1373 */
1374 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1375 return a.intentFilterEquals(b);
1376 }
1377
1378 /**
1379 * @see LocationPermissionChecker
1380 */
1381 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1382 return new LocationPermissionChecker(context);
1383 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001384
1385 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001386 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001387 *
1388 * This method returns null in versions before T, where carrier privilege
1389 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001390 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001391 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001392 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1393 @NonNull final Context context, @NonNull final TelephonyManager tm) {
1394 if (SdkLevel.isAtLeastT()) {
1395 return new CarrierPrivilegeAuthenticator(context, tm);
1396 } else {
1397 return null;
1398 }
1399 }
1400
1401 /**
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001402 * @see DeviceConfigUtils#isFeatureEnabled
1403 */
Motomu Utsumi6f4d8062023-04-21 12:35:22 +09001404 public boolean isFeatureEnabled(Context context, String name) {
1405 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING, name,
1406 TETHERING_MODULE_NAME, false /* defaultValue */);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001407 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001408
1409 /**
1410 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001411 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001412 * @return BpfNetMaps implementation.
1413 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001414 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1415 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001416 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001417
1418 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001419 * @see ClatCoordinator
1420 */
1421 public ClatCoordinator getClatCoordinator(INetd netd) {
1422 return new ClatCoordinator(
1423 new ClatCoordinator.Dependencies() {
1424 @NonNull
1425 public INetd getNetd() {
1426 return netd;
1427 }
1428 });
1429 }
1430
1431 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001432 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1433 */
1434 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1435 final InterfaceParams params = InterfaceParams.getByName(iface);
1436 if (params == null) {
1437 // the interface might have disappeared.
1438 logw("Failed to get interface params for interface " + iface);
1439 return;
1440 }
1441 try {
1442 // converting rateInBytesPerSecond from long to int is safe here because the
1443 // setting's range is limited to INT_MAX.
1444 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001445 Log.i(TAG,
1446 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001447 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1448 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1449 } catch (IOException e) {
1450 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1451 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1452 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1453 + ") failure: ", e);
1454 }
1455 }
1456
1457 /**
1458 * Wraps {@link TcUtils#tcFilterDelDev}
1459 */
1460 public void disableIngressRateLimit(String iface) {
1461 final InterfaceParams params = InterfaceParams.getByName(iface);
1462 if (params == null) {
1463 // the interface might have disappeared.
1464 logw("Failed to get interface params for interface " + iface);
1465 return;
1466 }
1467 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001468 Log.i(TAG,
1469 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001470 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1471 } catch (IOException e) {
1472 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1473 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1474 }
1475 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001476
1477 /**
1478 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1479 */
1480 // TODO: when available in all active branches:
1481 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1482 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1483 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1484 return BroadcastOptionsShimImpl.newInstance(options);
1485 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001486
1487 /**
1488 * Wrapper method for
1489 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1490 *
1491 * @param changeId The ID of the compatibility change in question.
1492 * @param packageName The package name of the app in question.
1493 * @param user The user that the operation is done for.
1494 * @return {@code true} if the change is enabled for the specified package.
1495 */
1496 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1497 @NonNull final UserHandle user) {
1498 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1499 }
Motomu Utsumia20f7602023-03-16 17:04:21 +09001500
1501 /**
1502 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1503 *
1504 * @param ranges target uid ranges
1505 * @param exemptUids uids to skip close socket
1506 */
1507 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1508 @NonNull final Set<Integer> exemptUids)
1509 throws SocketException, InterruptedIOException, ErrnoException {
1510 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1511 }
Motomu Utsumied1848c2023-03-28 18:08:12 +09001512
1513 /**
1514 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1515 *
1516 * @param ownerUids target uids to close sockets
1517 */
1518 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1519 throws SocketException, InterruptedIOException, ErrnoException {
1520 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1521 }
Chalard Jean1f2b50f2023-05-15 17:26:13 +09001522
1523 /**
1524 * Schedule the evaluation timeout.
1525 *
1526 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1527 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1528 * of these events happen, this time will run out, after which the network is considered
1529 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1530 * on this network and considers it won't provide connectivity. In particular, that means
1531 * it's when the system prefers it to cell if it's wifi and configuration says it should
1532 * prefer bad wifi to cell.
1533 */
1534 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1535 @NonNull final Network network, final long delayMs) {
1536 handler.sendMessageDelayed(
1537 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1538 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001539 }
1540
junyulaie7c7d2a2021-01-26 15:29:15 +08001541 public ConnectivityService(Context context) {
1542 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001543 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1544 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001545 }
1546
1547 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001548 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1549 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001550 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001551
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001552 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001553 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001554 mSystemProperties = mDeps.getSystemProperties();
1555 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001556 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001557 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001558 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1559 // Pass limit - 1 to maintain backward compatibility.
1560 // TODO: Remove the workaround.
1561 mNetworkRequestCounter =
1562 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1563 mSystemNetworkRequestCounter =
1564 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001565
Hugo Benichi208c0102016-07-28 17:53:06 +09001566 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001567 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1568 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001569 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001570 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001571 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001572 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1573 mDefaultNetworkRequests.add(mDefaultRequest);
1574 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001575
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001576 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001577 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001578
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001579 // The default WiFi request is a background request so that apps using WiFi are
1580 // migrated to a better network (typically ethernet) when one comes up, instead
1581 // of staying on WiFi forever.
1582 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1583 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1584
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001585 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1586 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1587 NetworkRequest.Type.BACKGROUND_REQUEST);
1588
Chalard Jean0702f982021-09-16 21:50:07 +09001589 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1590 // TODO: Consider making the timer customizable.
1591 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1592 mCellularRadioTimesharingCapable =
1593 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1594
Paul Hu51f816b2022-08-11 14:43:47 +00001595 mNetd = netd;
1596 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001597 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001598 mPermissionMonitor =
1599 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001600 mHandlerThread.start();
1601 mHandler = new InternalHandler(mHandlerThread.getLooper());
1602 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001603 mConnectivityDiagnosticsHandler =
1604 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001605
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001606 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001607 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001608
junyulaie7c7d2a2021-01-26 15:29:15 +08001609 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001610 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001611 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001612 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001613
Wink Saville32506bc2013-06-29 21:10:57 -07001614 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001615 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001616 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001617 mCarrierPrivilegeAuthenticator =
1618 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001619
Sudheer Shanka9967d462021-03-18 19:09:25 +00001620 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001621 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1622 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001623 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001624
1625 final PowerManager powerManager = (PowerManager) context.getSystemService(
1626 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001627 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001628 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001629
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001630 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1631 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001632 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001633 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001634 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001635 mProtectedNetworks.add(p);
1636 } else {
1637 if (DBG) loge("Ignoring protectedNetwork " + p);
1638 }
1639 }
1640
soma, kawata29444ae2019-05-23 09:30:40 +09001641 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1642
James Mattis02220e22021-03-13 19:27:21 -08001643 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001644 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001645 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001646 final IntentFilter userIntentFilter = new IntentFilter();
1647 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1648 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1649 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1650 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001651
James Mattis02220e22021-03-13 19:27:21 -08001652 // Listen to package add/removes for netd
1653 final IntentFilter packageIntentFilter = new IntentFilter();
1654 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1655 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1656 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1657 packageIntentFilter.addDataScheme("package");
1658 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001659 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001660
lucaslind5c2d072021-02-20 18:59:47 +08001661 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001662
Chalard Jean46bfbf02022-02-02 00:56:25 +09001663 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001664 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001665 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001666 } catch (RemoteException | ServiceSpecificException e) {
1667 loge("Error registering event listener :" + e);
1668 }
1669
Erik Kline05f2b402015-04-30 12:58:40 +09001670 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1671 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001672
chiachangwang7c17c282023-02-02 05:58:59 +00001673 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001674 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001675 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001676
1677 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001678 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001679 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1680 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001681 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001682 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1683 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001684
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001685 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001686 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001687 mNetworkRanker =
1688 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1689
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001690 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001691
Chiachang Wangc1215d32020-10-20 15:38:58 +08001692 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001693 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001694
Chalard Jean28018572020-12-21 18:36:52 +09001695 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1696 // request that doesn't allow fallback to the default network. It should never be visible
1697 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1698 // arguments like the handler or the DnsResolver.
1699 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001700 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001701 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001702 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001703 new LinkProperties(), new NetworkCapabilities(),
1704 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001705 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1706 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001707
1708 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001709 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1710 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1711 // Even if it could, running on S would at least require mocking out the BPF map,
1712 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1713 // the bpf syscall. http://aosp/1907693
1714 if (SdkLevel.isAtLeastT()) {
1715 mDscpPolicyTracker = new DscpPolicyTracker();
1716 }
Tyler Wear72388212021-09-09 14:49:02 -07001717 } catch (ErrnoException e) {
1718 loge("Unable to create DscpPolicyTracker");
1719 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001720
1721 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1722 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001723
1724 if (SdkLevel.isAtLeastT()) {
1725 mCdmps = new CompanionDeviceManagerProxyService(context);
1726 } else {
1727 mCdmps = null;
1728 }
Mark Fasheh7501e762023-05-04 20:23:11 +00001729
1730 if (SdkLevel.isAtLeastU()
1731 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION)) {
1732 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1733 new UidFrozenStateChangedCallback() {
1734 @Override
1735 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1736 if (uids.length != frozenStates.length) {
1737 Log.wtf(TAG, "uids has length " + uids.length
1738 + " but frozenStates has length " + frozenStates.length);
1739 return;
1740 }
1741
1742 final UidFrozenStateChangedArgs args =
1743 new UidFrozenStateChangedArgs(uids, frozenStates);
1744
1745 mHandler.sendMessage(
1746 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1747 }
1748 };
1749
1750 final ActivityManager activityManager =
1751 mContext.getSystemService(ActivityManager.class);
1752 activityManager.registerUidFrozenStateChangedCallback(
1753 (Runnable r) -> r.run(), frozenStateChangedCallback);
1754 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001755 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001756
Xiao Ma0a171c02022-01-23 16:14:51 +00001757 /**
1758 * Check whether or not the device supports Ethernet transport.
1759 */
1760 public static boolean deviceSupportsEthernet(final Context context) {
1761 final PackageManager pm = context.getPackageManager();
1762 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1763 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1764 }
1765
Chalard Jean46adcf32018-04-18 20:18:38 +09001766 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001767 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1768 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001769 }
1770
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001771 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1772 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001773 final NetworkCapabilities netCap = new NetworkCapabilities();
1774 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001775 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001776 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001777 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001778 return netCap;
1779 }
1780
James Mattis45d81842021-01-10 14:24:24 -08001781 private NetworkRequest createDefaultRequest() {
1782 return createDefaultInternetRequestForTransport(
1783 TYPE_NONE, NetworkRequest.Type.REQUEST);
1784 }
1785
lucaslin3ba7cc22022-12-19 02:35:33 +00001786 private NetworkRequest createVpnRequest() {
1787 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1788 .withoutDefaultCapabilities()
1789 .addTransportType(TRANSPORT_VPN)
1790 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1791 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1792 .build();
1793 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1794 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1795 }
1796
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001797 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001798 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001799 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001800 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001801 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001802 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001803 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001804 netCap.addTransportType(transportType);
1805 }
James Mattis45d81842021-01-10 14:24:24 -08001806 return createNetworkRequest(type, netCap);
1807 }
1808
1809 private NetworkRequest createNetworkRequest(
1810 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001811 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001812 }
1813
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001814 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1815 NetworkRequest.Type type) {
1816 final NetworkCapabilities netCap = new NetworkCapabilities();
1817 netCap.clearAll();
1818 netCap.addCapability(capability);
1819 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1820 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1821 }
1822
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001823 // Used only for testing.
1824 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001825 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001826 // changing ContentResolver to make registerContentObserver non-final).
1827 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1828 // by subclassing SettingsObserver.
1829 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001830 void updateAlwaysOnNetworks() {
1831 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001832 }
1833
Erik Kline9a62f012018-03-21 07:18:33 -07001834 // See FakeSettingsProvider comment above.
1835 @VisibleForTesting
1836 void updatePrivateDnsSettings() {
1837 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1838 }
1839
paulhu51f77dc2021-06-07 02:34:20 +00001840 @VisibleForTesting
1841 void updateMobileDataPreferredUids() {
1842 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1843 }
1844
Patrick Rohr2857ac42022-01-21 14:58:16 +01001845 @VisibleForTesting
1846 void updateIngressRateLimit() {
1847 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1848 }
1849
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001850 private void handleAlwaysOnNetworkRequest(
1851 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001852 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001853 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001854 handleAlwaysOnNetworkRequest(networkRequest, enable);
1855 }
1856
1857 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001858 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001859 if (enable == isEnabled) {
1860 return; // Nothing to do.
1861 }
1862
1863 if (enable) {
1864 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001865 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001866 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001867 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001868 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001869 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1870 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001871 }
1872 }
1873
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001874 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001875 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1876 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1877 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1878 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001879 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1880 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001881 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001882 }
1883
paulhu51f77dc2021-06-07 02:34:20 +00001884 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001885 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001886 private void registerSettingsCallbacks() {
1887 // Watch for global HTTP proxy changes.
1888 mSettingsObserver.observe(
1889 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1890 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1891
Chalard Jean46bfbf02022-02-02 00:56:25 +09001892 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001893 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001894 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001895 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1896
Chalard Jean46bfbf02022-02-02 00:56:25 +09001897 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001898 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001899 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001900 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001901
1902 // Watch for mobile data preferred uids changes.
1903 mSettingsObserver.observe(
1904 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1905 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001906
1907 // Watch for ingress rate limit changes.
1908 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01001909 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01001910 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1911 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001912 }
1913
Erik Kline31b4a9e2018-01-11 21:07:29 +09001914 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001915 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1916 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001917 }
1918 }
1919
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001920 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001921 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1922 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001923 return mNextNetworkRequestId++;
1924 }
1925
junyulai74f9a8b2018-06-13 15:00:37 +08001926 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09001927 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08001928 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001929 if (network == null) {
1930 return null;
1931 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001932 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001933 }
1934
1935 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001936 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001937 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001938 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001939 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001940
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001941 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001942 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001943 private NetworkAgentInfo getVpnForUid(int uid) {
1944 synchronized (mNetworkForNetId) {
1945 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1946 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09001947 if (nai.isVPN() && nai.everConnected()
1948 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001949 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001950 }
1951 }
1952 }
1953 return null;
1954 }
1955
Chalard Jean46bfbf02022-02-02 00:56:25 +09001956 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001957 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001958 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001959 final NetworkAgentInfo nai = getVpnForUid(uid);
1960 if (nai != null) return nai.declaredUnderlyingNetworks;
1961 return null;
1962 }
1963
Lorenzo Colittia7574052021-01-19 01:33:05 +09001964 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001965 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001966
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001967 final Network[] networks = getVpnUnderlyingNetworks(uid);
1968 if (networks != null) {
1969 // getUnderlyingNetworks() returns:
1970 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1971 // empty array => the VPN explicitly said "no default network".
1972 // non-empty array => the VPN specified one or more default networks; we use the
1973 // first one.
1974 if (networks.length > 0) {
1975 nai = getNetworkAgentInfoForNetwork(networks[0]);
1976 } else {
1977 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001978 }
1979 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001980 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001981 }
1982
1983 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001984 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001985 */
paulhu7aeba372020-12-30 00:42:19 +08001986 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1987 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001988 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001989 if (ignoreBlocked) {
1990 return false;
1991 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001992 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001993 final long ident = Binder.clearCallingIdentity();
1994 try {
1995 final boolean metered = nc == null ? true : nc.isMetered();
1996 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1997 } finally {
1998 Binder.restoreCallingIdentity(ident);
1999 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002000 }
2001
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002002 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002003 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2004 return;
2005 }
Hugo Benichi47011212017-03-30 10:46:05 +09002006 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002007 synchronized (mBlockedAppUids) {
2008 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002009 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002010 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002011 blocked = false;
2012 } else {
2013 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002014 }
2015 }
Hugo Benichi47011212017-03-30 10:46:05 +09002016 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2017 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2018 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002019 }
2020
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002021 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002022 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2023 return;
2024 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002025 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002026 final int requestId = nri.getActiveRequest() != null
2027 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002028 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002029 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002030 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002031 }
2032
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002033 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002034 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002035 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002036 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002037 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002038 @NonNull
2039 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2040 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002041 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2042 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2043 // but only exists if an app asks about them or requests them. Ensure the requesting app
2044 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002045 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002046 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2047 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2048 null /* extraInfo */);
2049 }
2050 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002051 return filtered;
2052 }
2053
2054 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2055 boolean ignoreBlocked) {
2056 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2057 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002058 }
2059
2060 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002061 * Return NetworkInfo for the active (i.e., connected) network interface.
2062 * It is assumed that at most one network is active at a time. If more
2063 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002064 * @return the info for the active network, or {@code null} if none is
2065 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002066 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002067 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002068 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002069 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002070 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002071 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002072 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2073 if (nai == null) return null;
2074 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2075 maybeLogBlockedNetworkInfo(networkInfo, uid);
2076 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002077 }
2078
Paul Jensen1f567382015-02-13 14:18:39 -05002079 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002080 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002081 public Network getActiveNetwork() {
2082 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002083 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002084 }
2085
2086 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002087 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002088 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002089 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002090 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002091 }
2092
Chalard Jean46bfbf02022-02-02 00:56:25 +09002093 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002094 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002095 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2096 if (vpnNai != null) {
2097 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2098 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2099 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002100 }
Paul Jensen1f567382015-02-13 14:18:39 -05002101 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002102
James Mattis2516da32021-01-31 17:06:19 -08002103 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002104 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2105 ignoreBlocked)) {
2106 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002107 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002108 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002109 }
2110
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002111 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002112 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002113 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002114 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002115 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2116 if (nai == null) return null;
2117 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002118 }
2119
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002120 /** Returns a NetworkInfo object for a network that doesn't exist. */
2121 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2122 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2123 getNetworkTypeName(networkType), "" /* subtypeName */);
2124 info.setIsAvailable(true);
2125 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2126 // background data is restricted.
2127 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2128 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2129 ? DetailedState.BLOCKED
2130 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002131 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2132 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002133 return info;
2134 }
2135
Lorenzo Colittia7574052021-01-19 01:33:05 +09002136 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002137 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2138 return null;
2139 }
2140 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002141 if (nai == null) {
2142 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002143 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002144 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2145 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002146 }
2147
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002148 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002149 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002150 public NetworkInfo getNetworkInfo(int networkType) {
2151 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002152 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002153 if (getVpnUnderlyingNetworks(uid) != null) {
2154 // A VPN is active, so we may need to return one of its underlying networks. This
2155 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002156 // getNetworkAgentInfoForUid.
2157 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2158 if (nai == null) return null;
2159 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2160 if (networkInfo.getType() == networkType) {
2161 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002162 }
2163 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002164 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002165 }
2166
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002167 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002168 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002169 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002170 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002171 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002172 if (nai == null) return null;
2173 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002174 }
2175
2176 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002177 public NetworkInfo[] getAllNetworkInfo() {
2178 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002179 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002180 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2181 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002182 NetworkInfo info = getNetworkInfo(networkType);
2183 if (info != null) {
2184 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002185 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002186 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002187 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002188 }
2189
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002190 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002191 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002192 public Network getNetworkForType(int networkType) {
2193 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002194 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2195 return null;
2196 }
2197 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2198 if (nai == null) {
2199 return null;
2200 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002201 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002202 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2203 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002204 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002205 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002206 }
2207
2208 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002209 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002210 public Network[] getAllNetworks() {
2211 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002212 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002213 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002214 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002215 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002216 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002217 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002218 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002219 }
2220
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002221 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002222 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002223 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002224 // The basic principle is: if an app's traffic could possibly go over a
2225 // network, without the app doing anything multinetwork-specific,
2226 // (hence, by "default"), then include that network's capabilities in
2227 // the array.
2228 //
2229 // In the normal case, app traffic only goes over the system's default
2230 // network connection, so that's the only network returned.
2231 //
2232 // With a VPN in force, some app traffic may go into the VPN, and thus
2233 // over whatever underlying networks the VPN specifies, while other app
2234 // traffic may go over the system default network (e.g.: a split-tunnel
2235 // VPN, or an app disallowed by the VPN), so the set of networks
2236 // returned includes the VPN's underlying networks and the system
2237 // default.
2238 enforceAccessPermission();
2239
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002240 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002241
James Mattis2516da32021-01-31 17:06:19 -08002242 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2243 if (!nri.isBeingSatisfied()) {
2244 continue;
2245 }
2246 final NetworkAgentInfo nai = nri.getSatisfier();
2247 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2248 if (null != nc
2249 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2250 && !result.containsKey(nai.network)) {
2251 result.put(
2252 nai.network,
2253 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002254 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002255 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2256 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002257 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002258 }
2259
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002260 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002261 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002262 if (null != networks) {
2263 for (final Network network : networks) {
2264 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2265 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002266 result.put(
2267 network,
2268 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002269 nc,
2270 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002271 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002272 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002273 }
2274 }
2275 }
2276
2277 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2278 out = result.values().toArray(out);
2279 return out;
2280 }
2281
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002282 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002283 public boolean isNetworkSupported(int networkType) {
2284 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002285 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002286 }
2287
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002288 /**
2289 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002290 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002291 * @return the ip properties for the active network, or {@code null} if
2292 * none is active
2293 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002294 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002295 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002296 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002297 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002298 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2299 if (nai == null) return null;
2300 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002301 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002302 }
2303
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002304 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002305 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002306 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002307 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002308 final LinkProperties lp = getLinkProperties(nai);
2309 if (lp == null) return null;
2310 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002311 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002312 }
2313
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002314 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002315 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002316 public LinkProperties getLinkProperties(Network network) {
2317 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002318 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2319 if (lp == null) return null;
2320 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002321 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002322 }
2323
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002324 @Nullable
2325 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002326 if (nai == null) {
2327 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002328 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002329 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002330 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002331 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002332 }
2333
lucaslinc582d502022-01-27 09:07:00 +08002334 @Override
2335 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002336 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002337 @NonNull String packageName, @Nullable String callingAttributionTag) {
2338 Objects.requireNonNull(packageName);
2339 Objects.requireNonNull(lp);
2340 enforceNetworkStackOrSettingsPermission();
2341 if (!checkAccessPermission(-1 /* pid */, uid)) {
2342 return null;
2343 }
2344 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2345 }
2346
Qingxi Lib2748102020-01-08 12:51:49 -08002347 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2348 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2349 }
2350
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002351 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002352 if (nai == null) return null;
2353 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002354 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002355 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002356 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002357 }
2358
2359 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002360 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2361 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002362 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002363 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002364 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002365 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002366 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002367 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002368 }
2369
lucaslinc582d502022-01-27 09:07:00 +08002370 @Override
lucaslind2b06132022-03-02 10:56:57 +08002371 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2372 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2373 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002374 Objects.requireNonNull(nc);
2375 Objects.requireNonNull(packageName);
2376 enforceNetworkStackOrSettingsPermission();
2377 if (!checkAccessPermission(-1 /* pid */, uid)) {
2378 return null;
2379 }
2380 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2381 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2382 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2383 callingAttributionTag);
2384 }
2385
lucaslin69e1aa92022-03-22 18:15:09 +08002386 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2387 if (nc.getUnderlyingNetworks() != null
2388 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2389 nc.setUnderlyingNetworks(null);
2390 }
2391 }
2392
Qingxi Libb8da982020-01-17 17:54:27 -08002393 @VisibleForTesting
2394 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002395 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002396 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2397 // this would be expensive (one more permission check every time any NC callback is
2398 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2399 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2400 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002401 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002402 if (!checkSettingsPermission(callerPid, callerUid)) {
2403 newNc.setUids(null);
2404 newNc.setSSID(null);
2405 }
Etan Cohen107ae952018-12-30 17:59:59 -08002406 if (newNc.getNetworkSpecifier() != null) {
2407 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2408 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002409 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2410 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002411 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2412 newNc.setAdministratorUids(new int[0]);
2413 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002414 if (!checkAnyPermissionOf(mContext,
Benedict Wong53de25f2021-03-24 14:01:51 -07002415 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002416 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002417 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002418 }
lucaslin69e1aa92022-03-22 18:15:09 +08002419 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002420
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002421 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002422 }
2423
Roshan Pius98f59ec2021-02-23 08:47:39 -08002424 /**
2425 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002426 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002427 * NetworkCapabilities.
2428 * Note: This wrapper does not support any sort of invalidation and thus must not be
2429 * persistent or long-lived. It may only be used for the time necessary to
2430 * compute the redactions required by one particular NetworkCallback or
2431 * synchronous call.
2432 */
2433 private class RedactionPermissionChecker {
2434 private final int mCallingPid;
2435 private final int mCallingUid;
2436 @NonNull private final String mCallingPackageName;
2437 @Nullable private final String mCallingAttributionTag;
2438
2439 private Boolean mHasLocationPermission = null;
2440 private Boolean mHasLocalMacAddressPermission = null;
2441 private Boolean mHasSettingsPermission = null;
2442
2443 RedactionPermissionChecker(int callingPid, int callingUid,
2444 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2445 mCallingPid = callingPid;
2446 mCallingUid = callingUid;
2447 mCallingPackageName = callingPackageName;
2448 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002449 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002450
2451 private boolean hasLocationPermissionInternal() {
2452 final long token = Binder.clearCallingIdentity();
2453 try {
2454 return mLocationPermissionChecker.checkLocationPermission(
2455 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2456 null /* message */);
2457 } finally {
2458 Binder.restoreCallingIdentity(token);
2459 }
2460 }
2461
2462 /**
2463 * Returns whether the app holds location permission or not (might return cached result
2464 * if the permission was already checked before).
2465 */
2466 public boolean hasLocationPermission() {
2467 if (mHasLocationPermission == null) {
2468 // If there is no cached result, perform the check now.
2469 mHasLocationPermission = hasLocationPermissionInternal();
2470 }
2471 return mHasLocationPermission;
2472 }
2473
2474 /**
2475 * Returns whether the app holds local mac address permission or not (might return cached
2476 * result if the permission was already checked before).
2477 */
2478 public boolean hasLocalMacAddressPermission() {
2479 if (mHasLocalMacAddressPermission == null) {
2480 // If there is no cached result, perform the check now.
2481 mHasLocalMacAddressPermission =
2482 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2483 }
2484 return mHasLocalMacAddressPermission;
2485 }
2486
2487 /**
2488 * Returns whether the app holds settings permission or not (might return cached
2489 * result if the permission was already checked before).
2490 */
2491 public boolean hasSettingsPermission() {
2492 if (mHasSettingsPermission == null) {
2493 // If there is no cached result, perform the check now.
2494 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2495 }
2496 return mHasSettingsPermission;
2497 }
2498 }
2499
2500 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2501 @NetworkCapabilities.NetCapability long redaction) {
2502 return (redactions & redaction) != 0;
2503 }
2504
2505 /**
2506 * Use the provided |applicableRedactions| to check the receiving app's
2507 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2508 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2509 * before being sent to the corresponding app.
2510 */
2511 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2512 @NetworkCapabilities.RedactionType long applicableRedactions,
2513 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2514 boolean includeLocationSensitiveInfo) {
2515 long redactions = applicableRedactions;
2516 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2517 if (includeLocationSensitiveInfo
2518 && redactionPermissionChecker.hasLocationPermission()) {
2519 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2520 }
2521 }
2522 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2523 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2524 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2525 }
2526 }
2527 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2528 if (redactionPermissionChecker.hasSettingsPermission()) {
2529 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2530 }
2531 }
2532 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002533 }
2534
Qingxi Lib2748102020-01-08 12:51:49 -08002535 @VisibleForTesting
2536 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002537 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002538 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002539 int callingPid, int callingUid, @NonNull String callingPkgName,
2540 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002541 if (nc == null) {
2542 return null;
2543 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002544 // Avoid doing location permission check if the transport info has no location sensitive
2545 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002546 final RedactionPermissionChecker redactionPermissionChecker =
2547 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2548 callingAttributionTag);
2549 final long redactions = retrieveRequiredRedactions(
2550 nc.getApplicableRedactions(), redactionPermissionChecker,
2551 includeLocationSensitiveInfo);
2552 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002553 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002554 // TODO : calling UID is redacted because apps should generally not know what UID is
2555 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002556 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002557 newNc.setOwnerUid(INVALID_UID);
2558 return newNc;
2559 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002560 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2561 if (nc.hasTransport(TRANSPORT_VPN)) {
2562 // Owner UIDs already checked above. No need to re-check.
2563 return newNc;
2564 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002565 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2566 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002567 // compatibility for older apps.
2568 if (!includeLocationSensitiveInfo
2569 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002570 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002571 newNc.setOwnerUid(INVALID_UID);
2572 return newNc;
2573 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002574 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002575 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002576 newNc.setOwnerUid(INVALID_UID);
2577 }
Qingxi Lib2748102020-01-08 12:51:49 -08002578 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002579 }
2580
lucaslinc582d502022-01-27 09:07:00 +08002581 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002582 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2583 LinkProperties lp, int callerPid, int callerUid) {
2584 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002585 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2586 // this would be expensive (one more permission check every time any LP callback is
2587 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2588 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2589 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002590
2591 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2592 final boolean needsSanitization =
2593 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2594 if (!needsSanitization) {
2595 return new LinkProperties(lp);
2596 }
2597
2598 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002599 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002600 }
2601
2602 final LinkProperties newLp = new LinkProperties(lp);
2603 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2604 // object gets parceled.
2605 newLp.setCaptivePortalApiUrl(null);
2606 newLp.setCaptivePortalData(null);
2607 return newLp;
2608 }
2609
Roshan Pius08c94fb2020-01-16 12:17:17 -08002610 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2611 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002612 // There is no need to track the effective UID of the request here. If the caller
2613 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002614 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002615 // Unprivileged apps can only pass in null or their own UID.
2616 if (nc.getUids() == null) {
2617 // If the caller passes in null, the callback will also match networks that do not
2618 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2619 // In this case, redact everything in the request immediately. This ensures that the
2620 // app is not able to get any redacted information by filing an unredacted request
2621 // and observing whether the request matches something.
2622 if (nc.getNetworkSpecifier() != null) {
2623 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2624 }
2625 } else {
2626 nc.setSingleUid(callerUid);
2627 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002628 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002629 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002630 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002631
2632 // Clear owner UID; this can never come from an app.
2633 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002634 }
2635
Chalard Jean38354d12018-03-20 19:13:57 +09002636 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002637 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002638 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2639 }
2640 }
2641
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002642 @Override
2643 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2644 enforceAccessPermission();
2645 final int callerUid = Binder.getCallingUid();
2646 final long token = Binder.clearCallingIdentity();
2647 try {
2648 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2649 } finally {
2650 Binder.restoreCallingIdentity(token);
2651 }
2652 }
2653
junyulaiebd15162021-03-03 12:09:05 +08002654 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002655 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002656 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002657 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002658 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002659
Serik Beketayev05130302021-01-15 16:47:25 -08002660 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002661 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002662 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2663 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002664 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002665 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002666 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002667 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2668 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002669 }
2670 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002671 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002672 }
2673
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002674 @Override
junyulaiebd15162021-03-03 12:09:05 +08002675 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002676 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002677 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002678 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002679
2680 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2681 for (Network network : getAllNetworks()) {
2682 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09002683 final boolean includeNetwork = (nai != null) && nai.isCreated();
2684 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002685 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2686 // NetworkCapabilities, which may contain UIDs of apps to which the
2687 // network applies. Should the UIDs be cleared so as not to leak or
2688 // interfere ?
2689 result.add(nai.getNetworkStateSnapshot());
2690 }
2691 }
2692 return result;
2693 }
2694
2695 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002696 public boolean isActiveNetworkMetered() {
2697 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002698
Qingxi Lib2748102020-01-08 12:51:49 -08002699 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002700 if (caps != null) {
2701 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2702 } else {
2703 // Always return the most conservative value
2704 return true;
2705 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002706 }
2707
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002708 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002709 * Ensures that the system cannot call a particular method.
2710 */
2711 private boolean disallowedBecauseSystemCaller() {
2712 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002713 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2714 // for devices launched with Q and above. However, existing devices upgrading to Q and
2715 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002716 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002717 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002718 log("This method exists only for app backwards compatibility"
2719 + " and must not be called by system services.");
2720 return true;
2721 }
2722 return false;
2723 }
2724
paulhub2c28682021-08-18 18:35:54 +08002725 private int getAppUid(final String app, final UserHandle user) {
2726 final PackageManager pm =
2727 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2728 final long token = Binder.clearCallingIdentity();
2729 try {
2730 return pm.getPackageUid(app, 0 /* flags */);
2731 } catch (PackageManager.NameNotFoundException e) {
2732 return -1;
2733 } finally {
2734 Binder.restoreCallingIdentity(token);
2735 }
2736 }
2737
2738 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2739 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2740 if (getAppUid(packageName, user) != callingUid) {
2741 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2742 }
2743 }
2744
Lorenzo Colitti23862912018-09-28 11:31:55 +09002745 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002746 * Ensure that a network route exists to deliver traffic to the specified
2747 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002748 * @param networkType the type of the network over which traffic to the
2749 * specified host is to be routed
2750 * @param hostAddress the IP address of the host to which the route is
2751 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002752 * @return {@code true} on success, {@code false} on failure
2753 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002754 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002755 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2756 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002757 if (disallowedBecauseSystemCaller()) {
2758 return false;
2759 }
paulhub2c28682021-08-18 18:35:54 +08002760 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002761 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002762 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002763 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002764 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002765
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002766 InetAddress addr;
2767 try {
2768 addr = InetAddress.getByAddress(hostAddress);
2769 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002770 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002771 return false;
2772 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002773
The Android Open Source Project28527d22009-03-03 19:31:44 -08002774 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002775 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002776 return false;
2777 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002778
2779 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2780 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002781 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002782 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2783 } else {
2784 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2785 }
2786 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002787 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002788
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002789 DetailedState netState;
2790 synchronized (nai) {
2791 netState = nai.networkInfo.getDetailedState();
2792 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002793
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002794 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002795 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002796 log("requestRouteToHostAddress on down network "
2797 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002798 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002799 }
2800 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002801 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002802
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002803 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002804 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002805 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002806 LinkProperties lp;
2807 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002808 synchronized (nai) {
2809 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002810 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002811 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002812 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002813 if (DBG) {
2814 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2815 }
Wink Saville32506bc2013-06-29 21:10:57 -07002816 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002817 } finally {
2818 Binder.restoreCallingIdentity(token);
2819 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002820 }
2821
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002822 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002823 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002824 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002825 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002826 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002827 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002828 if (bestRoute.getGateway().equals(addr)) {
2829 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002830 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002831 } else {
2832 // if we will connect to this through another route, add a direct route
2833 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002834 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002835 }
2836 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002837 if (DBG) log("Adding legacy route " + bestRoute +
2838 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002839
2840 final String dst = bestRoute.getDestinationLinkAddress().toString();
2841 final String nextHop = bestRoute.hasGateway()
2842 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002843 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002844 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2845 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002846 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002847 return false;
2848 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002849 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002850 }
2851
paulhu7c0a2e62021-01-08 00:51:49 +08002852 class DnsResolverUnsolicitedEventCallback extends
2853 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002854 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002855 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002856 try {
2857 mHandler.sendMessage(mHandler.obtainMessage(
2858 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002859 new PrivateDnsValidationUpdate(event.netId,
2860 InetAddresses.parseNumericAddress(event.ipAddress),
2861 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002862 } catch (IllegalArgumentException e) {
2863 loge("Error parsing ip address in validation event");
2864 }
2865 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002866
2867 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002868 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2869 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002870 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2871 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2872 // event callback for certain nai. e.g. cellular. Register here to pass to
2873 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002874 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002875 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2876 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002877 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002878 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002879 }
2880 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002881
2882 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002883 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2884 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2885 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002886 }
dalyk1720e542018-03-05 12:42:22 -05002887
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002888 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002889 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002890 return this.VERSION;
2891 }
2892
2893 @Override
2894 public String getInterfaceHash() {
2895 return this.HASH;
2896 }
paulhu7c0a2e62021-01-08 00:51:49 +08002897 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002898
2899 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002900 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2901 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002902
paulhu7c0a2e62021-01-08 00:51:49 +08002903 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002904 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002905 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002906 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002907 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002908 }
2909 }
2910
Sudheer Shanka9967d462021-03-18 19:09:25 +00002911 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002912 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002913 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002914 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2915 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002916 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002917 };
2918
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002919 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002920 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002921 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002922 }
2923
Mark Fasheh7501e762023-05-04 20:23:11 +00002924 static final class UidFrozenStateChangedArgs {
2925 final int[] mUids;
2926 final int[] mFrozenStates;
2927
2928 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
2929 mUids = uids;
2930 mFrozenStates = frozenStates;
2931 }
2932 }
2933
2934 private void handleFrozenUids(int[] uids, int[] frozenStates) {
2935 final ArraySet<Range<Integer>> ranges = new ArraySet<>();
2936
2937 for (int i = 0; i < uids.length; i++) {
2938 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
2939 Integer uidAsInteger = Integer.valueOf(uids[i]);
2940 ranges.add(new Range(uidAsInteger, uidAsInteger));
2941 }
2942 }
2943
2944 if (!ranges.isEmpty()) {
2945 final Set<Integer> exemptUids = new ArraySet<>();
2946 try {
2947 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
2948 } catch (Exception e) {
2949 loge("Exception in socket destroy: " + e);
2950 }
2951 }
2952 }
2953
2954 @VisibleForTesting
2955 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
2956
Paul Jensen83f5d572014-08-29 09:54:01 -04002957 private void enforceInternetPermission() {
2958 mContext.enforceCallingOrSelfPermission(
2959 android.Manifest.permission.INTERNET,
2960 "ConnectivityService");
2961 }
2962
The Android Open Source Project28527d22009-03-03 19:31:44 -08002963 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002964 mContext.enforceCallingOrSelfPermission(
2965 android.Manifest.permission.ACCESS_NETWORK_STATE,
2966 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002967 }
2968
lucaslinc582d502022-01-27 09:07:00 +08002969 private boolean checkAccessPermission(int pid, int uid) {
2970 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
2971 == PERMISSION_GRANTED;
2972 }
2973
paulhua6ee2122021-02-22 15:40:43 +08002974 /**
2975 * Performs a strict and comprehensive check of whether a calling package is allowed to
2976 * change the state of network, as the condition differs for pre-M, M+, and
2977 * privileged/preinstalled apps. The caller is expected to have either the
2978 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2979 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2980 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2981 * permission and cannot be revoked. See http://b/23597341
2982 *
2983 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2984 * of this app will be updated to the current time.
2985 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002986 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002987 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2988 == PackageManager.PERMISSION_GRANTED) {
2989 return;
2990 }
2991
2992 if (callingPkg == null) {
2993 throw new SecurityException("Calling package name is null.");
2994 }
2995
2996 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2997 final int uid = mDeps.getCallingUid();
2998 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2999 callingPkg, callingAttributionTag, null /* message */);
3000
3001 if (mode == AppOpsManager.MODE_ALLOWED) {
3002 return;
3003 }
3004
3005 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3006 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3007 return;
3008 }
3009
3010 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3011 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3012 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003013 }
3014
Charles He9369e612017-05-15 17:07:18 +01003015 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003016 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003017 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003018 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003019 }
3020
Quang Luong98858d62023-02-11 00:25:24 +00003021 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003022 enforceAnyPermissionOf(mContext,
3023 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003024 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003025 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3026 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3027 }
3028
paulhu8e96a752019-08-12 16:25:11 +08003029 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003030 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003031 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003032 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003033 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003034 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003035 }
3036
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003037 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003038 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003039 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003040 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003041 android.Manifest.permission.NETWORK_SETTINGS,
3042 android.Manifest.permission.NETWORK_FACTORY,
3043 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3044 }
3045
3046 private void enforceNetworkFactoryOrTestNetworksPermission() {
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.MANAGE_TEST_NETWORKS,
3051 android.Manifest.permission.NETWORK_FACTORY,
3052 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3053 }
3054
lucaslin69e1aa92022-03-22 18:15:09 +08003055 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3056 return PERMISSION_GRANTED == mContext.checkPermission(
3057 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3058 || PERMISSION_GRANTED == mContext.checkPermission(
3059 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3060 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003061 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003062 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003063 }
3064
Chalard Jean9a396cc2018-02-21 18:43:54 +09003065 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003066 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003067 android.Manifest.permission.NETWORK_SETTINGS,
3068 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003069 }
3070
3071 private boolean checkSettingsPermission(int pid, int uid) {
3072 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003073 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3074 || PERMISSION_GRANTED == mContext.checkPermission(
3075 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003076 }
3077
paulhu8e96a752019-08-12 16:25:11 +08003078 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003079 enforceNetworkStackPermissionOr(mContext,
3080 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003081 }
3082
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003083 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003084 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003085 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003086 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003087 }
3088
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003089 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003090 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003091 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3092 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003093 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003094 }
3095
James Mattis8378aec2021-01-26 14:05:36 -08003096 private void enforceOemNetworkPreferencesPermission() {
3097 mContext.enforceCallingOrSelfPermission(
3098 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3099 "ConnectivityService");
3100 }
3101
James Mattisfa270db2021-05-31 17:11:10 -07003102 private void enforceManageTestNetworksPermission() {
3103 mContext.enforceCallingOrSelfPermission(
3104 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3105 "ConnectivityService");
3106 }
3107
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003108 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003109 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003110 android.Manifest.permission.NETWORK_STACK,
3111 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003112 }
3113
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003114 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003115 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003116 android.Manifest.permission.NETWORK_STACK,
3117 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3118 }
3119
paulhu1a407652019-03-22 16:35:06 +08003120 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003121 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003122 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003123 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3124 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003125 }
3126
Paul Hu8fc2a552022-05-04 18:44:42 +08003127 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3128 boolean checkUidsAllowedList) {
3129 if (PermissionUtils.checkAnyPermissionOf(mContext,
3130 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3131 return true;
3132 }
3133
3134 // fallback to ConnectivityInternalPermission
3135 // TODO: Remove this fallback check after all apps have declared
3136 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3137 if (PermissionUtils.checkAnyPermissionOf(mContext,
3138 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3139 return true;
3140 }
3141
3142 // Check whether uid is in allowed on restricted networks list.
3143 if (checkUidsAllowedList
3144 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3145 return true;
3146 }
3147 return false;
3148 }
3149
3150 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3151 final int callingUid = mDeps.getCallingUid();
3152 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3153 throw new SecurityException("ConnectivityService: user " + callingUid
3154 + " has no permission to access restricted network.");
3155 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003156 }
3157
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003158 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003159 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003160 }
3161
Roshan Pius98f59ec2021-02-23 08:47:39 -08003162 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3163 return PERMISSION_GRANTED == mContext.checkPermission(
3164 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3165 }
3166
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003167 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003168 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003169 }
3170
3171 private void sendInetConditionBroadcast(NetworkInfo info) {
3172 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3173 }
3174
Wink Saville4f0de1e2011-08-04 15:01:58 -07003175 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003176 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003177 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003178 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003179 if (info.isFailover()) {
3180 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3181 info.setFailover(false);
3182 }
3183 if (info.getReason() != null) {
3184 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3185 }
3186 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003187 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3188 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003189 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003190 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003191 return intent;
3192 }
3193
3194 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3195 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3196 }
3197
Michael Groover73f69482023-01-27 11:01:25 -06003198 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3199 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003200 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3201 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003202 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003203 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003204 if (!mSystemReady
3205 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003206 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003207 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003208 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003209 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003210 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003211 }
3212
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003213 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003214 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003215 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003216 final NetworkInfo ni = intent.getParcelableExtra(
3217 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003218 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3219 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003220 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003221 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003222 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003223 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003224 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003225 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003226 } finally {
3227 Binder.restoreCallingIdentity(ident);
3228 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003229 }
3230 }
3231
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003232 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3233 NetworkInfo info) {
3234 // Delivery group policy APIs are only available on U+.
3235 if (!SdkLevel.isAtLeastU()) return;
3236
3237 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3238 try {
3239 // This allows us to discard older broadcasts still waiting to be delivered
3240 // which have the same namespace and key.
3241 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3242 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3243 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003244 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003245 } catch (UnsupportedApiLevelException e) {
3246 Log.wtf(TAG, "Using unsupported API" + e);
3247 }
3248 }
3249
3250 @VisibleForTesting
3251 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3252 final StringBuilder sb = new StringBuilder();
3253 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3254 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3255 sb.append(info.getExtraInfo());
3256 return sb.toString();
3257 }
3258
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003259 /**
Aaron Huang96011892020-06-27 07:18:23 +08003260 * Called by SystemServer through ConnectivityManager when the system is ready.
3261 */
3262 @Override
3263 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003264 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003265 throw new SecurityException("Calling Uid is not system uid.");
3266 }
3267 systemReadyInternal();
3268 }
3269
3270 /**
3271 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003272 */
3273 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003274 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003275 // Load flags after PackageManager is ready to query module version
3276 mFlags.loadFlags(mDeps, mContext);
3277
Aaron Huang9a57acf2020-12-08 10:03:29 +08003278 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3279 // listening network request which is sent by MultipathPolicyTracker won't be added
3280 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3281 // be called after PermissionMonitor#startMonitoring().
3282 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3283 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3284 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003285 final ConditionVariable startMonitoringDone = new ConditionVariable();
3286 mHandler.post(() -> {
3287 mPermissionMonitor.startMonitoring();
3288 startMonitoringDone.open();
3289 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003290 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003291 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003292
Hugo Benichie5220992017-04-26 14:53:28 +09003293 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003294 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003295 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003296 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003297 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003298 }
3299 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003300
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003301 // Create network requests for always-on networks.
3302 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003303
3304 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003305 // Note that updating can be skipped here if the list is empty only because no uid
3306 // rules are applied before system ready. Normally, the empty uid list means to clear
3307 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003308 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3309 updateMobileDataPreferredUids();
3310 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003311
3312 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
3313 if (SdkLevel.isAtLeastT()) {
3314 mBpfNetMaps.setPullAtomCallback(mContext);
3315 }
Paul Hu3c8c8102022-08-25 07:06:16 +00003316 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3317 // have permission problem. While CV#block() is unbounded in time and can in principle block
3318 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3319 // could have blocked forever too.
3320 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003321 }
3322
The Android Open Source Project28527d22009-03-03 19:31:44 -08003323 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003324 * Start listening for default data network activity state changes.
3325 */
3326 @Override
3327 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003328 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003329 }
3330
3331 /**
3332 * Stop listening for default data network activity state changes.
3333 */
3334 @Override
3335 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003336 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003337 }
3338
3339 /**
3340 * Check whether the default network radio is currently active.
3341 */
3342 @Override
3343 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003344 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003345 }
3346
3347 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003348 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003349 * and set it on it's iface.
3350 */
Junyu Lai970963e2022-10-25 15:46:47 +08003351 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003352 final String iface = newLp.getInterfaceName();
3353 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003354 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003355 // Silently ignore unset MTU value.
3356 return;
3357 }
Hansen Kurli04252032022-12-07 11:21:49 +00003358 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3359 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3360 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003361 return;
3362 }
Hansen Kurli04252032022-12-07 11:21:49 +00003363 // Cannot set MTU without interface name
3364 if (TextUtils.isEmpty(iface)) {
3365 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003366 return;
3367 }
sy.yun4aa73922013-09-02 05:24:09 +09003368
Hansen Kurli04252032022-12-07 11:21:49 +00003369 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3370 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003371 return;
3372 }
3373
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003374 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003375 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003376 mNetd.interfaceSetMtu(iface, mtu);
3377 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003378 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003379 }
3380 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003381
Chenbo Feng15416292018-11-08 17:36:21 -08003382 @VisibleForTesting
3383 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003384
Junyu Lai970963e2022-10-25 15:46:47 +08003385 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003386 String[] values = null;
3387 if (tcpBufferSizes != null) {
3388 values = tcpBufferSizes.split(",");
3389 }
3390
3391 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003392 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003393 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3394 values = tcpBufferSizes.split(",");
3395 }
3396
3397 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3398
3399 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003400 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003401
Chenbo Feng15416292018-11-08 17:36:21 -08003402 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3403 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3404 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003405 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003406 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003407 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003408 }
3409 }
3410
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003411 @Override
3412 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003413 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003414 NETWORK_RESTORE_DELAY_PROP_NAME);
3415 if(restoreDefaultNetworkDelayStr != null &&
3416 restoreDefaultNetworkDelayStr.length() != 0) {
3417 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003418 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003419 } catch (NumberFormatException e) {
3420 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003421 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003422 // if the system property isn't set, use the value for the apn type
3423 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3424
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003425 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3426 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003427 }
3428 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003429 }
3430
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003431 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003432 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003433 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003434 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003435 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003436 // Start gathering diagnostic information.
3437 netDiags.add(new NetworkDiagnostics(
3438 nai.network,
3439 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003440 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003441 DIAG_TIME_MS));
3442 }
3443
3444 for (NetworkDiagnostics netDiag : netDiags) {
3445 pw.println();
3446 netDiag.waitForMeasurements();
3447 netDiag.dump(pw);
3448 }
3449 }
3450
The Android Open Source Project28527d22009-03-03 19:31:44 -08003451 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003452 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3453 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003454 if (!checkDumpPermission(mContext, TAG, writer)) return;
3455
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003456 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003457 }
3458
lucaslin99473f62020-12-10 15:10:54 +08003459 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3460 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3461 != PackageManager.PERMISSION_GRANTED) {
3462 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003463 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003464 + " due to missing android.permission.DUMP permission");
3465 return false;
3466 } else {
3467 return true;
3468 }
3469 }
3470
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003471 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003472 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003473
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003474 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003475 dumpNetworkDiagnostics(pw);
3476 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003477 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003478 dumpNetworks(pw);
3479 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003480 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003481 dumpNetworkRequests(pw);
3482 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003483 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3484 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3485 dumpTrafficController(pw, fd, verbose);
3486 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003487 }
Erik Kline9647f382015-06-05 17:47:34 +09003488
Junyu Lai0da479b2022-04-20 15:06:29 +08003489 pw.println("NetworkProviders for:");
3490 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003491 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003492 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003493 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003494 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003495 pw.println();
3496
Chalard Jean5b409c72021-02-04 13:12:59 +09003497 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003498 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003499 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003500 pw.println("none");
3501 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003502 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003503 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003504 pw.println();
3505
James Mattis8b298a02021-06-01 22:34:04 -07003506 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003507 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003508 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003509 pw.decreaseIndent();
3510 pw.println();
3511
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003512 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003513 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003514 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003515 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003516 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003517
junyulaif2c67e42018-08-07 19:50:45 +08003518 pw.println("Status for known UIDs:");
3519 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003520 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003521 for (int i = 0; i < size; i++) {
3522 // Don't crash if the array is modified while dumping in bugreports.
3523 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003524 final int uid = mUidBlockedReasons.keyAt(i);
3525 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3526 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003527 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003528 } catch (ArrayIndexOutOfBoundsException e) {
3529 pw.println(" ArrayIndexOutOfBoundsException");
3530 } catch (ConcurrentModificationException e) {
3531 pw.println(" ConcurrentModificationException");
3532 }
3533 }
3534 pw.println();
3535 pw.decreaseIndent();
3536
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003537 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003538 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003539 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003540 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003541 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003542
Junyu Lai0da479b2022-04-20 15:06:29 +08003543 pw.println("Network Offers:");
3544 pw.increaseIndent();
3545 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3546 pw.println(offerInfo.offer);
3547 }
3548 pw.decreaseIndent();
3549 pw.println();
3550
Robert Greenwalt94e22142014-07-30 16:31:24 -07003551 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003552
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003553 pw.println();
markchien5e866652019-09-30 14:40:57 +08003554 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003555
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003556 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003557 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003558
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003559 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003560
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003561 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003562 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003563 pw.println("mNetworkRequestInfoLogs (most recent first):");
3564 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003565 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003566 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003567
3568 pw.println();
3569 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3570 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003571 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003572 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003573
3574 pw.println();
3575 pw.println("NetTransition WakeLock activity (most recent first):");
3576 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003577 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3578 pw.println("total releases: " + mTotalWakelockReleases);
3579 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3580 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3581 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3582 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3583 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3584 }
James Mattiscb1e0362021-04-06 17:07:42 -07003585 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003586
3587 pw.println();
3588 pw.println("bandwidth update requests (by uid):");
3589 pw.increaseIndent();
3590 synchronized (mBandwidthRequests) {
3591 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3592 pw.println("[" + mBandwidthRequests.keyAt(i)
3593 + "]: " + mBandwidthRequests.valueAt(i));
3594 }
3595 }
3596 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003597 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003598
James Mattiscb1e0362021-04-06 17:07:42 -07003599 pw.println();
3600 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3601 pw.increaseIndent();
3602 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003603 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003604 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003605
3606 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003607
3608 pw.println();
3609 pw.println("Permission Monitor:");
3610 pw.increaseIndent();
3611 mPermissionMonitor.dump(pw);
3612 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003613
3614 pw.println();
3615 pw.println("Legacy network activity:");
3616 pw.increaseIndent();
3617 mNetworkActivityTracker.dump(pw);
3618 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003619 }
3620
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003621 private void dumpNetworks(IndentingPrintWriter pw) {
3622 for (NetworkAgentInfo nai : networksSortedById()) {
3623 pw.println(nai.toString());
3624 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003625 pw.println("Nat464Xlat:");
3626 pw.increaseIndent();
3627 nai.dumpNat464Xlat(pw);
3628 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003629 pw.println(String.format(
3630 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3631 nai.numForegroundNetworkRequests(),
3632 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3633 nai.numBackgroundNetworkRequests(),
3634 nai.numNetworkRequests()));
3635 pw.increaseIndent();
3636 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3637 pw.println(nai.requestAt(i).toString());
3638 }
3639 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003640 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003641 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003642 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003643 pw.decreaseIndent();
3644 pw.decreaseIndent();
3645 }
3646 }
3647
James Mattis8b298a02021-06-01 22:34:04 -07003648 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3649 if (!mProfileNetworkPreferences.isEmpty()) {
3650 pw.println("Profile preferences:");
3651 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09003652 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07003653 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003654 }
James Mattis8b298a02021-06-01 22:34:04 -07003655 if (!mOemNetworkPreferences.isEmpty()) {
3656 pw.println("OEM preferences:");
3657 pw.increaseIndent();
3658 pw.println(mOemNetworkPreferences);
3659 pw.decreaseIndent();
3660 }
3661 if (!mMobileDataPreferredUids.isEmpty()) {
3662 pw.println("Mobile data preferred UIDs:");
3663 pw.increaseIndent();
3664 pw.println(mMobileDataPreferredUids);
3665 pw.decreaseIndent();
3666 }
James Mattis45d81842021-01-10 14:24:24 -08003667
James Mattis8b298a02021-06-01 22:34:04 -07003668 pw.println("Default requests:");
3669 pw.increaseIndent();
3670 dumpPerAppDefaultRequests(pw);
3671 pw.decreaseIndent();
3672 }
3673
3674 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003675 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3676 if (mDefaultRequest == defaultRequest) {
3677 continue;
3678 }
3679
James Mattis8b298a02021-06-01 22:34:04 -07003680 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3681 final String networkOutput;
3682 if (null == satisfier) {
3683 networkOutput = "null";
3684 } else if (mNoServiceNetwork.equals(satisfier)) {
3685 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003686 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003687 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003688 }
James Mattis8b298a02021-06-01 22:34:04 -07003689 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3690 ? "" : " asUid: " + defaultRequest.mAsUid;
3691 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3692 + defaultRequest.mPid + asUidString + "]";
3693 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3694 + " Preference order: " + defaultRequest.mPreferenceOrder
3695 + " Tracked UIDs: " + defaultRequest.getUids();
3696 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003697 }
3698 }
3699
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003700 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003701 NetworkRequestInfo[] infos = null;
3702 while (infos == null) {
3703 try {
3704 infos = requestsSortedById();
3705 } catch (ConcurrentModificationException e) {
3706 // mNetworkRequests should only be accessed from handler thread, except dump().
3707 // As dump() is never called in normal usage, it would be needlessly expensive
3708 // to lock the collection only for its benefit. Instead, retry getting the
3709 // requests if ConcurrentModificationException is thrown during dump().
3710 }
3711 }
3712 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003713 pw.println(nri.toString());
3714 }
3715 }
3716
Ken Chene6d511f2022-01-25 11:10:42 +08003717 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
3718 boolean verbose) {
3719 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09003720 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08003721 } catch (ServiceSpecificException e) {
3722 pw.println(e.getMessage());
3723 } catch (IOException e) {
3724 loge("Dump BPF maps failed, " + e);
3725 }
3726 }
3727
Chalard Jean524f0b12021-10-25 21:11:56 +09003728 private void dumpAllRequestInfoLogsToLogcat() {
3729 try (PrintWriter logPw = new PrintWriter(new Writer() {
3730 @Override
3731 public void write(final char[] cbuf, final int off, final int len) {
3732 // This method is called with 0-length and 1-length arrays for empty strings
3733 // or strings containing only the DEL character.
3734 if (len <= 1) return;
3735 Log.e(TAG, new String(cbuf, off, len));
3736 }
3737 @Override public void flush() {}
3738 @Override public void close() {}
3739 })) {
3740 mNetworkRequestInfoLogs.dump(logPw);
3741 }
3742 }
3743
Hugo Benichia480ba52018-09-03 08:19:02 +09003744 /**
3745 * Return an array of all current NetworkAgentInfos sorted by network id.
3746 */
3747 private NetworkAgentInfo[] networksSortedById() {
3748 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003749 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003750 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003751 return networks;
3752 }
3753
3754 /**
3755 * Return an array of all current NetworkRequest sorted by request id.
3756 */
James Mattis258ea3c2020-11-15 15:04:40 -08003757 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003758 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003759 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003760 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003761 // Sort the array based off the NRI containing the min requestId in its requests.
3762 Arrays.sort(requests,
3763 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3764 Comparator.comparingInt(req -> req.requestId)).requestId
3765 )
3766 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003767 return requests;
3768 }
3769
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003770 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003771 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003772 if (officialNai != null && officialNai.equals(nai)) return true;
3773 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003774 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003775 " - " + nai);
3776 }
3777 return false;
3778 }
3779
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003780 private boolean isDisconnectRequest(Message msg) {
3781 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
3782 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
3783 return info.getState() == NetworkInfo.State.DISCONNECTED;
3784 }
3785
Robert Greenwalt2034b912009-08-12 16:08:25 -07003786 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003787 private class NetworkStateTrackerHandler extends Handler {
3788 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003789 super(looper);
3790 }
3791
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003792 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003793 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3794 final NetworkAgentInfo nai = arg.first;
3795 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003796 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003797 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003798 }
3799 return;
3800 }
3801
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003802 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003803 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003804 return;
3805 }
3806
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003807 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003808 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09003809 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
3810 final NetworkCapabilities sanitized =
3811 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09003812 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003813 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003814 break;
3815 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003816 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003817 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003818 processLinkPropertiesFromAgent(nai, newLp);
3819 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003820 break;
3821 }
3822 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003823 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003824 updateNetworkInfo(nai, info);
3825 break;
3826 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003827 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003828 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003829 break;
3830 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003831 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09003832 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003833 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003834 // Note that if the NAI had been connected, this would affect the
3835 // score, and therefore would require re-mixing the score and performing
3836 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003837 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003838 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3839 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003840 // Mark the network as temporarily accepting partial connectivity so that it
3841 // will be validated (and possibly become default) even if it only provides
3842 // partial internet access. Note that if user connects to partial connectivity
3843 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3844 // out of wifi coverage) and if the same wifi is available again, the device
3845 // will auto connect to this wifi even though the wifi has "no internet".
3846 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003847 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003848 break;
3849 }
junyulai011b1f12019-01-03 18:50:15 +08003850 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003851 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003852 break;
3853 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003854 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003855 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003856 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003857
3858 if (isLegacyLockdownNai(nai)
3859 && (underlying == null || underlying.size() != 1)) {
3860 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3861 + " must have exactly one underlying network: " + underlying);
3862 }
3863
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003864 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3865 nai.declaredUnderlyingNetworks = (underlying != null)
3866 ? underlying.toArray(new Network[0]) : null;
3867
3868 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3869 if (DBG) {
3870 log(nai.toShortString() + " changed underlying networks to "
3871 + Arrays.toString(nai.declaredUnderlyingNetworks));
3872 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003873 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003874 notifyIfacesChangedForNetworkStats();
3875 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003876 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003877 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003878 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3879 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3880 nai.teardownDelayMs = msg.arg1;
3881 } else {
3882 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3883 }
Chalard Jean550b5212021-03-05 23:07:53 +09003884 break;
3885 }
3886 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3887 nai.setLingerDuration((int) arg.second);
3888 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003889 }
Tyler Wear72388212021-09-09 14:49:02 -07003890 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3891 DscpPolicy policy = (DscpPolicy) arg.second;
3892 if (mDscpPolicyTracker != null) {
3893 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3894 }
3895 break;
3896 }
3897 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3898 if (mDscpPolicyTracker != null) {
3899 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3900 }
3901 break;
3902 }
3903 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3904 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08003905 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07003906 }
3907 break;
3908 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09003909 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09003910 if (!nai.everConnected()) {
3911 Log.d(TAG, "unregisterAfterReplacement on never-connected "
3912 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09003913 teardownUnneededNetwork(nai);
3914 break;
3915 }
3916
3917 if (nai.isDestroyed()) {
3918 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
3919 + ", ignoring");
3920 break;
3921 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003922
3923 final int timeoutMs = (int) arg.second;
3924 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3925 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
3926 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
3927 }
3928
3929 // Marking a network awaiting replacement is used to ensure that any requests
3930 // satisfied by the network do not switch to another network until a
3931 // replacement is available or the wait for a replacement times out.
3932 // If the network is inactive (i.e., nascent or lingering), then there are no
3933 // such requests, and there is no point keeping it. Just tear it down.
3934 // Note that setLingerDuration(0) cannot be used to do this because the network
3935 // could be nascent.
3936 nai.clearInactivityState();
3937 if (unneeded(nai, UnneededFor.TEARDOWN)) {
3938 Log.d(TAG, nai.toShortString()
3939 + " marked awaiting replacement is unneeded, tearing down instead");
3940 teardownUnneededNetwork(nai);
3941 break;
3942 }
3943
3944 Log.d(TAG, "Marking " + nai.toShortString()
3945 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
3946 destroyNativeNetwork(nai);
3947
3948 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
3949 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
3950 // consider the fact that the network could already have disconnected or been
3951 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
3952 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
3953 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
3954 mKeepaliveTracker.handleStopAllKeepalives(nai,
3955 SocketKeepalive.ERROR_INVALID_NETWORK);
3956
3957 nai.updateScoreForNetworkAgentUpdate();
3958 // This rematch is almost certainly not going to result in any changes, because
3959 // the destroyed flag is only just above the "current satisfier wins"
3960 // tie-breaker. But technically anything that affects scoring should rematch.
3961 rematchAllNetworksAndRequests();
3962 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
3963 break;
3964 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003965 }
3966 }
3967
3968 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003969 final int netId = msg.arg2;
3970 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003971 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09003972 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003973 switch (msg.what) {
3974 default:
3975 return false;
lucasline117e2e2019-10-22 18:27:33 +08003976 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08003977 if (nai == null) {
3978 break;
3979 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003980 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
3981 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08003982 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003983 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08003984 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003985 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08003986 if (probePrivateDnsCompleted) {
3987 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3988 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003989 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003990 }
3991 // Only show the notification when the private DNS is broken and the
3992 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003993 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003994 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3995 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003996 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003997 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3998 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3999 // private DNS is broken, it means this network is being reevaluated.
4000 // Either probing private DNS is not necessary any more or it hasn't been
4001 // done yet. In either case, the networkCapabilities should be updated to
4002 // reflect the new status.
4003 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004004 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004005 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004006 }
4007 break;
4008 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004009 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004010 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4011
Erik Kline31b4a9e2018-01-11 21:07:29 +09004012 if (nai == null) break;
4013
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004014 handleNetworkTested(nai, results.mTestResult,
4015 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004016 break;
4017 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004018 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004019 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004020 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004021 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004022 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004023 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004024 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4025 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004026 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004027 if (nai == null) {
4028 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4029 break;
4030 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004031 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004032 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004033 (PendingIntent) msg.obj,
4034 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004035 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004036 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004037 break;
4038 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004039 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004040 if (nai == null) break;
4041
Erik Kline9a62f012018-03-21 07:18:33 -07004042 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004043 break;
4044 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004045 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004046 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004047 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004048 break;
4049 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004050 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004051 return true;
4052 }
4053
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004054 private void handleNetworkTested(
4055 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004056 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4057 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004058 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004059
4060 // If there is any kind of working networking, then the NAI has been evaluated
4061 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4062 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004063 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004064 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004065 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4066 // any callback that receives onAvailable for that rematch receives an extra caps
4067 // callback. To prevent that, update the score in the agent so the updates below won't
4068 // see an update to both caps and score at the same time.
4069 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004070 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4071
he_won.hwang881307a2022-03-15 21:23:52 +09004072 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4073 // Assume the validation failure is due to a temporary failure after roaming
4074 // and ignore it. NetworkMonitor will continue to retry validation. If it
4075 // continues to fail after the block timeout expires, the network will be
4076 // marked unvalidated. If it succeeds, then validation state will not change.
4077 return;
4078 }
4079
Chalard Jean254bd162022-08-25 13:04:51 +09004080 final boolean wasValidated = nai.isValidated();
4081 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004082 final boolean wasPortal = nai.captivePortalDetected();
4083 nai.setPartialConnectivity(partial);
4084 nai.setCaptivePortalDetected(portal);
4085 nai.updateScoreForNetworkAgentUpdate();
4086 final boolean partialConnectivityChanged = (wasPartial != partial);
4087 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004088
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004089 if (DBG) {
4090 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4091 ? " with redirect to " + redirectUrl
4092 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004093 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004094 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004095 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004096 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004097 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004098 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004099 if (valid) {
4100 handleFreshlyValidatedNetwork(nai);
4101 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4102 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004103 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004104 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004105 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004106 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004107 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004108 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004109 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004110 NotificationType.PRIVATE_DNS_BROKEN);
4111 // If network becomes valid, the hasShownBroken should be reset for
4112 // that network so that the notification will be fired when the private
4113 // DNS is broken again.
4114 nai.networkAgentConfig.hasShownBroken = false;
4115 }
4116 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004117 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004118 } else if (portalChanged) {
4119 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
4120 == getCaptivePortalMode()) {
4121 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4122 nai.onPreventAutomaticReconnect();
4123 teardownUnneededNetwork(nai);
4124 return;
4125 } else {
4126 updateCapabilitiesForNetwork(nai);
4127 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004128 } else if (becameEvaluated) {
4129 // If valid or partial connectivity changed, updateCapabilities* has
4130 // done the rematch.
4131 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004132 }
4133 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004134
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004135 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004136 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004137 nai.onValidationStatusChanged(
4138 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4139 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004140
4141 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004142 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004143 // immediately. Re-notify partial connectivity silently if no internet
4144 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004145 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004146 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004147 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4148 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004149 }
4150
Chalard Jean254bd162022-08-25 13:04:51 +09004151 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004152 handleNetworkUnvalidated(nai);
4153 }
4154 }
4155
Calvin Ondada1452016-10-11 15:10:46 -07004156 private int getCaptivePortalMode() {
4157 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004158 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4159 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004160 }
4161
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004162 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4163 switch (msg.what) {
4164 default:
4165 return false;
4166 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4167 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4168 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4169 handleLingerComplete(nai);
4170 }
4171 break;
4172 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004173 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4174 handleNetworkAgentRegistered(msg);
4175 break;
4176 }
4177 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4178 handleNetworkAgentDisconnected(msg);
4179 break;
4180 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004181 }
4182 return true;
4183 }
4184
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004185 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004186 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004187 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004188 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004189 maybeHandleNetworkAgentMessage(msg);
4190 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004191 }
4192 }
4193
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004194 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004195 private final int mNetId;
4196 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004197
4198 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004199 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004200 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004201 }
4202
4203 @Override
4204 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4205 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004206 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004207 }
4208
4209 @Override
4210 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004211 // Legacy version of notifyNetworkTestedWithExtras.
4212 // Would only be called if the system has a NetworkStack module older than the
4213 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004214 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004215 }
4216
4217 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004218 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004219 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4220 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004221 final Message msg = mTrackerHandler.obtainMessage(
4222 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004223 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004224 new NetworkTestedResults(
4225 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004226 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004227
4228 // Invoke ConnectivityReport generation for this Network test event.
4229 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4230 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004231
Cody Kestingf1120be2020-08-03 18:01:40 -07004232 // NetworkMonitor reports the network validation result as a bitmask while
4233 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4234 // logical value for ConnectivityDiagnostics.
4235 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4236 p.result);
4237
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004238 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004239 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004240 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4241 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4242
Aaron Huang959d3642021-01-21 15:47:41 +08004243 ConnectivityReportEvent reportEvent =
4244 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4245 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004246 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004247 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004248 }
4249
4250 @Override
4251 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4252 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4253 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004254 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004255 }
4256
4257 @Override
lucasline117e2e2019-10-22 18:27:33 +08004258 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4259 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4260 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004261 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004262 }
4263
4264 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004265 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4266 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4267 EVENT_CAPPORT_DATA_CHANGED,
4268 0, mNetId, data));
4269 }
4270
4271 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004272 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004273 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004274 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004275
4276 final PendingIntent pendingIntent;
4277 // Only the system server can register notifications with package "android"
4278 final long token = Binder.clearCallingIdentity();
4279 try {
paulhu7746e4e2020-06-09 19:07:03 +08004280 pendingIntent = PendingIntent.getBroadcast(
4281 mContext,
4282 0 /* requestCode */,
4283 intent,
4284 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004285 } finally {
4286 Binder.restoreCallingIdentity(token);
4287 }
4288 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4289 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004290 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004291 }
4292
4293 @Override
4294 public void hideProvisioningNotification() {
4295 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004296 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004297 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004298
4299 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004300 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004301 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004302 }
4303
4304 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004305 public int getInterfaceVersion() {
4306 return this.VERSION;
4307 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004308
4309 @Override
4310 public String getInterfaceHash() {
4311 return this.HASH;
4312 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004313 }
4314
Cody Kestingf1120be2020-08-03 18:01:40 -07004315 /**
4316 * Converts the given NetworkMonitor-specific validation result bitmask to a
4317 * ConnectivityDiagnostics-specific validation result int.
4318 */
4319 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4320 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4321 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4322 }
4323 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4324 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4325 }
4326 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4327 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4328 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4329 }
4330
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004331 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004332 log("Data stall detected with methods: " + p.detectionMethod);
4333
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004334 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004335 int detectionMethod = 0;
4336 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4337 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4338 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4339 }
4340 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4341 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4342 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4343 p.tcpMetricsCollectionPeriodMillis);
4344 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004345 }
4346
Cody Kestingf53a0752020-04-15 12:33:28 -07004347 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004348 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004349 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004350
4351 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4352 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4353 // the cost of going through two handlers.
4354 mConnectivityDiagnosticsHandler.sendMessage(msg);
4355 }
4356
Cody Kestingb37958e2020-05-15 10:36:01 -07004357 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4358 return (p.detectionMethod & detectionMethod) != 0;
4359 }
4360
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004361 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4362 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004363 }
4364
Erik Klinea73af002018-06-26 18:53:43 +09004365 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4366 if (nai == null) return;
4367 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4368 // in order to restart a validation pass from within netd.
4369 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4370 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004371 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004372 }
4373 }
4374
Erik Kline31b4a9e2018-01-11 21:07:29 +09004375 private void handlePrivateDnsSettingsChanged() {
4376 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4377
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004378 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004379 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004380 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004381 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4382 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004383 }
4384 }
4385
Erik Kline9a62f012018-03-21 07:18:33 -07004386 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4387 // Private DNS only ever applies to networks that might provide
4388 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004389 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004390
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004391 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004392 // schedule DNS resolutions. If a DNS resolution is required the
4393 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004394 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004395
4396 // With Private DNS bypass support, we can proceed to update the
4397 // Private DNS config immediately, even if we're in strict mode
4398 // and have not yet resolved the provider name into a set of IPs.
4399 updatePrivateDns(nai, cfg);
4400 }
4401
4402 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4403 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004404 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004405 }
4406
dalyk1720e542018-03-05 12:42:22 -05004407 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4408 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4409 if (nai == null) {
4410 return;
4411 }
4412 mDnsManager.updatePrivateDnsValidation(update);
4413 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4414 }
4415
paulhu7c0a2e62021-01-08 00:51:49 +08004416 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004417 int prefixLength) {
4418 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4419 if (nai == null) return;
4420
paulhu7c0a2e62021-01-08 00:51:49 +08004421 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4422 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004423
4424 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004425 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004426 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004427 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004428 prefixLength);
4429 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004430 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004431 return;
4432 }
4433 }
4434
Lorenzo Colittid523d142020-04-01 20:16:30 +09004435 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004436 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4437 }
4438
Hai Shalome58bdc62021-01-11 18:45:34 -08004439 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004440 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004441 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004442 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4443 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4444 }
4445
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004446 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004447 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004448 * @param nai the agent info to update
4449 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004450 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004451 */
junyulai2b6f0c22021-02-03 20:15:30 +08004452 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4453 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4454 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004455 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004456 // one lingered request, set inactive.
4457 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004458 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004459 if (DBG) log("Unsetting inactive " + nai.toShortString());
4460 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004461 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004462 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004463 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004464 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4465 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004466 }
junyulai2b6f0c22021-02-03 20:15:30 +08004467 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004468 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004469 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004470 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004471 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004472 }
4473
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004474 private void handleNetworkAgentRegistered(Message msg) {
4475 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4476 if (!mNetworkAgentInfos.contains(nai)) {
4477 return;
4478 }
4479
4480 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4481 if (VDBG) log("NetworkAgent registered");
4482 } else {
4483 loge("Error connecting NetworkAgent");
4484 mNetworkAgentInfos.remove(nai);
4485 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004486 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004487 synchronized (mNetworkForNetId) {
4488 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004489 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004490 mNetIdManager.releaseNetId(nai.network.getNetId());
4491 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004492 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004493 }
4494 }
4495 }
Paul Jensend5f53392014-11-25 15:26:53 -05004496
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09004497 @VisibleForTesting
4498 protected static boolean shouldCreateNetworksImmediately() {
4499 // Before U, physical networks are only created when the agent advances to CONNECTED.
4500 // In U and above, all networks are immediately created when the agent is registered.
4501 return SdkLevel.isAtLeastU();
4502 }
4503
4504 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4505 @NonNull NetworkInfo.State state) {
4506 if (nai.isCreated()) return false;
4507 if (state == NetworkInfo.State.CONNECTED) return true;
4508 if (state != NetworkInfo.State.CONNECTING) {
4509 // TODO: throw if no WTFs are observed in the field.
4510 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4511 return false;
4512 }
4513 return nai.isVPN() || shouldCreateNetworksImmediately();
4514 }
4515
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004516 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004517 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004518 }
4519
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004520 @VisibleForTesting
4521 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004522 // T+ devices should use unregisterAfterReplacement.
he_won.hwang881307a2022-03-15 21:23:52 +09004523 if (SdkLevel.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004524
4525 // If the network never roamed, return false. The check below is not sufficient if time
4526 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4527 if (nai.lastRoamTime == 0) return false;
4528
he_won.hwang881307a2022-03-15 21:23:52 +09004529 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4530 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004531 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004532 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004533 final long currentTimeMs = SystemClock.elapsedRealtime();
4534 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004535 if (timeSinceLastRoam <= blockTimeOut) {
4536 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4537 return true;
4538 }
4539 }
4540 return false;
4541 }
4542
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004543 private void handleNetworkAgentDisconnected(Message msg) {
4544 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004545 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004546 }
4547
Chalard Jeand9fffc32018-05-11 20:19:20 +09004548 // Destroys a network, remove references to it from the internal state managed by
4549 // ConnectivityService, free its interfaces and clean up.
4550 // Must be called on the Handler thread.
4551 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004552 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004553
4554 if (!mNetworkAgentInfos.contains(nai)) return;
4555
Chalard Jeand9fffc32018-05-11 20:19:20 +09004556 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004557 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004558 }
lucaslinb25c9a62019-02-12 15:30:13 +08004559 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004560 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004561 // A network agent has disconnected.
4562 // TODO - if we move the logic to the network agent (have them disconnect
4563 // because they lost all their requests or because their score isn't good)
4564 // then they would disconnect organically, report their new state and then
4565 // disconnect the channel.
wangshengrjxtjcb9b5334d2023-05-09 09:51:06 +08004566 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004567 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4568 null, null);
4569 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004570 final boolean wasDefault = isDefaultNetwork(nai);
4571 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004572 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004573 }
4574 notifyIfacesChangedForNetworkStats();
4575 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4576 // by other networks that are already connected. Perhaps that can be done by
4577 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4578 // of rematchAllNetworksAndRequests
4579 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004580 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004581
4582 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004583 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4584 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08004585 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004586 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004587 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004588 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004589 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004590 synchronized (mNetworkForNetId) {
4591 // Remove the NetworkAgent, but don't mark the netId as
4592 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004593 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004594 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004595 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08004596 // Update allowed network lists in netd. This should be called after removing nai
4597 // from mNetworkAgentInfos.
4598 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004599 // Remove all previously satisfied requests.
4600 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004601 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004602 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004603 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004604 if (currentNetwork != null
4605 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004606 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004607 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4608 // rematch not to keep disconnected agents instead of setting it here ; this
4609 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004610 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004611 for (final NetworkOfferInfo noi : mNetworkOffers) {
4612 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004613 }
James Mattise3ef1912020-12-20 11:09:58 -08004614
Chalard Jean5b409c72021-02-04 13:12:59 +09004615 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004616 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004617 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004618 // network, because while incorrect this is the closest to the old (also
4619 // incorrect) behavior.
4620 mNetworkActivityTracker.updateDataActivityTracking(
4621 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004622 ensureNetworkTransitionWakelock(nai.toShortString());
4623 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004624 }
4625 }
junyulai2b6f0c22021-02-03 20:15:30 +08004626 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004627 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004628 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004629 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004630 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004631 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004632 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004633
4634 // Immediate teardown.
4635 if (nai.teardownDelayMs == 0) {
4636 destroyNetwork(nai);
4637 return;
4638 }
4639
4640 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004641 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304642 try {
4643 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4644 } catch (RemoteException e) {
4645 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4646 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004647 }
4648 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4649 }
4650
4651 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004652 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004653 // Tell netd to clean up the configuration for this network
4654 // (routing rules, DNS, etc).
4655 // This may be slow as it requires a lot of netd shelling out to ip and
4656 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004657 // after we've rematched networks with requests (which might change the default
4658 // network or service a new request from an app), so network traffic isn't interrupted
4659 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004660 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004661 }
Chalard Jean254bd162022-08-25 13:04:51 +09004662 if (!nai.isCreated() && !SdkLevel.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004663 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4664 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4665 // false if the network was never created.
4666 // TODO: delete when S is no longer supported.
4667 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004668 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004669 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004670 }
4671
Ken Chen6df7a902021-04-09 15:08:42 +08004672 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004673 try {
4674 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004675 final NativeNetworkConfig config;
4676 if (nai.isVPN()) {
4677 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004678 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004679 return false;
4680 }
4681 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4682 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004683 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08004684 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004685 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004686 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004687 getNetworkPermission(nai.networkCapabilities),
4688 false /* secure */,
4689 VpnManager.TYPE_VPN_NONE,
4690 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08004691 }
Ken Chen6df7a902021-04-09 15:08:42 +08004692 mNetd.networkCreate(config);
4693 mDnsResolver.createNetworkCache(nai.network.getNetId());
4694 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4695 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004696 return true;
4697 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004698 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004699 return false;
4700 }
4701 }
4702
Ken Chen6df7a902021-04-09 15:08:42 +08004703 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004704 if (mDscpPolicyTracker != null) {
4705 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
4706 }
Luke Huangfdd11f82019-04-09 18:41:49 +08004707 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004708 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004709 } catch (RemoteException | ServiceSpecificException e) {
4710 loge("Exception destroying network(networkDestroy): " + e);
4711 }
4712 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004713 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004714 } catch (RemoteException | ServiceSpecificException e) {
4715 loge("Exception destroying network: " + e);
4716 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004717 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
4718 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
4719 // gets created, could add data to DnsManager data structures that will never get deleted.
4720 mDnsManager.removeNetwork(nai.network);
4721
4722 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09004723 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004724 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
4725 }
4726
Chalard Jean254bd162022-08-25 13:04:51 +09004727 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004728 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08004729 }
4730
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004731 // If this method proves to be too slow then we can maintain a separate
4732 // pendingIntent => NetworkRequestInfo map.
4733 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4734 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004735 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4736 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4737 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004738 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004739 return entry.getValue();
4740 }
4741 }
4742 return null;
4743 }
4744
Chalard Jean524f0b12021-10-25 21:11:56 +09004745 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4746 if (SdkLevel.isAtLeastT()) {
4747 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4748 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4749 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4750 // bug is fixed.
4751 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004752 throw new IllegalStateException("This NRI is already registered. New : " + nri
4753 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004754 }
4755 }
4756 }
4757 }
4758
Chalard Jeanac9ace02022-01-26 16:54:05 +09004759 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4760 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08004761 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004762 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4763 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004764 }
4765 return false;
4766 }
4767
James Mattisf7027322020-12-13 16:28:14 -08004768 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004769 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004770 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4771 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4772 final NetworkRequestInfo existingRequest =
4773 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004774 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004775 if (DBG) {
4776 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4777 + nri.mRequests.get(0) + " because their intents matched.");
4778 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004779 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004780 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004781 }
Erik Kline05f2b402015-04-30 12:58:40 +09004782 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004783 }
4784
James Mattisf7027322020-12-13 16:28:14 -08004785 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004786 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004787 }
4788
James Mattis3ce3d3c2021-02-09 18:18:28 -08004789 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004790 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004791 for (final NetworkRequestInfo nri : nris) {
4792 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004793 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004794 for (final NetworkRequest req : nri.mRequests) {
4795 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004796 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004797 if (req.isListen()) {
4798 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4799 if (req.networkCapabilities.hasSignalStrength()
4800 && network.satisfiesImmutableCapabilitiesOf(req)) {
4801 updateSignalStrengthThresholds(network, "REGISTER", req);
4802 }
James Mattisf7027322020-12-13 16:28:14 -08004803 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004804 }
4805 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004806
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004807 // If this NRI has a satisfier already, it is replacing an older request that
4808 // has been removed. Track it.
4809 final NetworkRequest activeRequest = nri.getActiveRequest();
4810 if (null != activeRequest) {
4811 // If there is an active request, then for sure there is a satisfier.
4812 nri.getSatisfier().addRequest(activeRequest);
4813 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004814 }
James Mattisf7027322020-12-13 16:28:14 -08004815
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004816 if (mFlags.noRematchAllRequestsOnRegister()) {
4817 rematchNetworksAndRequests(nris);
4818 } else {
4819 rematchAllNetworksAndRequests();
4820 }
James Mattis45d81842021-01-10 14:24:24 -08004821
Chalard Jean0354d8c2021-01-12 10:58:56 +09004822 // Requests that have not been matched to a network will not have been sent to the
4823 // providers, because the old satisfier and the new satisfier are the same (null in this
4824 // case). Send these requests to the providers.
4825 for (final NetworkRequestInfo nri : nris) {
4826 for (final NetworkOfferInfo noi : mNetworkOffers) {
4827 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004828 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004829 }
4830 }
4831
James Mattisf7027322020-12-13 16:28:14 -08004832 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4833 final int callingUid) {
4834 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004835 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004836 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4837 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4838 handleReleaseNetworkRequest(
4839 nri.mRequests.get(0),
4840 callingUid,
4841 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004842 }
4843 }
4844
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004845 // Determines whether the network is the best (or could become the best, if it validated), for
4846 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4847 // on the value of reason:
4848 //
4849 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4850 // then it should be torn down.
4851 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4852 // then it should be lingered.
4853 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004854 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004855
Chalard Jean254bd162022-08-25 13:04:51 +09004856 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09004857 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4858 return false;
4859 }
4860
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004861 final int numRequests;
4862 switch (reason) {
4863 case TEARDOWN:
4864 numRequests = nai.numRequestNetworkRequests();
4865 break;
4866 case LINGER:
4867 numRequests = nai.numForegroundNetworkRequests();
4868 break;
4869 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004870 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004871 return true;
4872 }
4873
Chalard Jean947acd42021-03-08 22:29:27 +09004874 if (numRequests > 0) return false;
4875
Paul Jensende49eb12015-06-25 15:30:08 -04004876 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004877 if (reason == UnneededFor.LINGER
4878 && !nri.isMultilayerRequest()
4879 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004880 // Background requests don't affect lingering.
4881 continue;
4882 }
4883
James Mattis3d229892020-11-16 16:46:28 -08004884 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004885 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004886 }
4887 }
Paul Jensende49eb12015-06-25 15:30:08 -04004888 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004889 }
4890
James Mattis3d229892020-11-16 16:46:28 -08004891 private boolean isNetworkPotentialSatisfier(
4892 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4893 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004894 // request, return immediately. For multilayer requests, check to see if any of the
4895 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004896 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4897 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004898 return false;
4899 }
4900 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004901 // This multilayer listen request is satisfied therefore no further requests need to be
4902 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004903 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004904 return false;
4905 }
James Mattis3d229892020-11-16 16:46:28 -08004906 // As non-multilayer listen requests have already returned, the below would only happen
4907 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004908 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004909 continue;
4910 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09004911 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08004912 // there is hope for it to become one if it validated, then it is needed.
4913 if (candidate.satisfies(req)) {
4914 // As soon as a network is found that satisfies a request, return. Specifically for
4915 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4916 // is important so as to not evaluate lower priority requests further in
4917 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004918 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4919 ? nri.getSatisfier() : null;
4920 // Note that this catches two important cases:
4921 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4922 // is currently satisfying the request. This is desirable when
4923 // cellular ends up validating but WiFi does not.
4924 // 2. Unvalidated WiFi will not be reaped when validated cellular
4925 // is currently satisfying the request. This is desirable when
4926 // WiFi ends up validating and out scoring cellular.
4927 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004928 }
4929 }
4930
4931 return false;
4932 }
4933
Erik Kline0c04b742016-07-07 16:50:58 +09004934 private NetworkRequestInfo getNriForAppRequest(
4935 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004936 // Looking up the app passed param request in mRequests isn't possible since it may return
4937 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4938 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004939 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4940 // to avoid potential race conditions when validating a package->uid mapping when sending
4941 // the callback on the very low-chance that an application shuts down prior to the callback
4942 // being sent.
4943 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4944 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004945
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004946 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004947 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004948 log(String.format("UID %d attempted to %s for unowned request %s",
4949 callingUid, requestedOperation, nri));
4950 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004951 }
Erik Kline0c04b742016-07-07 16:50:58 +09004952 }
4953
4954 return nri;
4955 }
4956
James Mattisf7027322020-12-13 16:28:14 -08004957 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4958 final String callingMethod) {
4959 if (nri.isMultilayerRequest()) {
4960 throw new IllegalStateException(
4961 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004962 }
4963 }
4964
James Mattisf7027322020-12-13 16:28:14 -08004965 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004966 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004967 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4968 // single NetworkRequest and thus does not apply to multilayer requests.
4969 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4970 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004971 return;
4972 }
James Mattis2516da32021-01-31 17:06:19 -08004973 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004974 return;
4975 }
James Mattisf7027322020-12-13 16:28:14 -08004976 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4977 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004978 }
4979 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004980 callCallbackForRequest(
4981 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004982 }
4983
James Mattisf7027322020-12-13 16:28:14 -08004984 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4985 final int callingUid,
4986 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004987 final NetworkRequestInfo nri =
4988 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4989 if (nri == null) {
4990 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004991 }
James Mattisf7027322020-12-13 16:28:14 -08004992 if (VDBG || (DBG && request.isRequest())) {
4993 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004994 }
4995 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004996 if (callOnUnavailable) {
4997 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4998 }
Erik Kline155a59a2015-11-25 12:49:38 +09004999 }
Erik Kline0c04b742016-07-07 16:50:58 +09005000
James Mattisa076c532020-12-02 14:12:41 -08005001 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005002 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005003 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005004 if (null == mNetworkRequests.remove(req)) {
5005 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5006 continue;
5007 }
James Mattisa076c532020-12-02 14:12:41 -08005008 if (req.isListen()) {
5009 removeListenRequestFromNetworks(req);
5010 }
5011 }
James Mattis8f036802021-06-20 16:26:01 -07005012 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005013 if (mDefaultNetworkRequests.remove(nri)) {
5014 // If this request was one of the defaults, then the UID rules need to be updated
5015 // WARNING : if the app(s) for which this network request is the default are doing
5016 // traffic, this will kill their connected sockets, even if an equivalent request
5017 // is going to be reinstated right away ; unconnected traffic will go on the default
5018 // until the new default is set, which will happen very soon.
5019 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5020 // remove ranges for those requests that won't have a replacement
5021 final NetworkAgentInfo satisfier = nri.getSatisfier();
5022 if (null != satisfier) {
5023 try {
paulhu0e79d952021-06-09 16:11:35 +08005024 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5025 satisfier.network.getNetId(),
5026 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005027 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005028 } catch (RemoteException e) {
5029 loge("Exception setting network preference default network", e);
5030 }
5031 }
5032 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005033
Junyu Lai00d92df2022-07-05 11:01:52 +08005034 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005035 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005036 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005037
5038 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005039 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005040 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005041 }
5042 }
5043
Chalard Jean0354d8c2021-01-12 10:58:56 +09005044 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5045 // needed for this offer.
5046 for (final NetworkOfferInfo noi : mNetworkOffers) {
5047 for (final NetworkRequest req : nri.mRequests) {
5048 if (req.isRequest() && noi.offer.neededFor(req)) {
5049 noi.offer.onNetworkUnneeded(req);
5050 }
5051 }
5052 }
James Mattisa076c532020-12-02 14:12:41 -08005053 }
5054
James Mattis3ce3d3c2021-02-09 18:18:28 -08005055 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5056 for (final NetworkRequestInfo nri : nris) {
5057 if (mDefaultRequest == nri) {
5058 // Make sure we never remove the default request.
5059 continue;
5060 }
5061 handleRemoveNetworkRequest(nri);
5062 }
5063 }
5064
James Mattisa076c532020-12-02 14:12:41 -08005065 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5066 // listens don't have a singular affected Network. Check all networks to see
5067 // if this listen request applies and remove it.
5068 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5069 nai.removeRequest(req.requestId);
5070 if (req.networkCapabilities.hasSignalStrength()
5071 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5072 updateSignalStrengthThresholds(nai, "RELEASE", req);
5073 }
5074 }
5075 }
5076
5077 /**
5078 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5079 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5080 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5081 */
5082 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5083 boolean wasKept = false;
5084 final NetworkAgentInfo nai = nri.getSatisfier();
5085 if (nai != null) {
5086 final int requestLegacyType = nri.getActiveRequest().legacyType;
5087 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5088 nai.removeRequest(nri.getActiveRequest().requestId);
5089 if (VDBG || DDBG) {
5090 log(" Removing from current network " + nai.toShortString()
5091 + ", leaving " + nai.numNetworkRequests() + " requests.");
5092 }
5093 // If there are still lingered requests on this network, don't tear it down,
5094 // but resume lingering instead.
5095 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005096 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005097 notifyNetworkLosing(nai, now);
5098 }
5099 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5100 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5101 teardownUnneededNetwork(nai);
5102 } else {
5103 wasKept = true;
5104 }
James Mattisa076c532020-12-02 14:12:41 -08005105 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5106 // Went from foreground to background.
5107 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005108 }
5109
Erik Kline0c04b742016-07-07 16:50:58 +09005110 // Maintain the illusion. When this request arrived, we might have pretended
5111 // that a network connected to serve it, even though the network was already
5112 // connected. Now that this request has gone away, we might have to pretend
5113 // that the network disconnected. LegacyTypeTracker will generate that
5114 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005115 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005116 boolean doRemove = true;
5117 if (wasKept) {
5118 // check if any of the remaining requests for this network are for the
5119 // same legacy type - if so, don't remove the nai
5120 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5121 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005122 if (otherRequest.legacyType == requestLegacyType
5123 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005124 if (DBG) log(" still have other legacy request - leaving");
5125 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005126 }
5127 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005128 }
5129
Erik Kline0c04b742016-07-07 16:50:58 +09005130 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005131 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005132 }
5133 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005134 }
5135 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005136
Junyu Lai00d92df2022-07-05 11:01:52 +08005137 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005138 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005139 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5140 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5141 }
5142
Lorenzo Colittid6459092016-07-04 12:55:44 +09005143 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005144 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005145 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005146 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005147 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005148 }
5149
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005150 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005151 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5152 enforceNetworkStackSettingsOrSetup();
5153 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5154 encodeBool(accept), encodeBool(always), network));
5155 }
5156
5157 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005158 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005159 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005160 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5161 }
5162
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005163 @Override
5164 public void setTestAllowBadWifiUntil(long timeMs) {
5165 enforceSettingsPermission();
5166 if (!Build.isDebuggable()) {
5167 throw new IllegalStateException("Does not support in non-debuggable build");
5168 }
5169
5170 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5171 throw new IllegalArgumentException("It should not exceed "
5172 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5173 }
5174
5175 mHandler.sendMessage(
5176 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5177 }
5178
chiachangwange0192a72023-02-06 13:25:01 +00005179 @Override
5180 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5181 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005182
5183 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5184 throw new IllegalArgumentException("Argument should not exceed "
5185 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5186 }
5187
5188 mHandler.sendMessage(
5189 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5190 }
5191
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005192 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5193 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5194 " accept=" + accept + " always=" + always);
5195
5196 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5197 if (nai == null) {
5198 // Nothing to do.
5199 return;
5200 }
5201
Chalard Jean254bd162022-08-25 13:04:51 +09005202 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005203 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005204 return;
5205 }
5206
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005207 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005208 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005209 }
5210
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005211 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5212 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005213 // If network becomes partial connectivity and user already accepted to use this
5214 // network, we should respect the user's option and don't need to popup the
5215 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005216 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005217 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005218 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005219 }
5220
5221 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005222 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005223 }
5224
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005225 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005226 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005227 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005228 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005229 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005230 }
5231
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005232 }
5233
lucaslin2240ef62019-03-12 13:08:03 +08005234 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5235 boolean always) {
5236 if (DBG) {
5237 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5238 + " always=" + always);
5239 }
5240
5241 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5242 if (nai == null) {
5243 // Nothing to do.
5244 return;
5245 }
5246
Chalard Jean254bd162022-08-25 13:04:51 +09005247 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005248 // The network validated while the dialog box was up. Take no action.
5249 return;
5250 }
5251
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005252 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5253 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005254 }
5255
5256 // TODO: Use the current design or save the user choice into IpMemoryStore.
5257 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005258 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005259 }
5260
5261 if (!accept) {
5262 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005263 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005264 // Tear down the network.
5265 teardownUnneededNetwork(nai);
5266 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005267 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5268 // result in a partial connectivity result which will be processed by
5269 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005270 //
5271 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5272 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005273 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005274 }
5275 }
5276
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005277 private void handleSetAvoidUnvalidated(Network network) {
5278 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005279 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005280 // Nothing to do. The network either disconnected or revalidated.
5281 return;
5282 }
Chalard Jean254bd162022-08-25 13:04:51 +09005283 if (0L == nai.getAvoidUnvalidated()) {
5284 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005285 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005286 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005287 }
5288 }
5289
Chalard Jean5fb43c72022-09-08 19:03:14 +09005290 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005291 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005292 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean1f2b50f2023-05-15 17:26:13 +09005293 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005294 }
5295
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005296 @Override
5297 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005298 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005299 mHandler.post(() -> {
5300 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5301 if (nai == null) return;
5302 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005303 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005304 });
5305 }
5306
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005307 /**
5308 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5309 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005310 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005311 * @param appExtras Bundle to use as intent extras for the captive portal application.
5312 * Must be treated as opaque to avoid preventing the captive portal app to
5313 * update its arguments.
5314 */
5315 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005316 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005317 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5318 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005319
5320 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5321 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005322 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5323 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005324 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5325
lucaslin75ff7022020-12-17 04:14:35 +08005326 final long token = Binder.clearCallingIdentity();
5327 try {
5328 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5329 } finally {
5330 Binder.restoreCallingIdentity(token);
5331 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005332 }
5333
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005334 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5335 private final Network mNetwork;
5336
5337 private CaptivePortalImpl(Network network) {
5338 mNetwork = network;
5339 }
5340
5341 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005342 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005343 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5344 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005345 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5346 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5347 // Since the network will be disconnected, skip notifying NetworkMonitor
5348 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005349 }
5350
Chiachang Wang938bfba2020-01-09 13:50:55 +08005351 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005352 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005353 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005354 }
5355
5356 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005357 public void appRequest(final int request) {
5358 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5359 if (nm == null) return;
5360
5361 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005362 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005363 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005364 }
5365 }
5366
5367 @Nullable
5368 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5369 // getNetworkAgentInfoForNetwork is thread-safe
5370 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5371 if (nai == null) return null;
5372
5373 // nai.networkMonitor() is thread-safe
5374 return nai.networkMonitor();
5375 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005376 }
5377
Hugo Benichic9048bc2016-09-14 23:23:08 +00005378 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005379 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005380 }
5381
Chalard Jean020b93a2022-09-01 13:20:14 +09005382 private boolean activelyPreferBadWifi() {
5383 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5384 }
5385
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005386 /**
5387 * Return whether the device should maintain continuous, working connectivity by switching away
5388 * from WiFi networks having no connectivity.
5389 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5390 */
5391 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005392 if (!checkNetworkStackPermission()) {
5393 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5394 }
5395 return avoidBadWifi();
5396 }
5397
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005398 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005399 ensureRunningOnConnectivityServiceThread();
5400 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005401 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005402 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005403 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005404 if (avoidBadWifi) {
5405 // If the device is now avoiding bad wifi, remove notifications that might have
5406 // been put up when the device didn't.
5407 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5408 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005409 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005410 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5411 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5412 for (final NetworkOfferInfo noi : offersToUpdate) {
5413 updateOfferScore(noi.offer);
5414 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005415 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005416 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005417 }
5418
Erik Kline95ecfee2016-10-02 18:02:14 +09005419 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005420 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005421 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005422 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005423 if (!configRestrict) {
5424 pw.println("Bad Wi-Fi avoidance: unrestricted");
5425 return;
5426 }
5427
5428 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5429 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005430 pw.println("Config restrict: " + configRestrict);
5431 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005432
Chalard Jeane0fdea32022-09-14 21:44:22 +09005433 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005434 String description;
5435 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005436 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005437 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005438 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005439 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005440 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005441 description = "avoid";
5442 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005443 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005444 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005445 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005446
5447 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5448 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005449 if (null == configValue) {
5450 description = "unset";
5451 } else if (configValue) {
5452 description = "force true";
5453 } else {
5454 description = "force false";
5455 }
5456 pw.println("Actively prefer bad wifi conf: " + description);
5457 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005458 pw.println("Network overrides:");
5459 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005460 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005461 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005462 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005463 }
5464 }
5465 pw.decreaseIndent();
5466 pw.decreaseIndent();
5467 }
5468
paulhu7746e4e2020-06-09 19:07:03 +08005469 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5470 // unify the method.
5471 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5472 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5473 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5474 return settingsComponent != null
5475 ? settingsComponent.getPackageName() : "com.android.settings";
5476 }
5477
lucaslinb1e8e382019-01-24 15:55:30 +08005478 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005479 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005480 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005481 switch (type) {
5482 case NO_INTERNET:
5483 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005484 // High priority because it is only displayed for explicitly selected networks.
5485 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005486 break;
lucasline117e2e2019-10-22 18:27:33 +08005487 case PRIVATE_DNS_BROKEN:
5488 action = Settings.ACTION_WIRELESS_SETTINGS;
5489 // High priority because we should let user know why there is no internet.
5490 highPriority = true;
5491 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005492 case LOST_INTERNET:
5493 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005494 // High priority because it could help the user avoid unexpected data usage.
5495 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005496 break;
lucaslin2240ef62019-03-12 13:08:03 +08005497 case PARTIAL_CONNECTIVITY:
5498 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005499 // Don't bother the user with a high-priority notification if the network was not
5500 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005501 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005502 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005503 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005504 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005505 return;
5506 }
5507
5508 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005509 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005510 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005511 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005512 // Some OEMs have their own Settings package. Thus, need to get the current using
5513 // Settings package name instead of just use default name "com.android.settings".
5514 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5515 intent.setClassName(settingsPkgName,
5516 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005517 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005518
paulhu2af50222020-10-11 22:52:27 +08005519 PendingIntent pendingIntent = PendingIntent.getActivity(
5520 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005521 0 /* requestCode */,
5522 intent,
paulhu2af50222020-10-11 22:52:27 +08005523 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005524
Serik Beketayevec8ad212020-12-07 22:43:07 -08005525 mNotifier.showNotification(
5526 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005527 }
5528
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005529 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5530 // Don't prompt if the network is validated, and don't prompt on captive portals
5531 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005532 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005533 return false;
5534 }
5535
5536 // If a network has partial connectivity, always prompt unless the user has already accepted
5537 // partial connectivity and selected don't ask again. This ensures that if the device
5538 // automatically connects to a network that has partial Internet access, the user will
5539 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005540 // because we have prompted them.
5541 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005542 return true;
5543 }
5544
5545 // If a network has no Internet access, only prompt if the network was explicitly selected
5546 // and if the user has not already told us to use the network regardless of whether it
5547 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005548 if (nai.networkAgentConfig.explicitlySelected
5549 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005550 return true;
5551 }
5552
5553 return false;
5554 }
5555
Chalard Jean5fb43c72022-09-08 19:03:14 +09005556 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5557 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005558
Chalard Jean5fb43c72022-09-08 19:03:14 +09005559 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5560 if (null == nai) return;
5561
5562 if (nai.setEvaluated()) {
5563 // If setEvaluated() returned true, the network never had any form of connectivity.
5564 // This may have an impact on request matching if bad WiFi avoidance is off and the
5565 // network was found not to have Internet access.
5566 nai.updateScoreForNetworkAgentUpdate();
5567 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005568
5569 // Also, if this is WiFi and it should be preferred actively, now is the time to
5570 // prompt the user that they walked past and connected to a bad WiFi.
5571 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5572 && !avoidBadWifi()
5573 && activelyPreferBadWifi()) {
5574 // The notification will be removed if the network validates or disconnects.
5575 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5576 return;
5577 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005578 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005579
Chalard Jean5fb43c72022-09-08 19:03:14 +09005580 if (!shouldPromptUnvalidated(nai)) return;
5581
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005582 // Stop automatically reconnecting to this network in the future. Automatically connecting
5583 // to a network that provides no or limited connectivity is not useful, because the user
5584 // cannot use that network except through the notification shown by this method, and the
5585 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005586 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005587
Chalard Jean254bd162022-08-25 13:04:51 +09005588 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005589 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005590 } else {
5591 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5592 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005593 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005594
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005595 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5596 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005597 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005598
lucaslin2240ef62019-03-12 13:08:03 +08005599 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5600 return;
5601 }
5602
5603 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005604 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005605 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005606 }
5607
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005608 @Override
5609 public int getMultipathPreference(Network network) {
5610 enforceAccessPermission();
5611
5612 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005613 if (nai != null && nai.networkCapabilities
5614 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005615 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5616 }
5617
Aaron Huang9a57acf2020-12-08 10:03:29 +08005618 final NetworkPolicyManager netPolicyManager =
5619 mContext.getSystemService(NetworkPolicyManager.class);
5620
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005621 final long token = Binder.clearCallingIdentity();
5622 final int networkPreference;
5623 try {
5624 networkPreference = netPolicyManager.getMultipathPreference(network);
5625 } finally {
5626 Binder.restoreCallingIdentity(token);
5627 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005628 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005629 return networkPreference;
5630 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005631 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5632 }
5633
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005634 @Override
5635 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005636 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005637 }
5638
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005639 private class InternalHandler extends Handler {
5640 public InternalHandler(Looper looper) {
5641 super(looper);
5642 }
5643
5644 @Override
5645 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005646 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005647 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005648 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005649 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005650 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005651 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005652 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005653 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005654 break;
5655 }
Jason Monka69f1b02013-10-10 14:02:51 -04005656 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005657 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5658 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005659 break;
5660 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005661 case EVENT_REGISTER_NETWORK_PROVIDER: {
5662 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005663 break;
5664 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005665 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5666 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005667 break;
5668 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005669 case EVENT_REGISTER_NETWORK_OFFER: {
5670 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5671 break;
5672 }
5673 case EVENT_UNREGISTER_NETWORK_OFFER: {
5674 final NetworkOfferInfo offer =
5675 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5676 if (null != offer) {
5677 handleUnregisterNetworkOffer(offer);
5678 }
5679 break;
5680 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005681 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005682 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5683 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5684 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005685 break;
5686 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005687 case EVENT_REGISTER_NETWORK_REQUEST:
5688 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005689 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005690 break;
5691 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005692 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5693 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005694 handleRegisterNetworkRequestWithIntent(msg);
5695 break;
5696 }
Erik Kline155a59a2015-11-25 12:49:38 +09005697 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5698 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5699 handleTimedOutNetworkRequest(nri);
5700 break;
5701 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005702 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5703 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5704 break;
5705 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005706 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005707 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5708 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005709 break;
5710 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005711 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005712 Network network = (Network) msg.obj;
5713 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005714 break;
5715 }
lucaslin2240ef62019-03-12 13:08:03 +08005716 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5717 Network network = (Network) msg.obj;
5718 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5719 toBool(msg.arg2));
5720 break;
5721 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005722 case EVENT_SET_AVOID_UNVALIDATED: {
5723 handleSetAvoidUnvalidated((Network) msg.obj);
5724 break;
5725 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09005726 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
5727 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005728 break;
5729 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005730 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5731 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005732 break;
5733 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00005734 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
5735 // handler thread.
5736 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005737 mKeepaliveTracker.handleStartKeepalive(msg);
5738 break;
5739 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00005740 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09005741 final AutomaticOnOffKeepalive ki =
5742 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
5743 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005744
chiachangwang676c84e2023-02-14 09:22:05 +00005745 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005746 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005747 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00005748 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005749 for (NetworkAgentInfo n : mNetworkAgentInfos) {
5750 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00005751 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
5752 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005753 }
5754 }
5755
5756 // If the network no longer exists, then the keepalive should have been
5757 // cleaned up already. There is no point trying to resume keepalives.
5758 if (!networkFound) return;
5759
chiachangwang676c84e2023-02-14 09:22:05 +00005760 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005761 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang676c84e2023-02-14 09:22:05 +00005762 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005763 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00005764 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005765 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005766 }
5767 break;
5768 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005769 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005770 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09005771 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
5772 (IBinder) msg.obj);
5773 if (ki == null) {
5774 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00005775 return;
5776 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09005777 final int reason = msg.arg2;
5778 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005779 break;
5780 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005781 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5782 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5783 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005784 break;
5785 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005786 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5787 handlePrivateDnsSettingsChanged();
5788 break;
dalyk1720e542018-03-05 12:42:22 -05005789 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5790 handlePrivateDnsValidationUpdate(
5791 (PrivateDnsValidationUpdate) msg.obj);
5792 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005793 case EVENT_UID_BLOCKED_REASON_CHANGED:
5794 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005795 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005796 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5797 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5798 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005799 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005800 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5801 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005802 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005803 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005804 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005805 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09005806 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
5807 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005808 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005809 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005810 }
lucaslin1193a5d2021-01-21 02:04:15 +08005811 case EVENT_REPORT_NETWORK_ACTIVITY:
5812 mNetworkActivityTracker.handleReportNetworkActivity();
5813 break;
paulhu51f77dc2021-06-07 02:34:20 +00005814 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5815 handleMobileDataPreferredUidsChanged();
5816 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005817 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5818 final long timeMs = ((Long) msg.obj).longValue();
5819 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5820 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005821 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5822 handleIngressRateLimitChanged();
5823 break;
Hansen Kurli55396972022-10-28 03:31:17 +00005824 case EVENT_USER_DOES_NOT_WANT:
5825 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5826 if (nai == null) break;
5827 nai.onPreventAutomaticReconnect();
5828 nai.disconnect();
5829 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00005830 case EVENT_SET_VPN_NETWORK_PREFERENCE:
5831 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
5832 break;
chiachangwange0192a72023-02-06 13:25:01 +00005833 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
5834 final long time = ((Long) msg.obj).longValue();
5835 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
5836 break;
5837 }
Mark Fasheh7501e762023-05-04 20:23:11 +00005838 case EVENT_UID_FROZEN_STATE_CHANGED:
5839 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
5840 handleFrozenUids(args.mUids, args.mFrozenStates);
5841 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005842 }
5843 }
5844 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005845
Lorenzo Colittid6459092016-07-04 12:55:44 +09005846 @Override
markchien5776f962019-12-16 20:15:20 +08005847 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005848 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08005849 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005850 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5851 Context.TETHERING_SERVICE);
5852 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005853 }
5854
Lorenzo Colittid6459092016-07-04 12:55:44 +09005855 @Override
markchien5776f962019-12-16 20:15:20 +08005856 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005857 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08005858 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005859 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5860 Context.TETHERING_SERVICE);
5861 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005862 }
5863
Lorenzo Colittid6459092016-07-04 12:55:44 +09005864 @Override
markchien5776f962019-12-16 20:15:20 +08005865 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005866 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005867 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005868 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5869 Context.TETHERING_SERVICE);
5870 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005871 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005872
markchien5776f962019-12-16 20:15:20 +08005873
Lorenzo Colittid6459092016-07-04 12:55:44 +09005874 @Override
markchien5776f962019-12-16 20:15:20 +08005875 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005876 public String[] getTetheringErroredIfaces() {
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
5881 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005882 }
5883
Lorenzo Colittid6459092016-07-04 12:55:44 +09005884 @Override
markchien5776f962019-12-16 20:15:20 +08005885 @Deprecated
5886 public String[] getTetherableUsbRegexs() {
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.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005892 }
5893
Udam Saini8f7d6a72017-06-07 12:06:28 -07005894 @Override
markchien5776f962019-12-16 20:15:20 +08005895 @Deprecated
5896 public String[] getTetherableWifiRegexs() {
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 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005901 }
5902
Robert Greenwalte0b00512014-07-02 09:59:16 -07005903 // Called when we lose the default network and have no replacement yet.
5904 // This will automatically be cleared after X seconds or a new default network
5905 // becomes CONNECTED, whichever happens first. The timer is started by the
5906 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005907 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005908 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005909 if (mNetTransitionWakeLock.isHeld()) {
5910 return;
5911 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005912 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005913 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5914 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005915 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005916 mWakelockLogs.log("ACQUIRE for " + forWhom);
5917 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005918 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005919 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005920 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005921 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005922
Hugo Benichi471b62a2017-03-30 23:18:10 +09005923 // Called when we gain a new default network to release the network transition wakelock in a
5924 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5925 // message is cancelled.
5926 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005927 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005928 if (!mNetTransitionWakeLock.isHeld()) {
5929 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005930 }
5931 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005932 // Cancel self timeout on wakelock hold.
5933 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5934 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5935 mHandler.sendMessageDelayed(msg, 1000);
5936 }
5937
5938 // Called when either message of ensureNetworkTransitionWakelock or
5939 // scheduleReleaseNetworkTransitionWakelock is processed.
5940 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5941 String event = eventName(eventId);
5942 synchronized (this) {
5943 if (!mNetTransitionWakeLock.isHeld()) {
5944 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005945 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005946 return;
5947 }
5948 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005949 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5950 mTotalWakelockDurationMs += lockDuration;
5951 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5952 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005953 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005954 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005955 }
5956
Robert Greenwalt986c7412010-09-08 15:24:47 -07005957 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005958 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005959 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005960 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005961 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005962 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005963 }
5964
Lorenzo Colittid6459092016-07-04 12:55:44 +09005965 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005966 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005967 enforceAccessPermission();
5968 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005969 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005970 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005971
5972 final NetworkAgentInfo nai;
5973 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005974 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005975 } else {
5976 nai = getNetworkAgentInfoForNetwork(network);
5977 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005978
5979 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005980 mHandler.obtainMessage(
5981 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005982 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005983
Hugo Benichid6b510a2017-04-06 17:22:18 +09005984 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005985 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005986 if (nai == null
5987 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005988 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005989 return;
5990 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005991 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09005992 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005993 mConnectivityDiagnosticsHandler.sendMessage(
5994 mConnectivityDiagnosticsHandler.obtainMessage(
5995 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5996 new ReportedNetworkConnectivityInfo(
5997 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005998 return;
5999 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006000 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006001 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006002 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006003 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006004 // Validating a network that has not yet connected could result in a call to
6005 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006006 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006007 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006008 }
paulhu7aeba372020-12-30 00:42:19 +08006009 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6010 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006011 return;
6012 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006013
6014 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6015 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6016 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6017 // completed.
6018 mConnectivityDiagnosticsHandler.sendMessage(
6019 mConnectivityDiagnosticsHandler.obtainMessage(
6020 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6021 new ReportedNetworkConnectivityInfo(
6022 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006023 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006024 }
6025
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006026 // TODO: call into netd.
6027 private boolean queryUserAccess(int uid, Network network) {
6028 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6029 if (nai == null) return false;
6030
6031 // Any UID can use its default network.
6032 if (nai == getDefaultNetworkForUid(uid)) return true;
6033
6034 // Privileged apps can use any network.
6035 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6036 return true;
6037 }
6038
6039 // An unprivileged UID can use a VPN iff the VPN applies to it.
6040 if (nai.isVPN()) {
6041 return nai.networkCapabilities.appliesToUid(uid);
6042 }
6043
6044 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6045 // sockets, i.e., if it is the owner.
6046 final NetworkAgentInfo vpn = getVpnForUid(uid);
6047 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6048 && uid != vpn.networkCapabilities.getOwnerUid()) {
6049 return false;
6050 }
6051
6052 // The UID's permission must be at least sufficient for the network. Since the restricted
6053 // permission was already checked above, that just leaves background networks.
6054 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6055 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6056 }
6057
6058 // Unrestricted network. Anyone gets to use it.
6059 return true;
6060 }
6061
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006062 /**
6063 * Returns information about the proxy a certain network is using. If given a null network, it
6064 * it will return the proxy for the bound network for the caller app or the default proxy if
6065 * none.
6066 *
6067 * @param network the network we want to get the proxy information for.
6068 * @return Proxy information if a network has a proxy configured, or otherwise null.
6069 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006070 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006071 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006072 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006073 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006074 if (network == null) {
6075 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006076 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006077 true);
6078 if (activeNetwork == null) {
6079 return null;
6080 }
6081 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006082 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006083 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6084 // caller may not have.
6085 return getLinkPropertiesProxyInfo(network);
6086 }
6087 // No proxy info available if the calling UID does not have network access.
6088 return null;
6089 }
6090
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006091
6092 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006093 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6094 if (nai == null) return null;
6095 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006096 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6097 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006098 }
6099 }
6100
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006101 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006102 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006103 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006104 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006105 }
6106
Chalard Jean777e2e52018-06-07 18:02:37 +09006107 @Override
6108 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006109 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006110 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006111 }
6112
Junyu Lai970963e2022-10-25 15:46:47 +08006113 private void handleApplyDefaultProxy(@Nullable ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04006114 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05006115 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07006116 proxy = null;
6117 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006118 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006119 }
6120
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006121 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6122 // when any network changes proxy.
6123 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6124 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006125 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6126 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006127 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6128
Chalard Jean7d97afc2018-06-07 17:41:29 +09006129 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006130 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006131 }
6132 }
6133
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006134 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006135 final private HashMap<Uri, Integer> mUriEventMap;
6136 final private Context mContext;
6137 final private Handler mHandler;
6138
6139 SettingsObserver(Context context, Handler handler) {
6140 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006141 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006142 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006143 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006144 }
6145
Erik Kline05f2b402015-04-30 12:58:40 +09006146 void observe(Uri uri, int what) {
6147 mUriEventMap.put(uri, what);
6148 final ContentResolver resolver = mContext.getContentResolver();
6149 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006150 }
6151
6152 @Override
6153 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006154 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006155 }
6156
6157 @Override
6158 public void onChange(boolean selfChange, Uri uri) {
6159 final Integer what = mUriEventMap.get(uri);
6160 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006161 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006162 } else {
6163 loge("No matching event to send for URI=" + uri);
6164 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006165 }
6166 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006167
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006168 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006169 Log.d(TAG, s);
6170 }
6171
6172 private static void logw(String s) {
6173 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006174 }
6175
Daniel Brightf9e945b2020-06-15 16:10:01 -07006176 private static void logwtf(String s) {
6177 Log.wtf(TAG, s);
6178 }
6179
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006180 private static void logwtf(String s, Throwable t) {
6181 Log.wtf(TAG, s, t);
6182 }
6183
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006184 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006185 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006186 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006187
Hugo Benichi39621362017-02-11 17:04:43 +09006188 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006189 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006190 }
6191
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006192 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006193 * Return the information of all ongoing VPNs.
6194 *
6195 * <p>This method is used to update NetworkStatsService.
6196 *
6197 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006198 */
junyulai2050bed2021-01-23 09:46:34 +08006199 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006200 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006201 if (mLockdownEnabled) {
6202 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006203 }
junyulai2050bed2021-01-23 09:46:34 +08006204 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006205 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006206 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006207 if (info != null) {
6208 infoList.add(info);
6209 }
6210 }
junyulai2050bed2021-01-23 09:46:34 +08006211 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006212 }
6213
6214 /**
6215 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006216 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006217 */
junyulai2050bed2021-01-23 09:46:34 +08006218 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006219 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006220 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6221 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006222 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6223 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6224 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006225 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6226 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006227 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006228 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006229 }
6230 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006231
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006232 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006233
6234 List<String> interfaces = new ArrayList<>();
6235 for (Network network : underlyingNetworks) {
6236 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6237 if (underlyingNai == null) continue;
6238 LinkProperties lp = underlyingNai.linkProperties;
6239 for (String iface : lp.getAllInterfaceNames()) {
6240 if (!TextUtils.isEmpty(iface)) {
6241 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006242 }
6243 }
Benedict Wong34857f82019-06-12 17:46:15 +00006244 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006245
6246 if (interfaces.isEmpty()) return null;
6247
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006248 // Must be non-null or NetworkStatsService will crash.
6249 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6250 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006251 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006252 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006253
junyulai2050bed2021-01-23 09:46:34 +08006254 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6255 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006256 }
6257
James Mattisd31bdfa2020-12-23 16:37:26 -08006258 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006259 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6260 Network[] underlyingNetworks) {
6261 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006262 if (underlyingNetworks == null && defaultNetwork != null) {
6263 // null underlying networks means to track the default.
6264 underlyingNetworks = new Network[] { defaultNetwork };
6265 }
6266 return underlyingNetworks;
6267 }
6268
6269 // Returns true iff |network| is an underlying network of |nai|.
6270 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6271 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6272 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006273 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006274 final Network[] underlying = underlyingNetworksOrDefault(
6275 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006276 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006277 }
6278
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006279 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006280 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006281 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006282 * When underlying networks change, such networks may have to update capabilities to reflect
6283 * things like the metered bit, their transports, and so on. The capabilities are calculated
6284 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006285 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006286 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006287 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006288 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006289 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006290 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006291 }
6292 }
6293 }
6294
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006295 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6296 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6297 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6298 // a VPN is not up.
6299 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6300 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6301 for (UidRange range : blockedUidRanges) {
6302 if (range.contains(uid)) return true;
6303 }
6304 return false;
6305 }
6306
6307 @Override
6308 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006309 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006310 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6311 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6312 }
6313
6314 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6315 if (DBG) {
6316 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6317 + Arrays.toString(ranges));
6318 }
6319 // Cannot use a Set since the list of UID ranges might contain duplicates.
6320 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6321 for (int i = 0; i < ranges.length; i++) {
6322 if (requireVpn) {
6323 newVpnBlockedUidRanges.add(ranges[i]);
6324 } else {
6325 newVpnBlockedUidRanges.remove(ranges[i]);
6326 }
6327 }
6328
6329 try {
6330 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6331 } catch (RemoteException | ServiceSpecificException e) {
6332 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6333 + Arrays.toString(ranges) + "): netd command failed: " + e);
6334 }
6335
Motomu Utsumib08654c2022-05-11 05:56:26 +00006336 if (SdkLevel.isAtLeastT()) {
6337 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6338 }
6339
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006340 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6341 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006342 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6343 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006344 }
6345
6346 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6347 }
6348
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006349 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006350 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006351 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006352 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006353 }
6354
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006355 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6356 return mLockdownEnabled
6357 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6358 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006359 }
6360
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006361 private NetworkAgentInfo getLegacyLockdownNai() {
6362 if (!mLockdownEnabled) {
6363 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006364 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006365 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006366 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6367 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006368
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006369 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006370 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6371 // a local variable. There is no need to make a copy because its contents cannot change.
6372 final Network[] underlying = nai.declaredUnderlyingNetworks;
6373 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006374 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006375 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006376
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006377 // The legacy lockdown VPN always uses the default network.
6378 // If the VPN's underlying network is no longer the current default network, it means that
6379 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006380 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6381 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006382 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006383 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006384 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006385 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006386
6387 return nai;
6388 };
6389
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006390 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6391 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6392 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006393 private DetailedState getLegacyLockdownState(DetailedState origState) {
6394 if (origState != DetailedState.CONNECTED) {
6395 return origState;
6396 }
6397 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6398 ? DetailedState.CONNECTING
6399 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006400 }
6401
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006402 private void filterForLegacyLockdown(NetworkInfo ni) {
6403 if (!mLockdownEnabled || !ni.isConnected()) return;
6404 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6405 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6406 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6407 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6408 // network, this time with a state of CONNECTED.
6409 //
6410 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6411 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6412 // is not too far off the truth, since an always-on VPN, when not connected, is always
6413 // trying to reconnect.
6414 if (getLegacyLockdownNai() == null) {
6415 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6416 }
6417 }
6418
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006419 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006420 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006421 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006422 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006423 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6424 return;
6425 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006426 final long ident = Binder.clearCallingIdentity();
6427 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006428 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006429 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006430 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006431 } finally {
6432 Binder.restoreCallingIdentity(ident);
6433 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006434 }
Wink Savillecb117d32013-08-29 14:57:08 -07006435
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006436 @Override
6437 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006438 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006439 final long ident = Binder.clearCallingIdentity();
6440 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006441 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006442 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006443 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6444 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006445 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006446 } finally {
6447 Binder.restoreCallingIdentity(ident);
6448 }
6449 }
6450
James Mattis02220e22021-03-13 19:27:21 -08006451 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006452 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6453 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6454 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006455 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006456 }
6457
James Mattis02220e22021-03-13 19:27:21 -08006458 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006459 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006460 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006461 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6462 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006463 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006464 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6465 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6466 }
junyulaid91e7052020-08-28 13:44:33 +08006467 }
6468
James Mattis02220e22021-03-13 19:27:21 -08006469 private void onPackageChanged(@NonNull final String packageName) {
6470 // This is necessary in case a package is added or removed, but also when it's replaced to
6471 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6472 // as one in the preferences, then it should follow the same routing as that other package,
6473 // which means updating the rules is never to be needed in this case (whether it joins or
6474 // leaves a UID with a preference).
6475 if (isMappedInOemNetworkPreference(packageName)) {
6476 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6477 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006478
6479 // Invalidates cache entry when the package is updated.
6480 synchronized (mSelfCertifiedCapabilityCache) {
6481 mSelfCertifiedCapabilityCache.remove(packageName);
6482 }
James Mattis02220e22021-03-13 19:27:21 -08006483 }
6484
6485 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006486 @Override
6487 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006488 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006489 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006490 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006491
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006492 // User should be filled for below intents, check the existence.
6493 if (user == null) {
6494 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6495 return;
6496 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006497
Lorenzo Colitticd675292021-02-04 17:32:07 +09006498 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006499 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006500 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006501 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006502 } else {
junyulaid91e7052020-08-28 13:44:33 +08006503 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006504 }
6505 }
6506 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006507
James Mattis02220e22021-03-13 19:27:21 -08006508 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6509 @Override
6510 public void onReceive(Context context, Intent intent) {
6511 ensureRunningOnConnectivityServiceThread();
6512 switch (intent.getAction()) {
6513 case Intent.ACTION_PACKAGE_ADDED:
6514 case Intent.ACTION_PACKAGE_REMOVED:
6515 case Intent.ACTION_PACKAGE_REPLACED:
6516 onPackageChanged(intent.getData().getSchemeSpecificPart());
6517 break;
6518 default:
6519 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6520 }
6521 }
6522 };
6523
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006524 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006525 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006526
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006527 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006528 public final String name;
6529 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006530 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006531 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006532
lifraf3a3492021-03-10 13:58:14 +08006533 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6534 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006535 this.name = name;
6536 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006537 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006538 mDeathRecipient = deathRecipient;
6539
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006540 if (mDeathRecipient == null) {
6541 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006542 }
6543 }
6544
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006545 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006546 try {
6547 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6548 } catch (RemoteException e) {
6549 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006550 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006551 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006552 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006553
James Mattis4fce5d12020-11-12 15:53:42 -08006554 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6555 for (int i = 0; i < requests.size(); i++) {
6556 ensureNetworkRequestHasType(requests.get(i));
6557 }
6558 }
6559
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006560 private void ensureNetworkRequestHasType(NetworkRequest request) {
6561 if (request.type == NetworkRequest.Type.NONE) {
6562 throw new IllegalArgumentException(
6563 "All NetworkRequests in ConnectivityService must have a type");
6564 }
6565 }
6566
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006567 /**
6568 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006569 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006570 */
James Mattis258ea3c2020-11-15 15:04:40 -08006571 @VisibleForTesting
6572 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006573 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6574 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006575 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006576
James Mattisa076c532020-12-02 14:12:41 -08006577 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6578 void setSatisfier(
6579 @Nullable final NetworkAgentInfo satisfier,
6580 @Nullable final NetworkRequest activeRequest) {
6581 mSatisfier = satisfier;
6582 mActiveRequest = activeRequest;
6583 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006584
James Mattisd31bdfa2020-12-23 16:37:26 -08006585 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006586 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006587 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006588 private NetworkAgentInfo mSatisfier;
6589 NetworkAgentInfo getSatisfier() {
6590 return mSatisfier;
6591 }
6592
6593 // The request in mRequests assigned to a network agent. This is null if none of the
6594 // requests in mRequests can be satisfied. This member has the constraint of only being
6595 // accessible on the handler thread.
6596 @Nullable
6597 private NetworkRequest mActiveRequest;
6598 NetworkRequest getActiveRequest() {
6599 return mActiveRequest;
6600 }
6601
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006602 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006603 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006604 @Nullable
6605 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006606
6607 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006608 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006609 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006610 final int mPid;
6611 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006612 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006613 @Nullable
6614 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006615
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006616 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006617 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006618
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006619 // Effective UID of this request. This is different from mUid when a privileged process
6620 // files a request on behalf of another UID. This UID is used to determine blocked status,
6621 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6622 // maximum limit of registered callbacks per UID.
6623 final int mAsUid;
6624
paulhu48291862021-07-14 14:53:57 +08006625 // Preference order of this request.
6626 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006627
James Mattis3ce3d3c2021-02-09 18:18:28 -08006628 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6629 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6630 // maintained for keying off of. This is only a concern when the original nri
6631 // mNetworkRequests changes which happens currently for apps that register callbacks to
6632 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6633 // that match the per-app default nri that currently tracks the calling app's uid so that
6634 // callbacks are fired at the appropriate time. When the callbacks fire,
6635 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6636 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6637 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6638 @NonNull
6639 private final NetworkRequest mNetworkRequestForCallback;
6640 NetworkRequest getNetworkRequestForCallback() {
6641 return mNetworkRequestForCallback;
6642 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006643
James Mattisd31bdfa2020-12-23 16:37:26 -08006644 /**
6645 * Get the list of UIDs this nri applies to.
6646 */
6647 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006648 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006649 // networkCapabilities.getUids() returns a defensive copy.
6650 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006651 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6652 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006653 }
6654
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006655 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6656 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006657 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006658 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006659 }
6660
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006661 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006662 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006663 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006664 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006665 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006666 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006667 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006668 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006669 mBinder = null;
6670 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006671 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006672 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006673 mPerUidCounter = getRequestCounter(this);
6674 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006675 /**
6676 * Location sensitive data not included in pending intent. Only included in
6677 * {@link NetworkCallback}.
6678 */
6679 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006680 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006681 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006682 }
6683
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006684 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006685 @Nullable final IBinder binder,
6686 @NetworkCallback.Flag int callbackFlags,
6687 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006688 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6689 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006690 }
6691
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006692 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006693 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006694 @Nullable final IBinder binder,
6695 @NetworkCallback.Flag int callbackFlags,
6696 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006697 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006698 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006699 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006700 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006701 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006702 mBinder = binder;
6703 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006704 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006705 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006706 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006707 mPerUidCounter = getRequestCounter(this);
6708 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006709 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006710 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006711 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006712 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006713 }
6714
James Mattis3ce3d3c2021-02-09 18:18:28 -08006715 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6716 @NonNull final List<NetworkRequest> r) {
6717 super();
6718 ensureAllNetworkRequestsHaveType(r);
6719 mRequests = initializeRequests(r);
6720 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006721 final NetworkAgentInfo satisfier = nri.getSatisfier();
6722 if (null != satisfier) {
6723 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6724 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09006725 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006726 // As this code creates a new NRI with a new set of requests, figure out which of
6727 // the list of requests should be the active request. It is always the first
6728 // request of the list that can be satisfied by the satisfier since the order of
6729 // requests is a priority order.
6730 // Note even in the presence of a satisfier there may not be an active request,
6731 // when the satisfier is the no-service network.
6732 NetworkRequest activeRequest = null;
6733 for (final NetworkRequest candidate : r) {
6734 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6735 activeRequest = candidate;
6736 break;
6737 }
6738 }
6739 setSatisfier(satisfier, activeRequest);
6740 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006741 mMessenger = nri.mMessenger;
6742 mBinder = nri.mBinder;
6743 mPid = nri.mPid;
6744 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006745 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006746 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006747 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006748 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006749 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006750 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006751 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006752 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006753 }
6754
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006755 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006756 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006757 }
6758
paulhue9913722021-05-26 15:19:20 +08006759 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006760 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006761 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006762 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006763 }
6764
James Mattis2516da32021-01-31 17:06:19 -08006765 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6766 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6767 // false.
6768 boolean isBeingSatisfied() {
6769 return (null != mSatisfier && null != mActiveRequest);
6770 }
6771
James Mattis3d229892020-11-16 16:46:28 -08006772 boolean isMultilayerRequest() {
6773 return mRequests.size() > 1;
6774 }
6775
James Mattis45d81842021-01-10 14:24:24 -08006776 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6777 // Creating a defensive copy to prevent the sender from modifying the list being
6778 // reflected in the return value of this method.
6779 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006780 return Collections.unmodifiableList(tempRequests);
6781 }
6782
James Mattisb1392002021-03-31 13:57:52 -07006783 void linkDeathRecipient() {
6784 if (null != mBinder) {
6785 try {
6786 mBinder.linkToDeath(this, 0);
6787 } catch (RemoteException e) {
6788 binderDied();
6789 }
6790 }
6791 }
6792
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006793 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006794 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006795 try {
6796 mBinder.unlinkToDeath(this, 0);
6797 } catch (NoSuchElementException e) {
6798 // Temporary workaround for b/194394697 pending analysis of additional logs
6799 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6800 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006801 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006802 }
6803
paulhu48291862021-07-14 14:53:57 +08006804 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6805 // Compare two preference orders.
6806 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006807 }
6808
paulhu48291862021-07-14 14:53:57 +08006809 int getPreferenceOrderForNetd() {
6810 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6811 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6812 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006813 }
paulhu48291862021-07-14 14:53:57 +08006814 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006815 }
6816
James Mattis4fce5d12020-11-12 15:53:42 -08006817 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006818 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09006819 // As an immutable collection, mRequests cannot change by the time the
6820 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6821 // is acceptable. Use handleReleaseNetworkRequest and not directly
6822 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6823 // the app already unregistered the request.
6824 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6825 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006826 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006827
James Mattis4fce5d12020-11-12 15:53:42 -08006828 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006829 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006830 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6831 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006832 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006833 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006834 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006835 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006836 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006837 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006838 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006839 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006840 }
6841
Junyu Lai00d92df2022-07-05 11:01:52 +08006842 // Keep backward compatibility since the ServiceSpecificException is used by
6843 // the API surface, see {@link ConnectivityManager#convertServiceException}.
6844 public static class RequestInfoPerUidCounter extends PerUidCounter {
6845 RequestInfoPerUidCounter(int maxCountPerUid) {
6846 super(maxCountPerUid);
6847 }
6848
6849 @Override
6850 public synchronized void incrementCountOrThrow(int uid) {
6851 try {
6852 super.incrementCountOrThrow(uid);
6853 } catch (IllegalStateException e) {
6854 throw new ServiceSpecificException(
6855 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
6856 "Uid " + uid + " exceeded its allotted requests limit");
6857 }
6858 }
6859
6860 @Override
6861 public synchronized void decrementCountOrThrow(int uid) {
6862 throw new UnsupportedOperationException("Use decrementCount instead.");
6863 }
6864
6865 public synchronized void decrementCount(int uid) {
6866 try {
6867 super.decrementCountOrThrow(uid);
6868 } catch (IllegalStateException e) {
6869 logwtf("Exception when decrement per uid request count: ", e);
6870 }
6871 }
6872 }
6873
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006874 // This checks that the passed capabilities either do not request a
6875 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006876 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006877 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006878 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006879 throw new SecurityException("Insufficient permissions to request a specific SSID");
6880 }
paulhu1a407652019-03-22 16:35:06 +08006881
6882 if (nc.hasSignalStrength()
6883 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6884 throw new SecurityException(
6885 "Insufficient permissions to request a specific signal strength");
6886 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006887 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006888
junyulai2217bec2021-04-14 23:33:31 +08006889 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006890 enforceNetworkFactoryPermission();
6891 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006892 }
6893
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006894 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006895 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006896 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006897 // mNetworkRequests may contain the same value multiple times in case of
6898 // multilayer requests. It won't matter in this case because the thresholds
6899 // will then be the same and be deduplicated as they enter the `thresholds` set.
6900 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006901 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6902 for (final NetworkRequest req : nri.mRequests) {
6903 if (req.networkCapabilities.hasSignalStrength()
6904 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6905 thresholds.add(req.networkCapabilities.getSignalStrength());
6906 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006907 }
6908 }
6909 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006910 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006911 }
6912
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006913 private void updateSignalStrengthThresholds(
6914 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006915 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006916
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006917 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006918 String detail;
6919 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6920 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6921 } else {
6922 detail = reason;
6923 }
6924 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006925 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006926 }
6927
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006928 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006929 }
6930
Chalard Jeandd421992021-12-16 23:16:02 +09006931 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006932 if (nc == null) {
6933 return;
6934 }
6935 NetworkSpecifier ns = nc.getNetworkSpecifier();
6936 if (ns == null) {
6937 return;
6938 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006939 if (ns instanceof MatchAllNetworkSpecifier) {
6940 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6941 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006942 }
6943
Chalard Jeandd421992021-12-16 23:16:02 +09006944 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006945 ensureValidNetworkSpecifier(nc);
6946 if (nc.isPrivateDnsBroken()) {
6947 throw new IllegalArgumentException("Can't request broken private DNS");
6948 }
Chalard Jeande665262022-02-25 16:12:12 +09006949 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09006950 throw new IllegalArgumentException("Can't request access UIDs");
6951 }
lucasline117e2e2019-10-22 18:27:33 +08006952 }
6953
Chalard Jeandd421992021-12-16 23:16:02 +09006954 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6955 ensureListenableCapabilities(nc);
6956 final String badCapability = nc.describeFirstNonRequestableCapability();
6957 if (badCapability != null) {
6958 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6959 }
6960 }
6961
Chiachang Wang3bc52762021-11-25 14:17:57 +08006962 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6963 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006964 private boolean isTargetSdkAtleast(int version, int callingUid,
6965 @NonNull String callingPackageName) {
6966 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006967 final PackageManager pm =
6968 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006969 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006970 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006971 if (callingVersion < version) return false;
6972 } catch (PackageManager.NameNotFoundException e) { }
6973 return true;
6974 }
6975
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006976 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006977 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006978 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006979 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006980 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006981 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006982 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6983 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006984 throw new SecurityException("Insufficient permissions to specify legacy type");
6985 }
markchienfac84a22020-03-18 21:16:15 +08006986 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006987 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006988 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006989 // Privileged callers can track the default network of another UID by passing in a UID.
6990 if (asUid != Process.INVALID_UID) {
6991 enforceSettingsPermission();
6992 } else {
6993 asUid = callingUid;
6994 }
junyulaiad010792021-01-11 16:53:38 +08006995 final NetworkRequest.Type reqType;
6996 try {
6997 reqType = NetworkRequest.Type.values()[reqTypeInt];
6998 } catch (ArrayIndexOutOfBoundsException e) {
6999 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7000 }
7001 switch (reqType) {
7002 case TRACK_DEFAULT:
7003 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007004 // is unused and will be replaced by ones appropriate for the UID (usually, the
7005 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007006 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007007 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007008 enforceAccessPermission();
7009 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007010 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007011 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007012 networkCapabilities = new NetworkCapabilities(defaultNc);
7013 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007014 case BACKGROUND_REQUEST:
7015 enforceNetworkStackOrSettingsPermission();
7016 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007017 case REQUEST:
7018 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7019 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007020 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007021 // TODO: this is incorrect. We mark the request as metered or not depending on
7022 // the state of the app when the request is filed, but we never change the
7023 // request if the app changes network state. http://b/29964605
7024 enforceMeteredApnPolicy(networkCapabilities);
7025 break;
junyulai1b1c8742021-03-12 20:05:08 +08007026 case LISTEN_FOR_BEST:
7027 enforceAccessPermission();
7028 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7029 break;
junyulaiad010792021-01-11 16:53:38 +08007030 default:
7031 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007032 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007033 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007034 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007035 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007036
junyulai1b1c8742021-03-12 20:05:08 +08007037 // Enforce FOREGROUND if the caller does not have permission to use background network.
7038 if (reqType == LISTEN_FOR_BEST) {
7039 restrictBackgroundRequestForCaller(networkCapabilities);
7040 }
7041
7042 // Set the UID range for this request to the single UID of the requester, unless the
7043 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007044 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7045 // are no visible methods to set the UIDs, an app could use reflection to try and get
7046 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007047 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007048 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7049 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007050
Etan Cohen85000162017-02-05 10:42:27 -08007051 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007052 throw new IllegalArgumentException("Bad timeout specified");
7053 }
Etan Cohen9786d922015-11-18 10:56:15 -08007054
James Mattis3ce3d3c2021-02-09 18:18:28 -08007055 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007056 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007057 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007058 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007059 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007060 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007061
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007062 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7063 // copied from the default request above. (This is necessary to ensure, for example, that
7064 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7065 // changes don't alter request matching.
7066 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7067 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007068 throw new IllegalStateException(
7069 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007070 + networkCapabilities + " vs. " + defaultNc);
7071 }
7072
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007073 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007074 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007075 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007076 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007077 }
7078 return networkRequest;
7079 }
7080
James Mattis3ce3d3c2021-02-09 18:18:28 -08007081 /**
7082 * Return the nri to be used when registering a network request. Specifically, this is used with
7083 * requests registered to track the default request. If there is currently a per-app default
7084 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7085 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007086 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7087 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007088 * @param nr the network request for the nri.
7089 * @param msgr the messenger for the nri.
7090 * @param binder the binder for the nri.
7091 * @param callingAttributionTag the calling attribution tag for the nri.
7092 * @return the nri to register.
7093 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007094 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007095 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007096 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007097 @Nullable String callingAttributionTag) {
7098 final List<NetworkRequest> requests;
7099 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7100 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007101 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007102 } else {
7103 requests = Collections.singletonList(nr);
7104 }
Roshan Pius951c0032020-12-22 15:10:42 -08007105 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007106 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007107 }
7108
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007109 private boolean shouldCheckCapabilitiesDeclaration(
7110 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7111 @NonNull final String callingPackageName) {
7112 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7113 // Only run the check if the change is enabled.
7114 if (!mDeps.isChangeEnabled(
7115 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7116 callingPackageName, user)) {
7117 return false;
7118 }
7119
7120 return networkCapabilities.hasCapability(
7121 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7122 || networkCapabilities.hasCapability(
7123 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7124 }
7125
7126 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
7127 @NonNull final NetworkCapabilities networkCapabilities) {
7128 // This check is added to fix the linter error for "current min is 30", which is not going
7129 // to happen because Connectivity service always run in S+.
7130 if (!SdkLevel.isAtLeastS()) {
7131 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7132 return;
7133 }
7134 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007135 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007136 try {
7137 synchronized (mSelfCertifiedCapabilityCache) {
7138 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7139 callerPackageName);
7140 if (applicationNetworkCapabilities == null) {
7141 final PackageManager packageManager = mContext.getPackageManager();
7142 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7143 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7144 callerPackageName
7145 );
7146 final XmlResourceParser parser = packageManager
7147 .getResourcesForApplication(callerPackageName)
7148 .getXml(networkSliceProperty.getResourceId());
7149 applicationNetworkCapabilities =
7150 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7151 mSelfCertifiedCapabilityCache.put(callerPackageName,
7152 applicationNetworkCapabilities);
7153 }
7154
7155 }
7156 } catch (PackageManager.NameNotFoundException ne) {
7157 throw new SecurityException(
7158 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7159 + " property");
7160 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7161 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007162 } finally {
7163 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007164 }
7165
7166 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7167 networkCapabilities);
7168 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007169 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007170 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007171 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7172 callingPackageName)) {
7173 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7174 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007175 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007176 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7177 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7178 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7179 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007180 }
junyulai96bd9fe2022-03-08 17:36:42 +08007181 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007182 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007183 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007184 }
7185 }
7186
fenglu3f357402015-03-20 11:29:56 -07007187 @Override
fenglub00f4882015-04-21 17:12:05 -07007188 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007189 enforceAccessPermission();
7190 NetworkAgentInfo nai = null;
7191 if (network == null) {
7192 return false;
7193 }
7194 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007195 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007196 }
7197 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007198 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007199 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007200 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007201 Integer uidReqs = mBandwidthRequests.get(uid);
7202 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007203 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007204 }
7205 mBandwidthRequests.put(uid, ++uidReqs);
7206 }
fenglu3f357402015-03-20 11:29:56 -07007207 return true;
7208 }
7209 return false;
7210 }
7211
Felipe Leme0a5ae422016-06-20 16:36:29 -07007212 private boolean isSystem(int uid) {
7213 return uid < Process.FIRST_APPLICATION_UID;
7214 }
fenglu3f357402015-03-20 11:29:56 -07007215
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007216 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007217 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007218 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007219 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007220 return;
7221 }
Hugo Benichi39621362017-02-11 17:04:43 +09007222 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7223 // Policy already enforced.
7224 return;
7225 }
paulhuaf50d7d2020-12-24 19:47:34 +08007226 final long ident = Binder.clearCallingIdentity();
7227 try {
7228 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7229 // If UID is restricted, don't allow them to bring up metered APNs.
7230 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7231 }
7232 } finally {
7233 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007234 }
7235 }
7236
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007237 @Override
7238 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007239 PendingIntent operation, @NonNull String callingPackageName,
7240 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007241 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007242 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007243 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007244 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007245 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007246 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007247 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007248 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007249 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007250 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7251 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007252
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007253 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007254 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007255 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7256 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007257 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007258 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7259 nri));
7260 return networkRequest;
7261 }
7262
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007263 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7264 mHandler.sendMessageDelayed(
7265 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007266 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007267 }
7268
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007269 @Override
7270 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007271 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007272 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007273 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007274 }
7275
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007276 // In order to implement the compatibility measure for pre-M apps that call
7277 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7278 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7279 // This ensures it has permission to do so.
7280 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7281 if (nc == null) {
7282 return false;
7283 }
7284 int[] transportTypes = nc.getTransportTypes();
7285 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7286 return false;
7287 }
7288 try {
7289 mContext.enforceCallingOrSelfPermission(
7290 android.Manifest.permission.ACCESS_WIFI_STATE,
7291 "ConnectivityService");
7292 } catch (SecurityException e) {
7293 return false;
7294 }
7295 return true;
7296 }
7297
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007298 @Override
7299 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007300 Messenger messenger, IBinder binder,
7301 @NetworkCallback.Flag int callbackFlags,
7302 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007303 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007304 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7305 enforceAccessPermission();
7306 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007307
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007308 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007309 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007310 Binder.getCallingPid(), callingUid, callingPackageName);
7311 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007312 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7313 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7314 // onLost and onAvailable callbacks when networks move in and out of the background.
7315 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7316 // can't request networks.
7317 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007318 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007319
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007320 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007321 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007322 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007323 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007324 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007325 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007326
7327 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7328 return networkRequest;
7329 }
7330
7331 @Override
7332 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007333 PendingIntent operation, @NonNull String callingPackageName,
7334 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007335 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007336 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007337 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7338 enforceAccessPermission();
7339 }
Chalard Jeandd421992021-12-16 23:16:02 +09007340 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007341 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007342 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007343 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007344 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007345
7346 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007347 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007348 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7349 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007350 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007351
WeiZhang1cc3f172021-06-03 19:02:04 -05007352 mHandler.sendMessage(mHandler.obtainMessage(
7353 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007354 }
7355
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007356 /** Returns the next Network provider ID. */
7357 public final int nextNetworkProviderId() {
7358 return mNextNetworkProviderId.getAndIncrement();
7359 }
7360
Erik Kline0c04b742016-07-07 16:50:58 +09007361 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007362 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007363 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007364 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007365 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007366 }
7367
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007368 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7369 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007370 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7371 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7372 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007373 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007374 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007375 return;
7376 }
7377
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007378 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7379 mNetworkProviderInfos.put(npi.messenger, npi);
7380 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007381 }
7382
7383 @Override
7384 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007385 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007386 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007387 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007388 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007389 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7390 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007391 }
7392
7393 @Override
7394 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007395 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007396 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007397 }
7398
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007399 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007400 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007401 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7402 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007403 Objects.requireNonNull(score);
7404 Objects.requireNonNull(caps);
7405 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007406 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007407 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007408 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7409 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007410 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7411 }
7412
Chalard Jeanbb902a52021-08-18 01:35:19 +09007413 private void updateOfferScore(final NetworkOffer offer) {
7414 final boolean yieldToBadWiFi =
7415 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7416 final NetworkOffer newOffer = new NetworkOffer(
7417 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7418 offer.caps, offer.callback, offer.providerId);
7419 if (offer.equals(newOffer)) return;
7420 handleRegisterNetworkOffer(newOffer);
7421 }
7422
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007423 @Override
7424 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007425 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007426 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7427 }
7428
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007429 private void handleUnregisterNetworkProvider(Messenger messenger) {
7430 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7431 if (npi == null) {
7432 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007433 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007434 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007435 // Unregister all the offers from this provider
7436 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7437 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007438 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007439 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7440 toRemove.add(noi);
7441 }
7442 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007443 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007444 handleUnregisterNetworkOffer(noi);
7445 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007446 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007447 }
7448
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007449 @Override
James Mattisf7027322020-12-13 16:28:14 -08007450 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007451 if (request.hasTransport(TRANSPORT_TEST)) {
7452 enforceNetworkFactoryOrTestNetworksPermission();
7453 } else {
7454 enforceNetworkFactoryPermission();
7455 }
James Mattisf7027322020-12-13 16:28:14 -08007456 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7457 if (nri != null) {
7458 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7459 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7460 mHandler.post(() -> handleReleaseNetworkRequest(
7461 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7462 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007463 }
7464
Paul Jensen1f567382015-02-13 14:18:39 -05007465 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7466 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007467 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007468 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007469 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007470 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007471 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007472
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007473 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007474 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007475 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007476
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007477 // UID ranges for users that are currently blocked by VPNs.
7478 // This array is accessed and iterated on multiple threads without holding locks, so its
7479 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7480 // (on the handler thread).
7481 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7482
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007483 // Must only be accessed on the handler thread
7484 @NonNull
7485 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7486
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007487 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007488 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007489
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007490 // Current OEM network preferences. This object must only be written to on the handler thread.
7491 // Since it is immutable and always non-null, other threads may read it if they only care
7492 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007493 @NonNull
7494 private OemNetworkPreferences mOemNetworkPreferences =
7495 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007496 // Current per-profile network preferences. This object follows the same threading rules as
7497 // the OEM network preferences above.
7498 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007499 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7500 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007501
lucaslin3ba7cc22022-12-19 02:35:33 +00007502 // Current VPN network preferences. This object follows the same threading rules as the OEM
7503 // network preferences above.
7504 @NonNull
7505 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7506 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7507
paulhu51f77dc2021-06-07 02:34:20 +00007508 // A set of UIDs that should use mobile data preferentially if available. This object follows
7509 // the same threading rules as the OEM network preferences above.
7510 @NonNull
7511 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7512
James Mattiscb1e0362021-04-06 17:07:42 -07007513 // OemNetworkPreferences activity String log entries.
7514 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7515 @NonNull
7516 private final LocalLog mOemNetworkPreferencesLogs =
7517 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7518
James Mattis02220e22021-03-13 19:27:21 -08007519 /**
7520 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7521 * @param packageName the package name to check existence of a mapping for.
7522 * @return true if a mapping exists, false otherwise
7523 */
7524 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7525 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7526 }
7527
James Mattise3ef1912020-12-20 11:09:58 -08007528 // The always-on request for an Internet-capable network that apps without a specific default
7529 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007530 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007531 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007532 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007533 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007534 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007535 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007536 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007537
James Mattisd31bdfa2020-12-23 16:37:26 -08007538 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7539 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7540 }
7541
7542 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007543 * Return the default network request currently tracking the given uid.
7544 * @param uid the uid to check.
7545 * @return the NetworkRequestInfo tracking the given uid.
7546 */
7547 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007548 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007549 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007550 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007551 // Checking the first request is sufficient as only multilayer requests will have more
7552 // than one request and for multilayer, all requests will track the same uids.
7553 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007554 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007555 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007556 highestPriorityNri = nri;
7557 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007558 }
7559 }
paulhuaa0743d2021-05-26 21:56:03 +08007560 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007561 }
7562
7563 /**
7564 * Get a copy of the network requests of the default request that is currently tracking the
7565 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007566 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7567 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007568 * @param requestorUid the uid to check the default for.
7569 * @param requestorPackageName the requestor's package name.
7570 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7571 */
7572 @NonNull
7573 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007574 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007575 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007576 getDefaultRequestTrackingUid(asUid).mRequests,
7577 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007578 }
7579
7580 /**
7581 * Copy the given nri's NetworkRequest collection.
7582 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007583 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7584 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007585 * @param requestorUid the uid to set on the copied collection.
7586 * @param requestorPackageName the package name to set on the copied collection.
7587 * @return the copied NetworkRequest collection.
7588 */
7589 @NonNull
7590 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007591 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7592 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007593 final List<NetworkRequest> requests = new ArrayList<>();
7594 for (final NetworkRequest nr : requestsToCopy) {
7595 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007596 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007597 nr.legacyType, nextNetworkRequestId(), nr.type));
7598 }
7599 return requests;
7600 }
7601
7602 @NonNull
7603 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007604 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7605 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007606 // These capabilities are for a TRACK_DEFAULT callback, so:
7607 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7608 // mDefaultRequest and a per-UID default request.
7609 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007610 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007611 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007612 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7613 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007614 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007615 restrictRequestUidsForCallerAndSetRequestorInfo(
7616 netCap, requestorUid, requestorPackageName);
7617 return netCap;
7618 }
7619
7620 /**
7621 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7622 * @param nr the network request to check for equality against.
7623 * @return the nri if one exists, null otherwise.
7624 */
7625 @Nullable
7626 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7627 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7628 if (nri.getNetworkRequestForCallback().equals(nr)) {
7629 return nri;
7630 }
7631 }
7632 return null;
7633 }
7634
7635 /**
7636 * Check if an nri is currently being managed by per-app default networking.
7637 * @param nri the nri to check.
7638 * @return true if this nri is currently being managed by per-app default networking.
7639 */
7640 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7641 // nri.mRequests.get(0) is only different from the original request filed in
7642 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7643 // functionality therefore if these two don't match, it means this particular nri is
7644 // currently being managed by a per-app default.
7645 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7646 }
7647
7648 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007649 * Determine if an nri is a managed default request that disallows default networking.
7650 * @param nri the request to evaluate
7651 * @return true if device-default networking is disallowed
7652 */
7653 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7654 // Check if this nri is a managed default that supports the default network at its
7655 // lowest priority request.
7656 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7657 final NetworkCapabilities lowestPriorityNetCap =
7658 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7659 return isPerAppDefaultRequest(nri)
7660 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7661 lowestPriorityNetCap));
7662 }
7663
Erik Kline05f2b402015-04-30 12:58:40 +09007664 // Request used to optionally keep mobile data active even when higher
7665 // priority networks like Wi-Fi are active.
7666 private final NetworkRequest mDefaultMobileDataRequest;
7667
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007668 // Request used to optionally keep wifi data active even when higher
7669 // priority networks like ethernet are active.
7670 private final NetworkRequest mDefaultWifiRequest;
7671
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007672 // Request used to optionally keep vehicle internal network always active
7673 private final NetworkRequest mDefaultVehicleRequest;
7674
James Mattisd31bdfa2020-12-23 16:37:26 -08007675 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7676 // network with no service. This NAI should never be matched against, nor should any public API
7677 // ever return the associated network. For this reason, this NAI is not in the list of available
7678 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7679 // default requests that don't support using the device default network which will ultimately
7680 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7681 @VisibleForTesting
7682 final NetworkAgentInfo mNoServiceNetwork;
7683
Chalard Jean5b409c72021-02-04 13:12:59 +09007684 // The NetworkAgentInfo currently satisfying the default request, if any.
7685 private NetworkAgentInfo getDefaultNetwork() {
7686 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007687 }
7688
James Mattis2516da32021-01-31 17:06:19 -08007689 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007690 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007691 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7692 // Currently, all network requests will have the same uids therefore checking the first
7693 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007694 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007695 if (null == uids) {
7696 continue;
7697 }
7698 for (final UidRange range : uids) {
7699 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007700 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007701 highestPriorityNri = nri;
7702 }
James Mattis2516da32021-01-31 17:06:19 -08007703 }
7704 }
7705 }
paulhuaa0743d2021-05-26 21:56:03 +08007706 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007707 }
7708
Varun Ananddf569952019-02-06 10:13:38 -08007709 @Nullable
7710 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7711 return nai != null ? nai.network : null;
7712 }
7713
7714 private void ensureRunningOnConnectivityServiceThread() {
7715 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7716 throw new IllegalStateException(
7717 "Not running on ConnectivityService thread: "
7718 + Thread.currentThread().getName());
7719 }
7720 }
7721
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007722 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007723 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7724 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007725 }
7726
Chalard Jean29d06db2018-05-02 21:14:54 +09007727 /**
7728 * Register a new agent with ConnectivityService to handle a network.
7729 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007730 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007731 * @param networkInfo the initial info associated with this network. It can be updated later :
7732 * see {@link #updateNetworkInfo}.
7733 * @param linkProperties the initial link properties of this network. They can be updated
7734 * later : see {@link #updateLinkProperties}.
7735 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007736 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007737 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007738 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007739 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007740 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007741 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007742 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007743 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007744 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7745 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007746 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7747 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7748 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007749 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007750 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007751 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08007752 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007753 } else {
7754 enforceNetworkFactoryPermission();
7755 }
7756
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007757 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007758 final long token = Binder.clearCallingIdentity();
7759 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007760 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007761 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007762 } finally {
7763 Binder.restoreCallingIdentity(token);
7764 }
7765 }
7766
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007767 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007768 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007769 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7770 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007771
Chalard Jeandbc46952022-02-02 00:14:18 +09007772 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
7773 // and mutate them at any time.
7774 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
7775 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
7776 final LinkProperties lpCopy = new LinkProperties(linkProperties);
7777
Chalard Jean366c5252022-01-25 18:27:53 +09007778 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09007779 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09007780 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7781 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007782 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09007783 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007784 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007785 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7786 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007787
Chalard Jeandbc46952022-02-02 00:14:18 +09007788 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09007789 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007790 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007791 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007792 mDeps.getNetworkStack().makeNetworkMonitor(
7793 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007794 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7795 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007796 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007797 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007798 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007799 }
7800
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007801 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007802 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007803 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09007804 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007805 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09007806 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
7807 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
7808 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09007809
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007810 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007811
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007812 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007813 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007814 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007815 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007816
7817 try {
7818 networkMonitor.start();
7819 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007820 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007821 }
Chalard Jean366c5252022-01-25 18:27:53 +09007822
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007823 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007824 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007825 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007826 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007827 }
7828
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007829 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7830 @NonNull public final NetworkOffer offer;
7831
7832 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7833 this.offer = offer;
7834 }
7835
7836 @Override
7837 public void binderDied() {
7838 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7839 }
7840 }
7841
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007842 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7843 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7844 if (npi.providerId == providerId) return true;
7845 }
7846 return false;
7847 }
7848
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007849 /**
7850 * Register or update a network offer.
7851 * @param newOffer The new offer. If the callback member is the same as an existing
7852 * offer, it is an update of that offer.
7853 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007854 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007855 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7856 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007857 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007858 // This may actually happen if a provider updates its score or registers and then
7859 // immediately unregisters. The offer would still be in the handler queue, but the
7860 // provider would have been removed.
7861 if (DBG) log("Received offer from an unregistered provider");
7862 return;
7863 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007864 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7865 if (null != existingOffer) {
7866 handleUnregisterNetworkOffer(existingOffer);
7867 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007868 if (DBG) {
7869 // handleUnregisterNetworkOffer has already logged the old offer
7870 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7871 }
7872 } else {
7873 if (DBG) {
7874 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7875 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007876 }
7877 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7878 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007879 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007880 } catch (RemoteException e) {
7881 noi.binderDied();
7882 return;
7883 }
7884 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007885 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007886 }
7887
7888 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7889 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007890 if (DBG) {
7891 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7892 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007893
7894 // If the provider removes the offer and dies immediately afterwards this
7895 // function may be called twice in a row, but the array will no longer contain
7896 // the offer.
7897 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007898 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007899 }
7900
7901 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7902 @NonNull final INetworkOfferCallback callback) {
7903 ensureRunningOnConnectivityServiceThread();
7904 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007905 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007906 }
7907 return null;
7908 }
7909
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007910 /**
7911 * Called when receiving LinkProperties directly from a NetworkAgent.
7912 * Stores into |nai| any data coming from the agent that might also be written to the network's
7913 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7914 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007915 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007916 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007917 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7918 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007919 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007920 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007921 }
7922
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007923 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08007924 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007925 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007926
Lorenzo Colittid523d142020-04-01 20:16:30 +09007927 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7928 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7929 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007930 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007931
Suprabh Shukla1e312032023-01-24 03:36:37 -08007932 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007933
7934 // update filtering rules, need to happen after the interface update so netd knows about the
7935 // new interface (the interface name -> index map becomes initialized)
7936 updateVpnFiltering(newLp, oldLp, networkAgent);
7937
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007938 updateMtu(newLp, oldLp);
7939 // TODO - figure out what to do for clat
7940// for (LinkProperties lp : newLp.getStackedLinks()) {
7941// updateMtu(lp, null);
7942// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007943 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007944 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7945 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007946
Erik Klineb9888902016-04-05 13:30:49 +09007947 updateRoutes(newLp, oldLp, netId);
7948 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007949 // Make sure LinkProperties represents the latest private DNS status.
7950 // This does not need to be done before updateDnses because the
7951 // LinkProperties are not the source of the private DNS configuration.
7952 // updateDnses will fetch the private DNS configuration from DnsManager.
7953 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007954
Chalard Jean5b409c72021-02-04 13:12:59 +09007955 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007956 handleApplyDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09007957 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007958 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007959 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007960
7961 updateWakeOnLan(newLp);
7962
Hai Shalome58bdc62021-01-11 18:45:34 -08007963 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7964 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7965 // does, it needs to be merged here.
7966 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7967 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007968
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007969 // TODO - move this check to cover the whole function
7970 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007971 synchronized (networkAgent) {
7972 networkAgent.linkProperties = newLp;
7973 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007974 // Start or stop DNS64 detection and 464xlat according to network state.
7975 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08007976 // Notify NSS when relevant events happened. Currently, NSS only cares about
7977 // interface changed to update clat interfaces accounting.
7978 final boolean interfacesChanged = oldLp == null
7979 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
7980 if (interfacesChanged) {
7981 notifyIfacesChangedForNetworkStats();
7982 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007983 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7984 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09007985 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007986 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007987
7988 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007989 }
7990
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09007991 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
7992 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
7993 }
7994
Hai Shalome58bdc62021-01-11 18:45:34 -08007995 /**
7996 * @param naData captive portal data from NetworkAgent
7997 * @param apiData captive portal data from capport API
7998 */
7999 @Nullable
8000 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8001 CaptivePortalData apiData) {
8002 if (naData == null || apiData == null) {
8003 return naData == null ? apiData : naData;
8004 }
8005 final CaptivePortalData.Builder captivePortalBuilder =
8006 new CaptivePortalData.Builder(naData);
8007
8008 if (apiData.isCaptive()) {
8009 captivePortalBuilder.setCaptive(true);
8010 }
8011 if (apiData.isSessionExtendable()) {
8012 captivePortalBuilder.setSessionExtendable(true);
8013 }
8014 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8015 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8016 // otherwise data would be inconsistent. Prefer the capport API info if present,
8017 // as it can generally be refreshed more often.
8018 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8019 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8020 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8021 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8022 // No source has time / bytes remaining information: surface the newest refresh time
8023 // for other fields
8024 captivePortalBuilder.setRefreshTime(
8025 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8026 }
8027
Hai Shalom7c6ab402021-02-04 19:34:06 -08008028 // Prioritize the user portal URL from the network agent if the source is authenticated.
8029 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8030 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8031 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8032 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008033 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008034 // Prioritize the venue information URL from the network agent if the source is
8035 // authenticated.
8036 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8037 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8038 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8039 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008040 }
8041 return captivePortalBuilder.build();
8042 }
8043
Suprabh Shukla619549f2023-04-26 18:47:36 -07008044 @VisibleForTesting
8045 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008046 // This needs to be kept in sync and backwards compatible with the decoding logic in
8047 // NetdEventListenerService, which is non-mainline code.
8048 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8049 }
8050
Suprabh Shukla63e59342023-04-25 23:15:43 -07008051 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8052 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8053 return true;
8054 }
8055 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8056 return true;
8057 }
8058 return false;
8059 }
8060
Suprabh Shukla1e312032023-01-24 03:36:37 -08008061 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008062 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008063 // marks on unsupported interfaces is harmless.
Suprabh Shukla63e59342023-04-25 23:15:43 -07008064 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008065 return;
8066 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008067
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008068 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
8069 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
8070
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008071 // Mask/mark of zero will not detect anything interesting.
8072 // Don't install rules unless both values are nonzero.
8073 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008074 return;
8075 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008076
Suprabh Shukla1e312032023-01-24 03:36:37 -08008077 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008078 try {
8079 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08008080 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008081 } else {
Luke Huang46289a22018-09-27 19:33:11 +08008082 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008083 }
8084 } catch (Exception e) {
8085 loge("Exception modifying wakeup packet monitoring: " + e);
8086 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008087 }
8088
Junyu Lai970963e2022-10-25 15:46:47 +08008089 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008090 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008091 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008092 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008093 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008094 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008095 for (final String iface : interfaceDiff.added) {
8096 try {
8097 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008098 mNetd.networkAddInterface(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008099 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008100 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008101 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008102 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008103 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008104 }
Paul Jensenbff73492014-04-28 10:33:11 -04008105 }
8106 }
Chalard Jean9589e722019-11-19 19:03:53 +09008107 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008108 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008109 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008110 wakeupModifyInterface(iface, nai, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008111 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008112 } catch (Exception e) {
8113 loge("Exception removing interface: " + e);
8114 }
8115 }
8116 }
8117
Tyler Weare4314862019-12-05 14:55:30 -08008118 // TODO: move to frameworks/libs/net.
8119 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
8120 final String nextHop;
8121
8122 switch (route.getType()) {
8123 case RouteInfo.RTN_UNICAST:
8124 if (route.hasGateway()) {
8125 nextHop = route.getGateway().getHostAddress();
8126 } else {
8127 nextHop = INetd.NEXTHOP_NONE;
8128 }
8129 break;
8130 case RouteInfo.RTN_UNREACHABLE:
8131 nextHop = INetd.NEXTHOP_UNREACHABLE;
8132 break;
8133 case RouteInfo.RTN_THROW:
8134 nextHop = INetd.NEXTHOP_THROW;
8135 break;
8136 default:
8137 nextHop = INetd.NEXTHOP_NONE;
8138 break;
8139 }
8140
8141 final RouteInfoParcel rip = new RouteInfoParcel();
8142 rip.ifName = route.getInterface();
8143 rip.destination = route.getDestination().toString();
8144 rip.nextHop = nextHop;
8145 rip.mtu = route.getMtu();
8146
8147 return rip;
8148 }
8149
Paul Jensene0fd4a82014-08-06 15:51:33 -04008150 /**
8151 * Have netd update routes from oldLp to newLp.
8152 * @return true if routes changed between oldLp and newLp
8153 */
Junyu Lai970963e2022-10-25 15:46:47 +08008154 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8155 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008156 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008157 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8158 new CompareOrUpdateResult<>(
8159 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008160 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008161 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008162
8163 // add routes before removing old in case it helps with continuous connectivity
8164
Chalard Jean9dd11612018-06-04 16:52:49 +09008165 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008166 for (RouteInfo route : routeDiff.added) {
8167 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008168 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008169 try {
Tyler Weare4314862019-12-05 14:55:30 -08008170 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008171 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008172 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008173 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008174 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008175 }
8176 }
8177 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008178 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008179 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008180 try {
Tyler Weare4314862019-12-05 14:55:30 -08008181 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008182 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008183 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008184 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008185 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008186 }
8187 }
8188
8189 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008190 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008191 try {
Tyler Weare4314862019-12-05 14:55:30 -08008192 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008193 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08008194 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008195 }
8196 }
Tyler Weare4314862019-12-05 14:55:30 -08008197
8198 for (RouteInfo route : routeDiff.updated) {
8199 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8200 try {
8201 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
8202 } catch (Exception e) {
8203 loge("Exception in networkUpdateRouteParcel: " + e);
8204 }
8205 }
8206 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8207 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008208 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008209
Junyu Lai970963e2022-10-25 15:46:47 +08008210 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8211 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008212 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8213 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008214 }
Erik Klineb9888902016-04-05 13:30:49 +09008215
Erik Kline31b4a9e2018-01-11 21:07:29 +09008216 if (DBG) {
8217 final Collection<InetAddress> dnses = newLp.getDnsServers();
8218 log("Setting DNS servers for network " + netId + " to " + dnses);
8219 }
Erik Klineb9888902016-04-05 13:30:49 +09008220 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008221 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008222 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008223 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008224 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008225 }
Erik Kline54e35c02017-04-07 15:29:29 +09008226 }
8227
Junyu Lai970963e2022-10-25 15:46:47 +08008228 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8229 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008230 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8231 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008232 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8233 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008234
8235 if (!wasFiltering && !needsFiltering) {
8236 // Nothing to do.
8237 return;
8238 }
8239
8240 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8241 // Nothing changed.
8242 return;
8243 }
8244
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008245 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008246 if (ranges == null || ranges.isEmpty()) {
8247 return;
8248 }
8249
Qingxi Libb8da982020-01-17 17:54:27 -08008250 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008251 // TODO: this create a window of opportunity for apps to receive traffic between the time
8252 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008253 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008254 // old rules are being removed.
8255 if (wasFiltering) {
8256 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8257 }
8258 if (needsFiltering) {
8259 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8260 }
8261 }
8262
Valentin Iftime9fa35092019-09-24 13:32:13 +02008263 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008264 if (mWolSupportedInterfaces == null) {
8265 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008266 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008267 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008268 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8269 }
8270
Luke Huangb913c812018-08-24 20:33:16 +08008271 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008272 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008273 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008274 }
8275 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008276 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008277 }
Luke Huangb913c812018-08-24 20:33:16 +08008278 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008279 }
8280
Chalard Jean62edfd82019-12-02 18:39:29 +09008281 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8282 @NonNull final NetworkCapabilities newNc) {
8283 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8284 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008285 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008286 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008287 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008288 } catch (RemoteException | ServiceSpecificException e) {
8289 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008290 }
8291 }
8292 }
8293
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008294 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008295 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008296 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008297 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008298 underlyingNetworks = underlyingNetworksOrDefault(
8299 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008300 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008301 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8302 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008303 // metered if any underlying is metered, or originally declared metered by the agent.
8304 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008305 boolean roaming = false; // roaming if any underlying is roaming
8306 boolean congested = false; // congested if any underlying is congested
8307 boolean suspended = true; // suspended if all underlying are suspended
8308
8309 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008310 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008311 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008312 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008313 for (Network underlyingNetwork : underlyingNetworks) {
8314 final NetworkAgentInfo underlying =
8315 getNetworkAgentInfoForNetwork(underlyingNetwork);
8316 if (underlying == null) continue;
8317
8318 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8319 hadUnderlyingNetworks = true;
8320 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008321 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008322 }
8323
8324 // Merge capabilities of this underlying network. For bandwidth, assume the
8325 // worst case.
8326 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8327 underlyingCaps.getLinkDownstreamBandwidthKbps());
8328 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8329 underlyingCaps.getLinkUpstreamBandwidthKbps());
8330 // If this underlying network is metered, the VPN is metered (it may cost money
8331 // to send packets on this network).
8332 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8333 // If this underlying network is roaming, the VPN is roaming (the billing structure
8334 // is different than the usual, local one).
8335 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8336 // If this underlying network is congested, the VPN is congested (the current
8337 // condition of the network affects the performance of this network).
8338 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8339 // If this network is not suspended, the VPN is not suspended (the VPN
8340 // is able to transfer some data).
8341 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008342 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008343 }
8344 }
8345 if (!hadUnderlyingNetworks) {
8346 // No idea what the underlying networks are; assume reasonable defaults
8347 metered = true;
8348 roaming = false;
8349 congested = false;
8350 suspended = false;
8351 }
8352
Chalard Jean1d420b32022-10-12 16:39:37 +09008353 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008354 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8355 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8356 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8357 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8358 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8359 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008360 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008361 }
8362
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008363 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008364 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8365 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8366 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008367 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008368 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008369 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008370 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008371 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8372 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008373 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008374 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008375 if (nai.everConnected()
8376 && !nai.isVPN()
8377 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008378 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008379 // does not cause any request (that is not a listen) currently matching that agent to
8380 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008381 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008382 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008383 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008384 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008385 }
8386
Paul Jensen53f08952015-06-16 14:27:36 -04008387 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008388 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008389 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008390 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008391 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008392 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008393 }
Chalard Jean254bd162022-08-25 13:04:51 +09008394 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008395 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008396 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008397 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008398 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008399 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008400 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008401 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008402 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008403 }
Chalard Jean254bd162022-08-25 13:04:51 +09008404 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008405 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8406 } else {
8407 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8408 }
lucasline117e2e2019-10-22 18:27:33 +08008409 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008410
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008411 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008412 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8413 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008414 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008415 }
8416
Lorenzo Colittibd079452021-07-02 11:47:57 +09008417 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008418 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008419 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008420 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008421 }
8422
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008423 return newNc;
8424 }
8425
Lorenzo Colitti44840702021-01-11 22:27:57 +09008426 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8427 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8428 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8429 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8430 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8431 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8432 if (prevSuspended != suspended) {
8433 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8434 // onResumed have been removed.
8435 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8436 : ConnectivityManager.CALLBACK_RESUMED);
8437 }
8438 if (prevSuspended != suspended || prevRoaming != roaming) {
8439 // updateNetworkInfo will mix in the suspended info from the capabilities and
8440 // take appropriate action for the network having possibly changed state.
8441 updateNetworkInfo(nai, nai.networkInfo);
8442 }
8443 }
8444
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008445 /**
8446 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8447 *
8448 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8449 * capabilities we manage and store in {@code nai}, such as validated status and captive
8450 * portal status)
8451 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8452 * potentially triggers rematches.
8453 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8454 * change.)
8455 *
8456 * @param oldScore score of the network before any of the changes that prompted us
8457 * to call this function.
8458 * @param nai the network having its capabilities updated.
8459 * @param nc the new network capabilities.
8460 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008461 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008462 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008463 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008464 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008465 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8466 if (null != differences) {
8467 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8468 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008469 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008470 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008471
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008472 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008473 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008474 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008475
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008476 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008477 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8478 // the change we're processing can't affect any requests, it can only affect the listens
8479 // on this network. We might have been called by rematchNetworkAndRequests when a
8480 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008481 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008482 } else {
8483 // If the requestable capabilities have changed or the score changed, we can't have been
8484 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008485 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008486 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008487 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008488 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008489
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008490 final boolean oldMetered = prevNc.isMetered();
8491 final boolean newMetered = newNc.isMetered();
8492 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008493
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008494 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008495 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8496 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008497 }
junyulaif2c67e42018-08-07 19:50:45 +08008498
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008499 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8500 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008501
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008502 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008503 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008504 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008505 }
8506
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008507 // This network might have been underlying another network. Propagate its capabilities.
8508 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008509
8510 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008511 mDnsManager.updateTransportsForNetwork(
8512 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008513 }
lucaslin53e8a262021-06-08 01:43:59 +08008514
8515 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008516 }
8517
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008518 /** Convenience method to update the capabilities for a given network. */
8519 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008520 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008521 }
8522
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008523 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008524 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008525 *
8526 * Ingress interface filtering enforces that all apps under the given network can only receive
8527 * packets from the network's interface (and loopback). This is important for VPNs because
8528 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8529 * non-VPN interfaces.
8530 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008531 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008532 * 1. the network is an app VPN (not legacy VPN)
8533 * 2. the VPN does not allow bypass
8534 * 3. the VPN is fully-routed
8535 * 4. the VPN interface is non-null
8536 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008537 * @see INetd#firewallAddUidInterfaceRules
8538 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008539 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008540 @Nullable
8541 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008542 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008543 if (nc == null || lp == null) return null;
8544 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008545 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008546 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008547 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008548 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008549 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008550 && !lp.hasExcludeRoute()) {
8551 return lp.getInterfaceName();
8552 }
8553 return null;
8554 }
8555
8556 /**
8557 * Returns whether we need to set interface filtering rule or not
8558 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008559 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008560 String isolationIface) {
8561 // Allow rules are always needed if VPN isolation is enabled.
8562 if (isolationIface != null) return true;
8563
8564 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8565 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8566 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
8567 return SdkLevel.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008568 }
8569
Chiachang Wang28afaff2020-12-10 22:24:47 +08008570 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8571 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8572 int index = 0;
8573 for (UidRange range : ranges) {
8574 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8575 index++;
8576 }
8577 return stableRanges;
8578 }
8579
Chalard Jeane6c95272022-01-25 21:04:21 +09008580 private static UidRangeParcel[] intsToUidRangeStableParcels(
8581 final @NonNull ArraySet<Integer> uids) {
8582 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8583 int index = 0;
8584 for (int uid : uids) {
8585 stableRanges[index] = new UidRangeParcel(uid, uid);
8586 index++;
8587 }
8588 return stableRanges;
8589 }
8590
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008591 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8592 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8593 for (int i = 0; i < ranges.length; i++) {
8594 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8595 }
8596 return stableRanges;
8597 }
8598
Motomu Utsumia20f7602023-03-16 17:04:21 +09008599 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
8600 Set<Integer> exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08008601 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8602 try {
Motomu Utsumia20f7602023-03-16 17:04:21 +09008603 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008604 } catch (Exception e) {
8605 loge("Exception in socket destroy: ", e);
8606 }
8607 }
8608 }
8609
paulhuaa0743d2021-05-26 21:56:03 +08008610 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumia20f7602023-03-16 17:04:21 +09008611 final Set<Integer> exemptUids = new ArraySet<>();
Ken Chen5e65a852020-12-24 12:59:10 +08008612 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8613 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8614 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumia20f7602023-03-16 17:04:21 +09008615 exemptUids.add(VPN_UID);
8616 exemptUids.add(nai.networkCapabilities.getOwnerUid());
Ken Chen5e65a852020-12-24 12:59:10 +08008617 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8618
Motomu Utsumi6345e462023-03-13 13:24:50 +09008619 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumia20f7602023-03-16 17:04:21 +09008620 maybeCloseSockets(nai, uidRanges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008621 try {
8622 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008623 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008624 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008625 } else {
paulhu0e79d952021-06-09 16:11:35 +08008626 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008627 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008628 }
8629 } catch (Exception e) {
8630 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8631 " on netId " + nai.network.netId + ". " + e);
8632 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09008633 // Close sockets that established connection while requesting netd.
Motomu Utsumia20f7602023-03-16 17:04:21 +09008634 maybeCloseSockets(nai, uidRanges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008635 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008636
lucaslin53e8a262021-06-08 01:43:59 +08008637 private boolean isProxySetOnAnyDefaultNetwork() {
8638 ensureRunningOnConnectivityServiceThread();
8639 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8640 final NetworkAgentInfo nai = nri.getSatisfier();
8641 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8642 return true;
8643 }
8644 }
8645 return false;
8646 }
8647
8648 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8649 NetworkCapabilities newNc) {
8650 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8651 // the proxy might be changed since the default network satisfied by the apps might also
8652 // changed.
8653 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8654 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008655 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8656 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008657 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008658 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8659 mProxyTracker.sendProxyBroadcast();
8660 }
8661 }
8662
Chalard Jeane6c95272022-01-25 21:04:21 +09008663 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8664 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008665 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8666 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008667 if (null == prevRanges) prevRanges = new ArraySet<>();
8668 if (null == newRanges) newRanges = new ArraySet<>();
8669 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8670
8671 prevRanges.removeAll(newRanges);
8672 newRanges.removeAll(prevRangesCopy);
8673
8674 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008675 // When updating the VPN uid routing rules, add the new range first then remove the old
8676 // range. If old range were removed first, there would be a window between the old
8677 // range being removed and the new range being added, during which UIDs contained
8678 // in both ranges are not subject to any VPN routing rules. Adding new range before
8679 // removing old range works because, unlike the filtering rules below, it's possible to
8680 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008681 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8682 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8683 // [1-5] & [1-2],[4-5] == [3]
8684 // Then we can do:
8685 // maybeCloseSockets([3])
8686 // mNetd.networkAddUidRanges([1-2],[4-5])
8687 // mNetd.networkRemoveUidRanges([1-5])
8688 // maybeCloseSockets([3])
8689 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8690 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008691 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008692 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008693 }
8694 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008695 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008696 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00008697 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
8698 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008699 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
8700 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008701 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008702 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008703 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8704 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8705 // were added first and then newRanges got removed later, there would be only one uid
8706 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8707 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8708 // Note that this is in contrast with the (more robust) update of VPN routing rules
8709 // above, where the addition of new ranges happens before the removal of old ranges.
8710 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8711 // to be removed will never overlap with the new range to be added.
8712 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008713 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
8714 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008715 }
8716 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008717 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008718 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008719 } catch (Exception e) {
8720 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008721 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008722 }
8723 }
8724
Chalard Jeande665262022-02-25 16:12:12 +09008725 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09008726 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8727 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09008728 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
8729 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09008730 if (prevEmpty && newEmpty) return;
8731
8732 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09008733 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008734 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09008735 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008736
8737 if (prevUids.equals(newUids)) return;
8738
8739 // This implementation is very simple and vastly faster for sets of Integers than
8740 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8741 // a key computed from the value and has storage for that.
8742 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8743 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8744 toRemove.removeAll(newUids);
8745 toAdd.removeAll(prevUids);
8746
8747 try {
8748 if (!toAdd.isEmpty()) {
8749 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8750 nai.network.netId,
8751 intsToUidRangeStableParcels(toAdd),
8752 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8753 }
8754 if (!toRemove.isEmpty()) {
8755 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8756 nai.network.netId,
8757 intsToUidRangeStableParcels(toRemove),
8758 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8759 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008760 } catch (ServiceSpecificException e) {
8761 // Has the interface disappeared since the network was built ?
8762 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008763 } catch (RemoteException e) {
8764 // Netd died. This usually causes a runtime restart anyway.
8765 }
8766 }
8767
Junyu Lai2ed7d412022-10-07 16:52:21 +08008768 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
8769 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008770 ensureRunningOnConnectivityServiceThread();
8771
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008772 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008773 // Ignore updates for disconnected networks
8774 return;
8775 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008776 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008777 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09008778 + "; created=" + nai.getCreatedTime()
8779 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00008780 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008781 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8782 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008783 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008784 }
8785
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008786 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8787 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008788 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008789 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008790 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008791 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8792 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8793 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008794 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8795 // need to be sent as a separate extra.
8796 final NetworkRequest req = nri.isMultilayerRequest()
8797 ? nri.getActiveRequest()
8798 // Non-multilayer listen requests do not have an active request
8799 : nri.mRequests.get(0);
8800 if (req == null) {
8801 Log.wtf(TAG, "No request in NRI " + nri);
8802 }
8803 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008804 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008805 sendIntent(nri.mPendingIntent, intent);
8806 }
8807 // else not handled
8808 }
8809
Michael Groover73f69482023-01-27 11:01:25 -06008810 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
8811 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008812 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8813 mPendingIntentWakeLock.acquire();
8814 try {
8815 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00008816 final BroadcastOptions options = BroadcastOptions.makeBasic();
8817 if (SdkLevel.isAtLeastT()) {
8818 // Explicitly disallow the receiver from starting activities, to prevent apps from
8819 // utilizing the PendingIntent as a backdoor to do this.
8820 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
8821 }
8822 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
8823 null /* requiredPermission */,
8824 SdkLevel.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008825 } catch (PendingIntent.CanceledException e) {
8826 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8827 mPendingIntentWakeLock.release();
8828 releasePendingNetworkRequest(pendingIntent);
8829 }
8830 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8831 }
8832
8833 @Override
8834 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8835 String resultData, Bundle resultExtras) {
8836 if (DBG) log("Finished sending " + pendingIntent);
8837 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008838 // Release with a delay so the receiving client has an opportunity to put in its
8839 // own request.
8840 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008841 }
8842
Chalard Jean46bfbf02022-02-02 00:56:25 +09008843 // networkAgent is only allowed to be null if notificationType is
8844 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
8845 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08008846 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09008847 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08008848 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008849 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008850 // Default request has no msgr. Also prevents callbacks from being invoked for
8851 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8852 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8853 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008854 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008855 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008856 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008857 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008858 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008859 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008860 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008861 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8862 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008863 }
Roshan Pius951c0032020-12-22 15:10:42 -08008864 final boolean includeLocationSensitiveInfo =
8865 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008866 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008867 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008868 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08008869 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09008870 networkCapabilitiesRestrictedForCallerPermissions(
8871 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
8872 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008873 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09008874 nri.mCallingAttributionTag);
8875 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008876 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8877 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008878 // For this notification, arg1 contains the blocked status.
8879 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008880 break;
8881 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008882 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008883 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008884 break;
8885 }
8886 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008887 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008888 final NetworkCapabilities netCap =
8889 networkCapabilitiesRestrictedForCallerPermissions(
8890 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8891 putParcelable(
8892 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008893 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008894 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008895 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008896 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008897 break;
8898 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008899 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008900 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8901 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008902 break;
8903 }
junyulaif2c67e42018-08-07 19:50:45 +08008904 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008905 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008906 msg.arg1 = arg1;
8907 break;
8908 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008909 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008910 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008911 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008912 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008913 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008914 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008915 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008916 }
James Mattis45d81842021-01-10 14:24:24 -08008917 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008918 } catch (RemoteException e) {
8919 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008920 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008921 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008922 }
8923
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008924 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8925 bundle.putParcelable(t.getClass().getSimpleName(), t);
8926 }
8927
Chalard Jean0702f982021-09-16 21:50:07 +09008928 /**
8929 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8930 *
8931 * When a request should be assigned to a new network, it is normally lingered to give
8932 * time for apps to gracefully migrate their connections. When both networks are on the same
8933 * radio, but that radio can't do time-sharing efficiently, this may end up being
8934 * counter-productive because any traffic on the old network may drastically reduce the
8935 * performance of the new network.
8936 * The stack supports a configuration to let modem vendors state that their radio can't
8937 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8938 * from one cell network to another can't be done gracefully.
8939 *
8940 * @param oldNai the old network serving the request
8941 * @param newNai the new network serving the request
8942 * @return whether the switch can be graceful
8943 */
8944 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8945 @NonNull final NetworkAgentInfo newSatisfier) {
8946 if (mCellularRadioTimesharingCapable) return true;
8947 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8948 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8949 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8950 }
8951
Paul Jensenaf94b982014-09-30 15:37:41 -04008952 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008953 if (nai.numRequestNetworkRequests() != 0) {
8954 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8955 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008956 // Ignore listening and track default requests.
8957 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008958 loge("Dead network still had at least " + nr);
8959 break;
8960 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008961 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008962 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008963 }
8964
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008965 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8966 if (oldNetwork == null) {
8967 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8968 return;
8969 }
Chalard Jean49707572019-12-10 21:07:02 +09008970 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008971
8972 // If we get here it means that the last linger timeout for this network expired. So there
8973 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008974 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008975
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008976 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008977 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008978 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008979 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008980 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008981 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008982 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008983 }
8984
James Mattise3ef1912020-12-20 11:09:58 -08008985 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8986 boolean isDefaultChanged = false;
8987 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8988 final NetworkReassignment.RequestReassignment reassignment =
8989 changes.getReassignment(defaultRequestInfo);
8990 if (null == reassignment) {
8991 continue;
8992 }
8993 // reassignment only contains those instances where the satisfying network changed.
8994 isDefaultChanged = true;
8995 // Notify system services of the new default.
8996 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8997 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008998
James Mattise3ef1912020-12-20 11:09:58 -08008999 if (isDefaultChanged) {
9000 // Hold a wakelock for a short time to help apps in migrating to a new default.
9001 scheduleReleaseNetworkTransitionWakelock();
9002 }
9003 }
9004
9005 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9006 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9007 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9008 if (DBG) {
9009 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9010 }
Chalard Jean8e382112019-12-03 20:45:30 +09009011
James Mattisd31bdfa2020-12-23 16:37:26 -08009012 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9013 if (newDefaultNetwork != null) {
9014 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009015 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009016
James Mattisd31bdfa2020-12-23 16:37:26 -08009017 // Set an app level managed default and return since further processing only applies to the
9018 // default network.
9019 if (mDefaultRequest != nri) {
9020 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9021 return;
9022 }
9023
9024 makeDefaultNetwork(newDefaultNetwork);
9025
James Mattise3ef1912020-12-20 11:09:58 -08009026 if (oldDefaultNetwork != null) {
9027 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9028 }
9029 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009030 handleApplyDefaultProxy(null != newDefaultNetwork
9031 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
9032 updateTcpBufferSizes(null != newDefaultNetwork
9033 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009034 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009035 }
9036
James Mattisd31bdfa2020-12-23 16:37:26 -08009037 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9038 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9039 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9040 try {
9041 if (VDBG) {
9042 log("Setting default network for " + nri
9043 + " using UIDs " + nri.getUids()
9044 + " with old network " + (oldDefaultNetwork != null
9045 ? oldDefaultNetwork.network().getNetId() : "null")
9046 + " and new network " + (newDefaultNetwork != null
9047 ? newDefaultNetwork.network().getNetId() : "null"));
9048 }
9049 if (nri.getUids().isEmpty()) {
9050 throw new IllegalStateException("makeDefaultForApps called without specifying"
9051 + " any applications to set as the default." + nri);
9052 }
9053 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009054 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009055 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009056 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009057 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009058 }
9059 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009060 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009061 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009062 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009063 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009064 }
9065 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009066 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009067 }
9068 }
9069
Junyu Lai35665cc2022-12-19 17:37:48 +08009070 /**
9071 * Collect restricted uid ranges for the given network and UserHandle, these uids
9072 * are not restricted for matched enterprise networks but being restricted for non-matched
9073 * enterprise networks and non-enterprise networks.
9074 */
9075 @NonNull
9076 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9077 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9078 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9079 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9080 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9081
9082 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9083 // The NC is built from a `ProfileNetworkPreference` which has only one
9084 // enterprise ID, so it's guaranteed to have exactly one.
9085 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9086 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9087 continue;
9088 }
9089 }
9090
9091 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9092 pref.capabilities.getUidRanges())) {
9093 throw new IllegalArgumentException(
9094 "Overlapping uid range in preference: " + pref);
9095 }
9096 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9097 }
9098 return restrictedUidRanges;
9099 }
9100
9101 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009102 // Netd command is not implemented before U.
9103 if (!SdkLevel.isAtLeastU()) return;
9104
Junyu Lai35665cc2022-12-19 17:37:48 +08009105 ensureRunningOnConnectivityServiceThread();
9106 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9107 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9108 .getUserHandles(true /* excludeDying */);
9109 if (users.isEmpty()) {
9110 throw new IllegalStateException("No user is available");
9111 }
9112
9113 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9114 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9115 for (final UserHandle user : users) {
9116 final ArraySet<UidRange> restrictedUidRanges =
9117 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9118 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9119 UidRange.createForUser(user), restrictedUidRanges));
9120 }
9121
9122 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9123 configs.add(new NativeUidRangeConfig(
9124 nai.network.netId, rangesParcel, 0 /* subPriority */));
9125 }
9126
9127 // The netd API replaces the previous configs with the current configs.
9128 // Thus, for network disconnection or preference removal, no need to
9129 // unset previous config. Instead, collecting all currently needed
9130 // configs and issue to netd.
9131 try {
9132 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9133 } catch (ServiceSpecificException e) {
9134 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009135 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009136 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009137 // Netd died. This will cause a runtime restart anyway.
9138 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009139 }
9140 }
9141
James Mattisd31bdfa2020-12-23 16:37:26 -08009142 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9143 try {
9144 if (null != newDefaultNetwork) {
9145 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9146 } else {
9147 mNetd.networkClearDefault();
9148 }
9149 } catch (RemoteException | ServiceSpecificException e) {
9150 loge("Exception setting default network :" + e);
9151 }
9152 }
9153
Chalard Jean05cbe972019-12-09 11:50:38 +09009154 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009155 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009156 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009157 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009158 processNewlySatisfiedListenRequests(nai);
9159 }
9160
9161 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009162 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9163 if (nri.isMultilayerRequest()) {
9164 continue;
9165 }
9166 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009167 if (!nr.isListen()) continue;
9168 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009169 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009170 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9171 }
9172 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009173 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009174
Chalard Jeancd397a22019-11-22 22:33:33 +09009175 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009176 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9177 if (nri.isMultilayerRequest()) {
9178 continue;
9179 }
9180 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009181 if (!nr.isListen()) continue;
9182 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9183 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009184 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009185 }
9186 }
9187 }
9188
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009189 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009190 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009191 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009192 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009193 @Nullable public final NetworkRequest mOldNetworkRequest;
9194 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009195 @Nullable public final NetworkAgentInfo mOldNetwork;
9196 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009197 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009198 @Nullable final NetworkRequest oldNetworkRequest,
9199 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009200 @Nullable final NetworkAgentInfo oldNetwork,
9201 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009202 mNetworkRequestInfo = networkRequestInfo;
9203 mOldNetworkRequest = oldNetworkRequest;
9204 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009205 mOldNetwork = oldNetwork;
9206 mNewNetwork = newNetwork;
9207 }
Chalard Jean49707572019-12-10 21:07:02 +09009208
9209 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009210 final NetworkRequest requestToShow = null != mNewNetworkRequest
9211 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9212 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009213 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9214 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009215 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009216 }
9217
Chalard Jean46a62372019-12-10 21:25:24 +09009218 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009219
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009220 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009221 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009222 }
9223
9224 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009225 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009226 // The code is never supposed to add two reassignments of the same request. Make
9227 // sure this stays true, but without imposing this expensive check on all
9228 // reassignments on all user devices.
9229 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009230 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009231 throw new IllegalStateException("Trying to reassign ["
9232 + reassignment + "] but already have ["
9233 + existing + "]");
9234 }
9235 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009236 }
Chalard Jean46a62372019-12-10 21:25:24 +09009237 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009238 }
9239
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009240 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009241 // the passed request.
9242 @Nullable
9243 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009244 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009245 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009246 }
9247 return null;
9248 }
Chalard Jean49707572019-12-10 21:07:02 +09009249
9250 public String toString() {
9251 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9252 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009253 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009254 for (final RequestReassignment rr : getRequestReassignments()) {
9255 sj.add(rr.toString());
9256 }
9257 return sj.toString();
9258 }
9259
9260 public String debugString() {
9261 final StringBuilder sb = new StringBuilder();
9262 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009263 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009264 for (final RequestReassignment rr : getRequestReassignments()) {
9265 sb.append("\n ").append(rr);
9266 }
9267 return sb.append("\n").toString();
9268 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009269 }
9270
Chalard Jean24344d72019-12-04 13:32:31 +09009271 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009272 @Nullable final NetworkRequest previousRequest,
9273 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009274 @Nullable final NetworkAgentInfo previousSatisfier,
9275 @Nullable final NetworkAgentInfo newSatisfier,
9276 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009277 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009278 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009279 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009280 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009281 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09009282 }
James Mattisa076c532020-12-02 14:12:41 -08009283 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009284 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009285 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009286 // If this network switch can't be supported gracefully, the request is not
9287 // lingered. This allows letting go of the network sooner to reclaim some
9288 // performance on the new network, since the radio can't do both at the same
9289 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009290 //
9291 // Also don't linger the request if the old network has been destroyed.
9292 // A destroyed network does not provide actual network connectivity, so
9293 // lingering it is not useful. In particular this ensures that a destroyed
9294 // network is outscored by its replacement,
9295 // then it is torn down immediately instead of being lingered, and any apps that
9296 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009297 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9298 }
Chalard Jean24344d72019-12-04 13:32:31 +09009299 } else {
9300 if (VDBG || DDBG) log(" accepting network in place of null");
9301 }
junyulai0ac374f2020-12-14 18:41:52 +08009302
9303 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9304 // and immediately satisfies a request then remove the timer. This will happen for
9305 // all networks except in the case of an underlying network for a VCN.
9306 if (newSatisfier.isNascent()) {
9307 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009308 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009309 }
9310
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009311 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009312 newSatisfier.unlingerRequest(newRequest.requestId);
9313 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009314 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009315 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009316 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009317 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009318 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009319 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009320 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009321 }
James Mattisa076c532020-12-02 14:12:41 -08009322 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009323 }
James Mattisa076c532020-12-02 14:12:41 -08009324 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009325 }
9326
James Mattisa076c532020-12-02 14:12:41 -08009327 /**
9328 * This function is triggered when something can affect what network should satisfy what
9329 * request, and it computes the network reassignment from the passed collection of requests to
9330 * network match to the one that the system should now have. That data is encoded in an
9331 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9332 * satisfier.
9333 *
9334 * After the reassignment is computed, it is applied to the state objects.
9335 *
9336 * @param networkRequests the nri objects to evaluate for possible network reassignment
9337 * @return NetworkReassignment listing of proposed network assignment changes
9338 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009339 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009340 private NetworkReassignment computeNetworkReassignment(
9341 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009342 final NetworkReassignment changes = new NetworkReassignment();
9343
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009344 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009345 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009346 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009347 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009348 }
Chalard Jean857a1712019-12-10 21:08:07 +09009349
James Mattisa076c532020-12-02 14:12:41 -08009350 for (final NetworkRequestInfo nri : networkRequests) {
9351 // Non-multilayer listen requests can be ignored.
9352 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9353 continue;
9354 }
9355 NetworkAgentInfo bestNetwork = null;
9356 NetworkRequest bestRequest = null;
9357 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009358 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009359 // Stop evaluating as the highest possible priority request is satisfied.
9360 if (null != bestNetwork) {
9361 bestRequest = req;
9362 break;
9363 }
9364 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009365 if (null == bestNetwork && isDefaultBlocked(nri)) {
9366 // Remove default networking if disallowed for managed default requests.
9367 bestNetwork = mNoServiceNetwork;
9368 }
9369 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009370 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009371 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009372 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009373 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009374 }
9375 return changes;
9376 }
9377
James Mattisa076c532020-12-02 14:12:41 -08009378 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9379 return new HashSet<>(mNetworkRequests.values());
9380 }
9381
Paul Jensenc88b39b2015-06-16 14:27:36 -04009382 /**
James Mattisa076c532020-12-02 14:12:41 -08009383 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009384 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009385 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009386 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009387 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9388 }
9389
9390 /**
9391 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9392 * being disconnected.
9393 */
9394 private void rematchNetworksAndRequests(
9395 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9396 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009397 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009398 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009399 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009400 final long computed = SystemClock.elapsedRealtime();
9401 applyNetworkReassignment(changes, start);
9402 final long applied = SystemClock.elapsedRealtime();
9403 issueNetworkNeeds();
9404 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009405 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009406 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9407 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009408 log(changes.debugString());
9409 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009410 // Shorter form, only one line of log
9411 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9412 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009413 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009414 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009415
Chalard Jeand7f762d2019-12-10 19:01:29 +09009416 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009417 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009418 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009419
9420 // Since most of the time there are only 0 or 1 background networks, it would probably
9421 // be more efficient to just use an ArrayList here. TODO : measure performance
9422 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9423 for (final NetworkAgentInfo nai : nais) {
9424 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9425 }
9426
Chalard Jeand7f762d2019-12-10 19:01:29 +09009427 // First, update the lists of satisfied requests in the network agents. This is necessary
9428 // because some code later depends on this state to be correct, most prominently computing
9429 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009430 for (final NetworkReassignment.RequestReassignment event :
9431 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009432 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9433 event.mOldNetworkRequest, event.mNewNetworkRequest,
9434 event.mOldNetwork, event.mNewNetwork,
9435 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009436 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009437
James Mattise3ef1912020-12-20 11:09:58 -08009438 // Process default network changes if applicable.
9439 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009440
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009441 // Notify requested networks are available after the default net is switched, but
9442 // before LegacyTypeTracker sends legacy broadcasts
9443 for (final NetworkReassignment.RequestReassignment event :
9444 changes.getRequestReassignments()) {
9445 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009446 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009447 } else {
James Mattisa076c532020-12-02 14:12:41 -08009448 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009449 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009450 }
9451 }
9452
junyulai0ac374f2020-12-14 18:41:52 +08009453 // Update the inactivity state before processing listen callbacks, because the background
9454 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009455 // just yet though, because they have to be sent after the listens are processed to keep
9456 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009457 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009458 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009459 // Rematching may have altered the inactivity state of some networks, so update all
9460 // inactivity timers. updateInactivityState reads the state from the network agent
9461 // and does nothing if the state has not changed : the source of truth is controlled
9462 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9463 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009464 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009465 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009466 }
9467 }
9468
Chalard Jeanb10ab412019-12-11 14:12:30 +09009469 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009470 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009471 // Process listen requests and update capabilities if the background state has
9472 // changed for this network. For consistency with previous behavior, send onLost
9473 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009474 processNewlyLostListenRequests(nai);
9475 if (oldBackground != nai.isBackgroundNetwork()) {
9476 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009477 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009478 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009479 }
9480
junyulai0ac374f2020-12-14 18:41:52 +08009481 for (final NetworkAgentInfo nai : inactiveNetworks) {
9482 // For nascent networks, if connecting with no foreground request, skip broadcasting
9483 // LOSING for backward compatibility. This is typical when mobile data connected while
9484 // wifi connected with mobile data always-on enabled.
9485 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009486 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009487 }
9488
James Mattise3ef1912020-12-20 11:09:58 -08009489 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009490
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009491 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009492 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009493 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009494 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009495 // This network has active linger timers and no requests, but is not
9496 // lingering. Linger it.
9497 //
9498 // One way (the only way?) this can happen if this network is unvalidated
9499 // and became unneeded due to another network improving its score to the
9500 // point where this network will no longer be able to satisfy any requests
9501 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009502 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009503 notifyNetworkLosing(nai, now);
9504 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009505 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009506 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009507 teardownUnneededNetwork(nai);
9508 }
9509 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009510 }
9511 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009512
Chalard Jean62edfd82019-12-02 18:39:29 +09009513 /**
9514 * Apply a change in background state resulting from rematching networks with requests.
9515 *
9516 * During rematch, a network may change background states by starting to satisfy or stopping
9517 * to satisfy a foreground request. Listens don't count for this. When a network changes
9518 * background states, its capabilities need to be updated and callbacks fired for the
9519 * capability change.
9520 *
9521 * @param nai The network that changed background states
9522 */
9523 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
9524 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
9525 if (Objects.equals(nai.networkCapabilities, newNc)) return;
9526 updateNetworkPermissions(nai, newNc);
9527 nai.getAndSetNetworkCapabilities(newNc);
9528 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
9529 }
9530
Chalard Jeanf0344532019-11-19 19:23:38 +09009531 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08009532 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009533 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09009534 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
9535 changes.getReassignment(mDefaultRequest);
9536 final NetworkAgentInfo oldDefaultNetwork =
9537 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
9538 final NetworkAgentInfo newDefaultNetwork =
9539 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08009540
Chalard Jean5b409c72021-02-04 13:12:59 +09009541 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009542 // Maintain the illusion : since the legacy API only understands one network at a time,
9543 // if the default network changed, apps should see a disconnected broadcast for the
9544 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009545 if (oldDefaultNetwork != null) {
9546 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9547 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009548 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009549 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009550 // The new default network can be newly null if and only if the old default
9551 // network doesn't satisfy the default request any more because it lost a
9552 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009553 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009554 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009555 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009556 }
9557 }
9558
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009559 // Now that all the callbacks have been sent, send the legacy network broadcasts
9560 // as needed. This is necessary so that legacy requests correctly bind dns
9561 // requests to this network. The legacy users are listening for this broadcast
9562 // and will generally do a dns request so they can ensureRouteToHost and if
9563 // they do that before the callbacks happen they'll use the default network.
9564 //
9565 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
9566 // callbacks, but if apps can receive the broadcast before the callback, they still might
9567 // have an inconsistent view of networking.
9568 //
9569 // This *does* introduce a race where if the user uses the new api
9570 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
9571 // they may get old info. Reverse this after the old startUsing api is removed.
9572 // This is on top of the multiple intent sequencing referenced in the todo above.
9573 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09009574 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009575 addNetworkToLegacyTypeTracker(nai);
9576 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08009577 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009578 }
9579
Chalard Jean0354d8c2021-01-12 10:58:56 +09009580 private void issueNetworkNeeds() {
9581 ensureRunningOnConnectivityServiceThread();
9582 for (final NetworkOfferInfo noi : mNetworkOffers) {
9583 issueNetworkNeeds(noi);
9584 }
9585 }
9586
9587 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
9588 ensureRunningOnConnectivityServiceThread();
9589 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9590 informOffer(nri, noi.offer, mNetworkRanker);
9591 }
9592 }
9593
9594 /**
9595 * Inform a NetworkOffer about any new situation of a request.
9596 *
9597 * This function handles updates to offers. A number of events may happen that require
9598 * updating the registrant for this offer about the situation :
9599 * • The offer itself was updated. This may lead the offer to no longer being able
9600 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
9601 * or conversely being strengthened enough to beat the satisfier (and therefore
9602 * start being needed)
9603 * • The network satisfying a request changed (including cases where the request
9604 * starts or stops being satisfied). The new network may be a stronger or weaker
9605 * match than the old one, possibly affecting whether the offer is needed.
9606 * • The network satisfying a request updated their score. This may lead the offer
9607 * to no longer be able to beat it if the current satisfier got better, or
9608 * conversely start being a good choice if the current satisfier got weaker.
9609 *
9610 * @param nri The request
9611 * @param offer The offer. This may be an updated offer.
9612 */
9613 private static void informOffer(@NonNull NetworkRequestInfo nri,
9614 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9615 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9616 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009617
9618 // Multi-layer requests have a currently active request, the one being satisfied.
9619 // Since the system will try to bring up a better network than is currently satisfying
9620 // the request, NetworkProviders need to be told the offers matching the requests *above*
9621 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9622 // not needed, and the offer is needed for the active request iff the offer can beat
9623 // the satisfier.
9624 // For non-multilayer requests, the logic above gracefully degenerates to only the
9625 // last case.
9626 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9627 // providers that the offer is needed for this request, until the active request is found.
9628 // In a second phase, deal with the currently active request. In a third phase, inform
9629 // the providers that offer is unneeded for the remaining requests.
9630
9631 // First phase : inform providers of all requests above the active request.
9632 int i;
9633 for (i = 0; nri.mRequests.size() > i; ++i) {
9634 final NetworkRequest request = nri.mRequests.get(i);
9635 if (activeRequest == request) break; // Found the active request : go to phase 2
9636 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9637 // Since this request is higher-priority than the one currently satisfied, if the
9638 // offer can satisfy it, the provider should try and bring up the network for sure ;
9639 // no need to even ask the ranker – an offer that can satisfy is always better than
9640 // no network. Hence tell the provider so unless it already knew.
9641 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9642 offer.onNetworkNeeded(request);
9643 }
9644 }
9645
9646 // Second phase : deal with the active request (if any)
9647 if (null != activeRequest && activeRequest.isRequest()) {
9648 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009649 // If an offer can satisfy the request, it is considered needed if it is currently
9650 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009651 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009652 && satisfier.factorySerialNumber == offer.providerId
9653 && activeRequest.canBeSatisfiedBy(offer.caps);
9654 final boolean newNeeded = currentlyServing
9655 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009656 if (newNeeded != oldNeeded) {
9657 if (newNeeded) {
9658 offer.onNetworkNeeded(activeRequest);
9659 } else {
9660 // The offer used to be able to beat the satisfier. Now it can't.
9661 offer.onNetworkUnneeded(activeRequest);
9662 }
9663 }
9664 }
9665
9666 // Third phase : inform the providers that the offer isn't needed for any request
9667 // below the active one.
9668 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
9669 final NetworkRequest request = nri.mRequests.get(i);
9670 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9671 // Since this request is lower-priority than the one currently satisfied, if the
9672 // offer can satisfy it, the provider should not try and bring up the network.
9673 // Hence tell the provider so unless it already knew.
9674 if (offer.neededFor(request)) {
9675 offer.onNetworkUnneeded(request);
9676 }
9677 }
9678 }
9679
Chalard Jean61c79252019-11-07 23:07:32 +09009680 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
9681 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9682 NetworkRequest nr = nai.requestAt(i);
9683 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
9684 // legacy type tracker filters out repeat adds
9685 mLegacyTypeTracker.add(nr.legacyType, nai);
9686 }
9687 }
9688
9689 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09009690 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09009691 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
9692 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
9693 if (nai.isVPN()) {
9694 mLegacyTypeTracker.add(TYPE_VPN, nai);
9695 }
9696 }
9697
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009698 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04009699 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +09009700 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09009701 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04009702 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09009703 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009704
Chalard Jean254bd162022-08-25 13:04:51 +09009705 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009706 // Don't repeat publish.
9707 if (newInetCondition == mDefaultInetConditionPublished) return;
9708
9709 mDefaultInetConditionPublished = newInetCondition;
9710 sendInetConditionBroadcast(nai.networkInfo);
9711 }
9712
Chalard Jeand61375d2020-01-14 22:46:36 +09009713 @NonNull
9714 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
9715 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009716 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09009717 final boolean suspended =
9718 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9719 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
9720 // Only override the state with SUSPENDED if the network is currently in CONNECTED
9721 // state. This is because the network could have been suspended before connecting,
9722 // or it could be disconnecting while being suspended, and in both these cases
9723 // the state should not be overridden. Note that the only detailed state that
9724 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
9725 // worry about multiple different substates of CONNECTED.
9726 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
9727 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009728 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
9729 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
9730 // network agent is created, then goes to suspended, then goes out of suspended without
9731 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +09009732 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009733 ? NetworkInfo.DetailedState.CONNECTED
9734 : NetworkInfo.DetailedState.CONNECTING,
9735 info.getReason(),
9736 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09009737 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009738 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09009739 return newInfo;
9740 }
9741
9742 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
9743 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
9744
Erik Kline99f301b2017-02-15 19:59:17 +09009745 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009746 NetworkInfo oldInfo = null;
9747 synchronized (networkAgent) {
9748 oldInfo = networkAgent.networkInfo;
9749 networkAgent.networkInfo = newInfo;
9750 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009751
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009752 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009753 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
9754 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009755 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009756
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09009757 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009758 // A network that has just connected has zero requests and is thus a foreground network.
9759 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
9760
Luke Huangfdd11f82019-04-09 18:41:49 +08009761 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09009762
9763 networkAgent.setCreated();
9764
9765 // If the network is created immediately on register, then apply the LinkProperties now.
9766 // Otherwise, this is done further down when the network goes into connected state.
9767 // Applying the LinkProperties means that the network is ready to carry traffic -
9768 // interfaces and routing rules have been added, DNS servers programmed, etc.
9769 // For VPNs, this must be done before the capabilities are updated, because as soon as
9770 // that happens, UIDs are routed to the network.
9771 if (shouldCreateNetworksImmediately()) {
9772 applyInitialLinkProperties(networkAgent);
9773 }
9774
9775 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
9776 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +09009777 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009778 // Initialize the network's capabilities to their starting values according to the
9779 // underlying networks. This ensures that the capabilities are correct before
9780 // anything happens to the network.
9781 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009782 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009783 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +09009784 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +08009785 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009786 }
9787
Chalard Jean254bd162022-08-25 13:04:51 +09009788 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
9789 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009790
lucaslin45e639b2019-04-03 17:09:28 +08009791 // NetworkCapabilities need to be set before sending the private DNS config to
9792 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009793 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9794
Erik Kline9a62f012018-03-21 07:18:33 -07009795 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09009796 if (!shouldCreateNetworksImmediately()) {
9797 applyInitialLinkProperties(networkAgent);
9798 } else {
9799 // The network was created when the agent registered, and the LinkProperties are
9800 // already up-to-date. However, updateLinkProperties also makes some changes only
9801 // when the network connects. Apply those changes here. On T and below these are
9802 // handled by the applyInitialLinkProperties call just above.
9803 // TODO: stop relying on updateLinkProperties(..., null) to do this.
9804 // If something depends on both LinkProperties and connected state, it should be in
9805 // this method as well.
9806 networkAgent.clatd.update();
9807 updateProxy(networkAgent.linkProperties, null);
9808 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009809
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +01009810 // If a rate limit has been configured and is applicable to this network (network
9811 // provides internet connectivity), apply it. The tc police filter cannot be attached
9812 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
9813 // updateInterfaces -> INetd#networkAddInterface.
9814 // Note: in case of a system server crash, the NetworkController constructor in netd
9815 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
9816 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9817 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9818 mIngressRateLimit);
9819 }
9820
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009821 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9822 // command must be sent after updating LinkProperties to maximize chances of
9823 // NetworkMonitor seeing the correct LinkProperties when starting.
9824 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009825 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009826 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009827 }
Chalard Jeand4900722022-02-06 12:25:38 +09009828 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9829 params.networkAgentConfig = networkAgent.networkAgentConfig;
9830 params.networkCapabilities = networkAgent.networkCapabilities;
9831 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9832 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +09009833 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
9834 // newer callback even before T. However getInterfaceVersion is a synchronized binder
9835 // call that would cause a Log.wtf to be emitted from the system_server process, and
9836 // in the absence of a satisfactory, scalable solution which follows an easy/standard
9837 // process to check the interface version, just use an SDK check. NetworkStack will
9838 // always be new enough when running on T+.
9839 if (SdkLevel.isAtLeastT()) {
9840 networkAgent.networkMonitor().notifyNetworkConnected(params);
9841 } else {
9842 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
9843 params.networkCapabilities);
9844 }
Chalard Jean1f2b50f2023-05-15 17:26:13 +09009845 final long delay = !avoidBadWifi() && activelyPreferBadWifi()
Chalard Jeane63c42f2022-09-16 19:31:45 +09009846 ? ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS
9847 : DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
9848 scheduleEvaluationTimeout(networkAgent.network, delay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009849
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009850 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9851 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9852 // capabilities, so it only needs to be done once on initial connect, not every time the
9853 // network's capabilities change. Note that we do this before rematching the network,
9854 // so we could decide to tear it down immediately afterwards. That's fine though - on
9855 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9856 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009857 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009858
junyulai0ac374f2020-12-14 18:41:52 +08009859 // Before first rematching networks, put an inactivity timer without any request, this
9860 // allows {@code updateInactivityState} to update the state accordingly and prevent
9861 // tearing down for any {@code unneeded} evaluation in this period.
9862 // Note that the timer will not be rescheduled since the expiry time is
9863 // fixed after connection regardless of the network satisfying other requests or not.
9864 // But it will be removed as soon as the network satisfies a request for the first time.
9865 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9866 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009867 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009868
Paul Jensen05e85ee2014-09-11 11:00:39 -04009869 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009870 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009871
9872 // This has to happen after matching the requests, because callbacks are just requests.
9873 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009874 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009875 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009876 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009877 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009878 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009879 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009880 if (networkAgent.isVPN()) {
9881 // As the active or bound network changes for apps, broadcast the default proxy, as
9882 // apps may need to update their proxy data. This is called after disconnecting from
9883 // VPN to make sure we do not broadcast the old proxy data.
9884 // TODO(b/122649188): send the broadcast only to VPN users.
9885 mProxyTracker.sendProxyBroadcast();
9886 }
Chalard Jean254bd162022-08-25 13:04:51 +09009887 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
9888 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009889 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009890 }
9891 }
9892
Chalard Jean28018572020-12-21 18:36:52 +09009893 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009894 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9895 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009896 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009897 }
9898
Erik Kline99f301b2017-02-15 19:59:17 +09009899 // Notify only this one new request of the current state. Transfer all the
9900 // current state by calling NetworkCapabilities and LinkProperties callbacks
9901 // so that callers can be guaranteed to have as close to atomicity in state
9902 // transfer as can be supported by this current API.
9903 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009904 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009905 if (nri.mPendingIntent != null) {
9906 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9907 // Attempt no subsequent state pushes where intents are involved.
9908 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009909 }
Erik Kline99f301b2017-02-15 19:59:17 +09009910
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009911 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009912 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009913 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9914 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9915 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009916 }
9917
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009918 // Notify the requests on this NAI that the network is now lingered.
9919 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009920 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009921 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9922 }
9923
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009924 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9925 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9926 return vpnBlocked
9927 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9928 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9929 }
9930
9931 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9932 if (blockedReasons == BLOCKED_REASON_NONE) {
9933 mUidBlockedReasons.delete(uid);
9934 } else {
9935 mUidBlockedReasons.put(uid, blockedReasons);
9936 }
9937 }
9938
junyulaif2c67e42018-08-07 19:50:45 +08009939 /**
9940 * Notify of the blocked state apps with a registered callback matching a given NAI.
9941 *
9942 * Unlike other callbacks, blocked status is different between each individual uid. So for
9943 * any given nai, all requests need to be considered according to the uid who filed it.
9944 *
9945 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009946 * @param oldMetered True if the previous network capabilities were metered.
9947 * @param newMetered True if the current network capabilities are metered.
9948 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9949 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009950 */
9951 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009952 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9953 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009954
9955 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9956 NetworkRequest nr = nai.requestAt(i);
9957 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009958
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009959 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9960 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9961 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009962 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009963 : oldVpnBlocked;
9964
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009965 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9966 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9967 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009968 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009969 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009970 }
9971 }
9972 }
9973
9974 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009975 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009976 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009977 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009978 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009979 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009980 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009981 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009982 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009983
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009984 final int oldBlockedState = getBlockedState(
9985 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9986 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9987 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009988 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009989 }
junyulaif2c67e42018-08-07 19:50:45 +08009990 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9991 NetworkRequest nr = nai.requestAt(i);
9992 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009993 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009994 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9995 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009996 }
9997 }
9998 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009999 }
10000
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010001 @VisibleForTesting
10002 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010003 // The NetworkInfo we actually send out has no bearing on the real
10004 // state of affairs. For example, if the default connection is mobile,
10005 // and a request for HIPRI has just gone away, we need to pretend that
10006 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10007 // the state to DISCONNECTED, even though the network is of type MOBILE
10008 // and is still connected.
10009 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10010 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010011 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010012 if (state != DetailedState.DISCONNECTED) {
10013 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010014 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010015 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010016 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010017 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10018 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10019 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10020 if (info.isFailover()) {
10021 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10022 nai.networkInfo.setFailover(false);
10023 }
10024 if (info.getReason() != null) {
10025 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10026 }
10027 if (info.getExtraInfo() != null) {
10028 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10029 }
10030 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010031 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010032 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010033 if (newDefaultAgent != null) {
10034 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10035 newDefaultAgent.networkInfo);
10036 } else {
10037 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10038 }
10039 }
10040 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10041 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010042 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010043 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010044 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010045 }
10046 }
10047 }
10048
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010049 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010050 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010051 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010052 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010053 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010054 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10055 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010056 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10057 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010058 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010059 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010060 } else {
10061 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10062 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010063 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010064 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010065
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010066 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10067 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10068 }
10069
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010070 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010071 * Returns the list of all interfaces that could be used by network traffic that does not
10072 * explicitly specify a network. This includes the default network, but also all VPNs that are
10073 * currently connected.
10074 *
10075 * Must be called on the handler thread.
10076 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010077 @NonNull
10078 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010079 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010080 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010081 final Set<Integer> activeNetIds = new ArraySet<>();
10082 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10083 if (nri.isBeingSatisfied()) {
10084 activeNetIds.add(nri.getSatisfier().network().netId);
10085 }
10086 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010087 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010088 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010089 defaultNetworks.add(nai.network);
10090 }
10091 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010092 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010093 }
10094
10095 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010096 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10097 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010098 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010099 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010100 ensureRunningOnConnectivityServiceThread();
10101 String activeIface = null;
10102 LinkProperties activeLinkProperties = getActiveLinkProperties();
10103 if (activeLinkProperties != null) {
10104 activeIface = activeLinkProperties.getInterfaceName();
10105 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010106
junyulai2050bed2021-01-23 09:46:34 +080010107 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010108 try {
junyulaide41fc22021-01-22 22:46:01 +080010109 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010110 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010111 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10112 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010113 } catch (Exception ignored) {
10114 }
10115 }
10116
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010117 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010118 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010119 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010120 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010121 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010122
10123 if (!TextUtils.isEmpty(settingUrl)) {
10124 return settingUrl;
10125 }
10126
10127 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010128 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010129 if (!TextUtils.isEmpty(settingUrl)) {
10130 return settingUrl;
10131 }
10132
10133 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010134 }
10135
10136 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010137 public void startNattKeepalive(Network network, int intervalSeconds,
10138 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010139 enforceKeepalivePermission();
10140 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010141 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010142 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10143 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010144 // false and set the underpinned network to null because there is no way and no
10145 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10146 // deprecated method.
10147 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010148 }
10149
10150 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010151 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010152 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010153 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010154 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010155 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010156 mKeepaliveTracker.startNattKeepalive(
10157 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010158 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10159 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010160 } finally {
10161 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10162 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010163 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10164 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010165 }
10166 }
junyulaid05a1922019-01-15 11:32:44 +080010167 }
10168
10169 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010170 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010171 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010172 try {
10173 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010174 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010175 mKeepaliveTracker.startTcpKeepalive(
10176 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10177 } finally {
10178 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10179 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010180 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10181 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010182 }
10183 }
junyulai0835a1e2019-01-08 20:04:33 +080010184 }
10185
10186 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010187 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010188 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010189 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10190 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010191 }
10192
10193 @Override
Remi NGUYEN VAN6ca02962023-02-20 20:10:09 +090010194 public int[] getSupportedKeepalives() {
10195 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10196 // Backwards compatibility with CTS 13
10197 android.Manifest.permission.QUERY_ALL_PACKAGES);
10198
10199 return BinderUtils.withCleanCallingIdentity(() ->
10200 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10201 }
10202
10203 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010204 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010205 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010206
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010207 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010208 final long token = Binder.clearCallingIdentity();
10209 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010210 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10211 UserHandle.getUserHandleForUid(uid))) {
10212 return;
10213 }
10214
Heemin Seogdb8489d2019-06-12 09:21:44 -070010215 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10216 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010217
10218 // Turn airplane mode off
10219 setAirplaneMode(false);
10220
10221 // restore private DNS settings to default mode (opportunistic)
10222 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10223 UserHandle.getUserHandleForUid(uid))) {
10224 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10225 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10226 }
10227
10228 Settings.Global.putString(mContext.getContentResolver(),
10229 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010230 } finally {
10231 Binder.restoreCallingIdentity(token);
10232 }
Stuart Scottd5463642015-04-02 18:00:02 -070010233 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010234
Ricky Wai7097cc92018-01-23 04:09:45 +000010235 @Override
10236 public byte[] getNetworkWatchlistConfigHash() {
10237 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10238 if (nwm == null) {
10239 loge("Unable to get NetworkWatchlistManager");
10240 return null;
10241 }
10242 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10243 return nwm.getWatchlistConfigHash();
10244 }
10245
Hugo Benichibe0c7652016-05-31 16:28:06 +090010246 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010247 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010248 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010249 }
Hugo Benichif4210292017-04-21 15:07:12 +090010250
10251 private static boolean toBool(int encodedBoolean) {
10252 return encodedBoolean != 0; // Only 0 means false.
10253 }
10254
10255 private static int encodeBool(boolean b) {
10256 return b ? 1 : 0;
10257 }
mswest4632928412018-03-12 10:34:34 -070010258
10259 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010260 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10261 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10262 @NonNull String[] args) {
10263 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10264 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010265 }
10266
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010267 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010268 @Override
10269 public int onCommand(String cmd) {
10270 if (cmd == null) {
10271 return handleDefaultCommands(cmd);
10272 }
10273 final PrintWriter pw = getOutPrintWriter();
10274 try {
10275 switch (cmd) {
10276 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010277 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
10278 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070010279 final String action = getNextArg();
10280 if ("enable".equals(action)) {
10281 setAirplaneMode(true);
10282 return 0;
10283 } else if ("disable".equals(action)) {
10284 setAirplaneMode(false);
10285 return 0;
10286 } else if (action == null) {
10287 final ContentResolver cr = mContext.getContentResolver();
10288 final int enabled = Settings.Global.getInt(cr,
10289 Settings.Global.AIRPLANE_MODE_ON);
10290 pw.println(enabled == 0 ? "disabled" : "enabled");
10291 return 0;
10292 } else {
10293 onHelp();
10294 return -1;
10295 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010296 case "reevaluate":
10297 // Usage : adb shell cmd connectivity reevaluate <netId>
10298 // If netId is omitted, then reevaluate the default network
10299 final String netId = getNextArg();
10300 final NetworkAgentInfo nai;
10301 if (null == netId) {
10302 // Note that the command is running on the wrong thread to call this,
10303 // so this could in principle return stale data. But it can't crash.
10304 nai = getDefaultNetwork();
10305 } else {
10306 // If netId can't be parsed, this throws NumberFormatException, which
10307 // is passed back to adb who prints it.
10308 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10309 }
10310 if (null == nai) {
10311 pw.println("Unknown network (net ID not found or no default network)");
10312 return 0;
10313 }
10314 Log.d(TAG, "Reevaluating network " + nai.network);
10315 reportNetworkConnectivity(nai.network, !nai.isValidated());
10316 return 0;
mswest4632928412018-03-12 10:34:34 -070010317 default:
10318 return handleDefaultCommands(cmd);
10319 }
10320 } catch (Exception e) {
10321 pw.println(e);
10322 }
10323 return -1;
10324 }
10325
10326 @Override
10327 public void onHelp() {
10328 PrintWriter pw = getOutPrintWriter();
10329 pw.println("Connectivity service commands:");
10330 pw.println(" help");
10331 pw.println(" Print this help text.");
10332 pw.println(" airplane-mode [enable|disable]");
10333 pw.println(" Turn airplane mode on or off.");
10334 pw.println(" airplane-mode");
10335 pw.println(" Get airplane mode.");
10336 }
10337 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010338
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010339 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010340 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10341 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10342 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010343 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010344 }
10345
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010346 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10347 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010348 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10349 final TransportInfo newInfo = nc.getTransportInfo();
10350 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10351 return;
10352 }
10353 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010354 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010355 }
10356 }
10357
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010358 /**
10359 * @param connectionInfo the connection to resolve.
10360 * @return {@code uid} if the connection is found and the app has permission to observe it
10361 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10362 * connection is not found.
10363 */
10364 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010365 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10366 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10367 }
10368
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010369 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010370 connectionInfo.local, connectionInfo.remote);
10371
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010372 if (uid == INVALID_UID) return uid; // Not found.
10373
10374 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10375 // VPN, if any, that applies to the UID that owns the connection.
10376 if (checkNetworkStackPermission()) return uid;
10377
10378 final NetworkAgentInfo vpn = getVpnForUid(uid);
10379 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010380 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010381 return INVALID_UID;
10382 }
10383
10384 return uid;
10385 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010386
Benedict Wong493e04b2018-11-09 14:45:34 -080010387 /**
10388 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10389 *
10390 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10391 */
10392 @Override
10393 public IBinder startOrGetTestNetworkService() {
10394 synchronized (mTNSLock) {
10395 TestNetworkService.enforceTestNetworkPermissions(mContext);
10396
10397 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010398 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010399 }
10400
10401 return mTNS;
10402 }
10403 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010404
Cody Kesting73708bf2019-12-18 10:57:50 -080010405 /**
10406 * Handler used for managing all Connectivity Diagnostics related functions.
10407 *
10408 * @see android.net.ConnectivityDiagnosticsManager
10409 *
10410 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10411 */
10412 @VisibleForTesting
10413 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010414 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10415
Cody Kesting73708bf2019-12-18 10:57:50 -080010416 /**
10417 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10418 * android.net.ConnectivityDiagnosticsManager}.
10419 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10420 * NetworkRequestInfo to be registered
10421 */
10422 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10423
10424 /**
10425 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10426 * android.net.ConnectivityDiagnosticsManager}.
10427 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10428 * arg1 = the uid of the caller
10429 */
10430 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10431
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010432 /**
10433 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010434 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010435 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10436 * NetworkMonitor.
10437 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010438 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010439 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010440
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010441 /**
10442 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10443 * been detected on the network.
10444 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10445 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10446 * arg2 = NetID.
10447 * data = PersistableBundle of extras passed from NetworkMonitor.
10448 */
10449 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10450
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010451 /**
10452 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10453 * the platform. This event will invoke {@link
10454 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10455 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070010456 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010457 */
10458 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
10459
Cody Kesting73708bf2019-12-18 10:57:50 -080010460 private ConnectivityDiagnosticsHandler(Looper looper) {
10461 super(looper);
10462 }
10463
10464 @Override
10465 public void handleMessage(Message msg) {
10466 switch (msg.what) {
10467 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10468 handleRegisterConnectivityDiagnosticsCallback(
10469 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
10470 break;
10471 }
10472 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10473 handleUnregisterConnectivityDiagnosticsCallback(
10474 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
10475 break;
10476 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010477 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010478 final ConnectivityReportEvent reportEvent =
10479 (ConnectivityReportEvent) msg.obj;
10480
Aaron Huang959d3642021-01-21 15:47:41 +080010481 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010482 break;
10483 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010484 case EVENT_DATA_STALL_SUSPECTED: {
10485 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080010486 final Pair<Long, PersistableBundle> arg =
10487 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010488 if (nai == null) break;
10489
Aaron Huang959d3642021-01-21 15:47:41 +080010490 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010491 break;
10492 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010493 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070010494 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010495 break;
10496 }
10497 default: {
10498 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
10499 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010500 }
10501 }
10502 }
10503
10504 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
10505 @VisibleForTesting
10506 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
10507 @NonNull private final IConnectivityDiagnosticsCallback mCb;
10508 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010509 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010510
10511 @VisibleForTesting
10512 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010513 @NonNull IConnectivityDiagnosticsCallback cb,
10514 @NonNull NetworkRequestInfo nri,
10515 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010516 mCb = cb;
10517 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010518 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010519 }
10520
10521 @Override
10522 public void binderDied() {
10523 log("ConnectivityDiagnosticsCallback IBinder died.");
10524 unregisterConnectivityDiagnosticsCallback(mCb);
10525 }
10526 }
10527
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010528 /**
10529 * Class used for sending information from {@link
10530 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
10531 */
10532 private static class NetworkTestedResults {
10533 private final int mNetId;
10534 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010535 @Nullable private final String mRedirectUrl;
10536
10537 private NetworkTestedResults(
10538 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
10539 mNetId = netId;
10540 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010541 mRedirectUrl = redirectUrl;
10542 }
10543 }
10544
10545 /**
10546 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
10547 * ConnectivityDiagnosticsHandler}.
10548 */
10549 private static class ConnectivityReportEvent {
10550 private final long mTimestampMillis;
10551 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080010552 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010553
Aaron Huang959d3642021-01-21 15:47:41 +080010554 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
10555 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010556 mTimestampMillis = timestampMillis;
10557 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080010558 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010559 }
10560 }
10561
Cody Kestingf1120be2020-08-03 18:01:40 -070010562 /**
10563 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
10564 * ConnectivityDiagnosticsHandler}.
10565 */
10566 private static class ReportedNetworkConnectivityInfo {
10567 public final boolean hasConnectivity;
10568 public final boolean isNetworkRevalidating;
10569 public final int reporterUid;
10570 @NonNull public final NetworkAgentInfo nai;
10571
10572 private ReportedNetworkConnectivityInfo(
10573 boolean hasConnectivity,
10574 boolean isNetworkRevalidating,
10575 int reporterUid,
10576 @NonNull NetworkAgentInfo nai) {
10577 this.hasConnectivity = hasConnectivity;
10578 this.isNetworkRevalidating = isNetworkRevalidating;
10579 this.reporterUid = reporterUid;
10580 this.nai = nai;
10581 }
10582 }
10583
Cody Kesting73708bf2019-12-18 10:57:50 -080010584 private void handleRegisterConnectivityDiagnosticsCallback(
10585 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
10586 ensureRunningOnConnectivityServiceThread();
10587
10588 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080010589 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010590 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
10591
James Mattis64b8b0f2020-11-24 17:40:49 -080010592 // Connectivity Diagnostics are meant to be used with a single network request. It would be
10593 // confusing for these networks to change when an NRI is satisfied in another layer.
10594 if (nri.isMultilayerRequest()) {
10595 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
10596 + "network requests.");
10597 }
10598
Cody Kesting73708bf2019-12-18 10:57:50 -080010599 // This means that the client registered the same callback multiple times. Do
10600 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080010601 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010602 if (VDBG) log("Diagnostics callback is already registered");
10603
10604 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10605 // incremented when the NetworkRequestInfo is created as part of
10606 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010607 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080010608 return;
10609 }
10610
Cody Kesting31f1ff62020-03-05 10:46:02 -080010611 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080010612
10613 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080010614 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010615 } catch (RemoteException e) {
10616 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080010617 return;
10618 }
10619
10620 // Once registered, provide ConnectivityReports for matching Networks
10621 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
10622 synchronized (mNetworkForNetId) {
10623 for (int i = 0; i < mNetworkForNetId.size(); i++) {
10624 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080010625 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
10626 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080010627 matchingNetworks.add(nai);
10628 }
10629 }
10630 }
10631 for (final NetworkAgentInfo nai : matchingNetworks) {
10632 final ConnectivityReport report = nai.getConnectivityReport();
10633 if (report == null) {
10634 continue;
10635 }
10636 if (!checkConnectivityDiagnosticsPermissions(
10637 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10638 continue;
10639 }
10640
10641 try {
10642 cb.onConnectivityReportAvailable(report);
10643 } catch (RemoteException e) {
10644 // Exception while sending the ConnectivityReport. Move on to the next network.
10645 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010646 }
10647 }
10648
10649 private void handleUnregisterConnectivityDiagnosticsCallback(
10650 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
10651 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010652 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010653
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010654 final ConnectivityDiagnosticsCallbackInfo cbInfo =
10655 mConnectivityDiagnosticsCallbacks.remove(iCb);
10656 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010657 if (VDBG) log("Removing diagnostics callback that is not currently registered");
10658 return;
10659 }
10660
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010661 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080010662
Cody Kesting70fa2b22020-12-02 12:16:56 -080010663 // Caller's UID must either be the registrants (if they are unregistering) or the System's
10664 // (if the Binder died)
10665 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
10666 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080010667 return;
10668 }
10669
Cody Kesting46cb1672020-03-04 13:35:20 -080010670 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10671 // incremented when the NetworkRequestInfo is created as part of
10672 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010673 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080010674
Cody Kesting31f1ff62020-03-05 10:46:02 -080010675 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010676 }
10677
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010678 private void handleNetworkTestedWithExtras(
10679 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
10680 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080010681 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010682 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010683 final ConnectivityReport report =
10684 new ConnectivityReport(
10685 reportEvent.mNai.network,
10686 reportEvent.mTimestampMillis,
10687 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010688 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010689 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080010690 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070010691
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010692 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010693 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010694 for (final IConnectivityDiagnosticsCallback cb : results) {
10695 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080010696 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010697 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070010698 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010699 }
10700 }
10701 }
10702
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010703 private void handleDataStallSuspected(
10704 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
10705 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080010706 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010707 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010708 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080010709 new DataStallReport(
10710 nai.network,
10711 timestampMillis,
10712 detectionMethod,
10713 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010714 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080010715 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010716 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010717 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010718 for (final IConnectivityDiagnosticsCallback cb : results) {
10719 try {
10720 cb.onDataStallSuspected(report);
10721 } catch (RemoteException ex) {
10722 loge("Error invoking onDataStallSuspected", ex);
10723 }
10724 }
10725 }
10726
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010727 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070010728 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
10729 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
10730 final ConnectivityReport cachedReport = nai.getConnectivityReport();
10731
10732 // If the Network is being re-validated as a result of this call to
10733 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
10734 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010735 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010736 getMatchingPermissionedCallbacks(
10737 nai,
10738 reportedNetworkConnectivityInfo.isNetworkRevalidating
10739 ? Process.INVALID_UID
10740 : reportedNetworkConnectivityInfo.reporterUid);
10741
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010742 for (final IConnectivityDiagnosticsCallback cb : results) {
10743 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070010744 cb.onNetworkConnectivityReported(
10745 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010746 } catch (RemoteException ex) {
10747 loge("Error invoking onNetworkConnectivityReported", ex);
10748 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010749
10750 // If the Network isn't re-validating, also provide the cached report. If there is no
10751 // cached report, the Network is still being validated and a report will be sent once
10752 // validation is complete. Note that networks which never undergo validation will still
10753 // have a cached ConnectivityReport with RESULT_SKIPPED.
10754 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
10755 try {
10756 cb.onConnectivityReportAvailable(cachedReport);
10757 } catch (RemoteException ex) {
10758 loge("Error invoking onConnectivityReportAvailable", ex);
10759 }
10760 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010761 }
10762 }
10763
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010764 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090010765 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
10766 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010767 sanitized.setUids(null);
10768 sanitized.setAdministratorUids(new int[0]);
10769 sanitized.setOwnerUid(Process.INVALID_UID);
10770 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080010771 }
10772
Cody Kestingf1120be2020-08-03 18:01:40 -070010773 /**
10774 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
10775 *
10776 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
10777 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010778 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070010779 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010780 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010781 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010782 mConnectivityDiagnosticsCallbacks.entrySet()) {
10783 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
10784 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070010785
James Mattis64b8b0f2020-11-24 17:40:49 -080010786 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070010787 if (!nai.satisfies(nri.mRequests.get(0))) {
10788 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010789 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010790
10791 // UID for this callback must either be:
10792 // - INVALID_UID (which sends callbacks to all UIDs), or
10793 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
10794 // notified as a result)
10795 if (uid != Process.INVALID_UID && uid != nri.mUid) {
10796 continue;
10797 }
10798
10799 if (!checkConnectivityDiagnosticsPermissions(
10800 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10801 continue;
10802 }
10803
10804 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010805 }
10806 return results;
10807 }
10808
Cody Kesting7474f672021-05-11 14:22:40 -070010809 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
10810 @NonNull NetworkAgentInfo nai) {
10811 // TODO(b/188483916): replace with a transport-agnostic location-aware check
10812 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
10813 }
10814
Cody Kesting160ef392021-05-05 13:17:22 -070010815 private boolean hasLocationPermission(String packageName, int uid) {
10816 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
10817 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
10818 // call in a try-catch.
10819 try {
10820 if (!mLocationPermissionChecker.checkLocationPermission(
10821 packageName, null /* featureId */, uid, null /* message */)) {
10822 return false;
10823 }
10824 } catch (SecurityException e) {
10825 return false;
10826 }
10827
10828 return true;
10829 }
10830
10831 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
10832 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090010833 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070010834 && virtual.networkCapabilities.getOwnerUid() == uid
10835 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
10836 return true;
10837 }
10838 }
10839
10840 return false;
10841 }
10842
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010843 @VisibleForTesting
10844 boolean checkConnectivityDiagnosticsPermissions(
10845 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
10846 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
10847 return true;
10848 }
10849
Cody Kesting160ef392021-05-05 13:17:22 -070010850 // Administrator UIDs also contains the Owner UID
10851 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10852 if (!CollectionUtils.contains(administratorUids, callbackUid)
10853 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010854 return false;
10855 }
10856
Cody Kesting7474f672021-05-11 14:22:40 -070010857 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10858 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010859 }
10860
Cody Kestingd199a9d2019-12-17 12:55:28 -080010861 @Override
10862 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010863 @NonNull IConnectivityDiagnosticsCallback callback,
10864 @NonNull NetworkRequest request,
10865 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010866 Objects.requireNonNull(callback, "callback must not be null");
10867 Objects.requireNonNull(request, "request must not be null");
10868 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10869
Cody Kesting73708bf2019-12-18 10:57:50 -080010870 if (request.legacyType != TYPE_NONE) {
10871 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10872 + " Please use NetworkCapabilities instead.");
10873 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010874 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010875 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010876
10877 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10878 // and administrator uids to be safe.
10879 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010880 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010881
10882 final NetworkRequest requestWithId =
10883 new NetworkRequest(
10884 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10885
10886 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10887 //
10888 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10889 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10890 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010891 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010892 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010893 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010894
10895 mConnectivityDiagnosticsHandler.sendMessage(
10896 mConnectivityDiagnosticsHandler.obtainMessage(
10897 ConnectivityDiagnosticsHandler
10898 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10899 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010900 }
10901
10902 @Override
10903 public void unregisterConnectivityDiagnosticsCallback(
10904 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010905 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010906 mConnectivityDiagnosticsHandler.sendMessage(
10907 mConnectivityDiagnosticsHandler.obtainMessage(
10908 ConnectivityDiagnosticsHandler
10909 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010910 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010911 0,
10912 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010913 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010914
Yan Yanfe96dde2022-12-05 23:00:01 +000010915 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
10916 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
10917 if (underlyingNetworks == null) return false;
10918
10919 for (Network network : underlyingNetworks) {
10920 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
10921 return true;
10922 }
10923 }
10924 return false;
10925 }
10926
Cody Kestingf53a0752020-04-15 12:33:28 -070010927 @Override
10928 public void simulateDataStall(int detectionMethod, long timestampMillis,
10929 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010930 Objects.requireNonNull(network, "network must not be null");
10931 Objects.requireNonNull(extras, "extras must not be null");
10932
paulhu3ffffe72021-09-16 10:15:22 +080010933 enforceAnyPermissionOf(mContext,
10934 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070010935 android.Manifest.permission.NETWORK_STACK);
10936 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000010937 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
10938 throw new SecurityException(
10939 "Data Stall simulation is only possible for test networks or networks built on"
10940 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010941 }
10942
10943 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000010944 if (nai == null
10945 || (nai.creatorUid != mDeps.getCallingUid()
10946 && nai.creatorUid != Process.SYSTEM_UID)) {
10947 throw new SecurityException(
10948 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070010949 }
10950
Cody Kesting652e3ec2020-05-21 12:08:21 -070010951 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10952 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10953 // Data Stall information as a DataStallReportParcelable and passing to
10954 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10955 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010956 final DataStallReportParcelable p = new DataStallReportParcelable();
10957 p.timestampMillis = timestampMillis;
10958 p.detectionMethod = detectionMethod;
10959
10960 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10961 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10962 }
10963 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10964 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10965 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10966 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10967 }
10968
Serik Beketayevec8ad212020-12-07 22:43:07 -080010969 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010970 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010971
lucaslin66f44212021-02-23 01:12:55 +080010972 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10973 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010974 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010975 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010976 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010977 }
lucaslin37a16d92021-01-21 19:48:09 +080010978
10979 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010980 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010981 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010982 nai.clatd.interfaceLinkStateChanged(iface, up);
10983 }
10984 }
10985
10986 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010987 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010988 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010989 nai.clatd.interfaceRemoved(iface);
10990 }
lucaslin66f44212021-02-23 01:12:55 +080010991 }
10992 }
10993
lucaslin1a8b4c62021-01-21 02:02:55 +080010994 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
10995
10996 /**
10997 * Class used for updating network activity tracking with netd and notify network activity
10998 * changes.
10999 */
11000 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011001 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011002 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011003 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080011004 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11005 new RemoteCallbackList<>();
11006 // Indicate the current system default network activity is active or not.
11007 @GuardedBy("mActiveIdleTimers")
11008 private boolean mNetworkActive;
11009 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090011010 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080011011 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080011012
Chalard Jean46bfbf02022-02-02 00:56:25 +090011013 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011014 public final int timeout;
11015 public final int transportType;
11016
11017 IdleTimerParams(int timeout, int transport) {
11018 this.timeout = timeout;
11019 this.transportType = transport;
11020 }
11021 }
11022
11023 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080011024 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011025 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011026 mNetd = netd;
11027 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080011028 }
11029
lucaslin66f44212021-02-23 01:12:55 +080011030 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
11031 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
11032 synchronized (mActiveIdleTimers) {
11033 mNetworkActive = active;
11034 // If there are no idle timers, it means that system is not monitoring
11035 // activity, so the system default network for those default network
11036 // unspecified apps is always considered active.
11037 //
11038 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
11039 // any network activity change event. Whenever this event is received,
11040 // the mActiveIdleTimers should be always not empty. The legacy behavior
11041 // is no-op. Remove to refer to mNetworkActive only.
11042 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
11043 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
11044 }
11045 }
11046 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011047
lucaslin1193a5d2021-01-21 02:04:15 +080011048 // The network activity should only be updated from ConnectivityService handler thread
11049 // when mActiveIdleTimers lock is held.
11050 @GuardedBy("mActiveIdleTimers")
11051 private void reportNetworkActive() {
11052 final int length = mNetworkActivityListeners.beginBroadcast();
11053 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
11054 try {
11055 for (int i = 0; i < length; i++) {
11056 try {
11057 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
11058 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011059 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080011060 }
11061 }
11062 } finally {
11063 mNetworkActivityListeners.finishBroadcast();
11064 }
11065 }
11066
11067 @GuardedBy("mActiveIdleTimers")
11068 public void handleReportNetworkActivity() {
11069 synchronized (mActiveIdleTimers) {
11070 reportNetworkActive();
11071 }
11072 }
11073
lucaslin1a8b4c62021-01-21 02:02:55 +080011074 // This is deprecated and only to support legacy use cases.
11075 private int transportTypeToLegacyType(int type) {
11076 switch (type) {
11077 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011078 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080011079 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011080 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080011081 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011082 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080011083 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011084 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080011085 default:
11086 loge("Unexpected transport in transportTypeToLegacyType: " + type);
11087 }
11088 return ConnectivityManager.TYPE_NONE;
11089 }
11090
11091 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
11092 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
11093 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
11094 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
11095 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
11096 final long ident = Binder.clearCallingIdentity();
11097 try {
11098 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
11099 RECEIVE_DATA_ACTIVITY_CHANGE,
11100 null /* resultReceiver */,
11101 null /* scheduler */,
11102 0 /* initialCode */,
11103 null /* initialData */,
11104 null /* initialExtra */);
11105 } finally {
11106 Binder.restoreCallingIdentity(ident);
11107 }
11108 }
11109
11110 /**
11111 * Setup data activity tracking for the given network.
11112 *
11113 * Every {@code setupDataActivityTracking} should be paired with a
11114 * {@link #removeDataActivityTracking} for cleanup.
11115 */
11116 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
11117 final String iface = networkAgent.linkProperties.getInterfaceName();
11118
11119 final int timeout;
11120 final int type;
11121
11122 if (networkAgent.networkCapabilities.hasTransport(
11123 NetworkCapabilities.TRANSPORT_CELLULAR)) {
11124 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011125 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080011126 10);
11127 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11128 } else if (networkAgent.networkCapabilities.hasTransport(
11129 NetworkCapabilities.TRANSPORT_WIFI)) {
11130 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011131 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080011132 15);
11133 type = NetworkCapabilities.TRANSPORT_WIFI;
11134 } else {
11135 return; // do not track any other networks
11136 }
11137
lucaslinb961efc2021-01-21 02:03:17 +080011138 updateRadioPowerState(true /* isActive */, type);
11139
lucaslin1a8b4c62021-01-21 02:02:55 +080011140 if (timeout > 0 && iface != null) {
11141 try {
lucaslin1193a5d2021-01-21 02:04:15 +080011142 synchronized (mActiveIdleTimers) {
11143 // Networks start up.
11144 mNetworkActive = true;
11145 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
11146 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
11147 reportNetworkActive();
11148 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011149 } catch (Exception e) {
11150 // You shall not crash!
11151 loge("Exception in setupDataActivityTracking " + e);
11152 }
11153 }
11154 }
11155
11156 /**
11157 * Remove data activity tracking when network disconnects.
11158 */
11159 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
11160 final String iface = networkAgent.linkProperties.getInterfaceName();
11161 final NetworkCapabilities caps = networkAgent.networkCapabilities;
11162
lucaslinb961efc2021-01-21 02:03:17 +080011163 if (iface == null) return;
11164
11165 final int type;
11166 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
11167 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11168 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
11169 type = NetworkCapabilities.TRANSPORT_WIFI;
11170 } else {
11171 return; // do not track any other networks
11172 }
11173
11174 try {
11175 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080011176 synchronized (mActiveIdleTimers) {
11177 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
11178 // The call fails silently if no idle timer setup for this interface
11179 mNetd.idletimerRemoveInterface(iface, params.timeout,
11180 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080011181 }
lucaslinb961efc2021-01-21 02:03:17 +080011182 } catch (Exception e) {
11183 // You shall not crash!
11184 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080011185 }
11186 }
11187
11188 /**
11189 * Update data activity tracking when network state is updated.
11190 */
11191 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
11192 NetworkAgentInfo oldNetwork) {
11193 if (newNetwork != null) {
11194 setupDataActivityTracking(newNetwork);
11195 }
11196 if (oldNetwork != null) {
11197 removeDataActivityTracking(oldNetwork);
11198 }
11199 }
lucaslinb961efc2021-01-21 02:03:17 +080011200
11201 private void updateRadioPowerState(boolean isActive, int transportType) {
11202 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
11203 switch (transportType) {
11204 case NetworkCapabilities.TRANSPORT_CELLULAR:
11205 bs.reportMobileRadioPowerState(isActive, NO_UID);
11206 break;
11207 case NetworkCapabilities.TRANSPORT_WIFI:
11208 bs.reportWifiRadioPowerState(isActive, NO_UID);
11209 break;
11210 default:
11211 logw("Untracked transport type:" + transportType);
11212 }
11213 }
lucaslin1193a5d2021-01-21 02:04:15 +080011214
11215 public boolean isDefaultNetworkActive() {
11216 synchronized (mActiveIdleTimers) {
11217 // If there are no idle timers, it means that system is not monitoring activity,
11218 // so the default network is always considered active.
11219 //
11220 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
11221 // tracking is disabled (negative idle timer value configured), or no active default
11222 // network. In the latter case, this reports active but it should report inactive.
11223 return mNetworkActive || mActiveIdleTimers.isEmpty();
11224 }
11225 }
11226
11227 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
11228 mNetworkActivityListeners.register(l);
11229 }
11230
11231 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
11232 mNetworkActivityListeners.unregister(l);
11233 }
lucaslin012f7a12021-01-21 02:04:35 +080011234
11235 public void dump(IndentingPrintWriter pw) {
11236 synchronized (mActiveIdleTimers) {
11237 pw.print("mNetworkActive="); pw.println(mNetworkActive);
11238 pw.println("Idle timers:");
11239 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
11240 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
11241 final IdleTimerParams params = ent.getValue();
11242 pw.print(" timeout="); pw.print(params.timeout);
11243 pw.print(" type="); pw.println(params.transportType);
11244 }
11245 }
11246 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011247 }
James Mattis47db0582021-01-01 14:13:35 -080011248
Daniel Brightf9e945b2020-06-15 16:10:01 -070011249 /**
11250 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
11251 *
11252 * @param socketInfo the socket information
11253 * @param callback the callback to register
11254 */
11255 @Override
11256 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
11257 @NonNull final IQosCallback callback) {
11258 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
11259 if (nai == null || nai.networkCapabilities == null) {
11260 try {
11261 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
11262 } catch (final RemoteException ex) {
11263 loge("registerQosCallbackInternal: RemoteException", ex);
11264 }
11265 return;
11266 }
11267 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
11268 }
11269
11270 /**
11271 * Register a {@link IQosCallback} with base {@link QosFilter}.
11272 *
11273 * @param filter the filter to register
11274 * @param callback the callback to register
11275 * @param nai the agent information related to the filter's network
11276 */
11277 @VisibleForTesting
11278 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
11279 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011280 Objects.requireNonNull(filter, "filter must be non-null");
11281 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011282
11283 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080011284 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
11285 // on this network is unregistered when the app loses permission or b) no QoS
11286 // callbacks are sent for restricted networks unless the app currently has permission
11287 // to access restricted networks.
11288 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070011289 }
11290 mQosCallbackTracker.registerCallback(callback, filter, nai);
11291 }
11292
11293 /**
11294 * Unregisters the given callback.
11295 *
11296 * @param callback the callback to unregister
11297 */
11298 @Override
11299 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011300 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011301 mQosCallbackTracker.unregisterCallback(callback);
11302 }
James Mattis47db0582021-01-01 14:13:35 -080011303
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011304 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
11305 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
11306 // Enterprise device can be fully managed like device owner and such use case
11307 // also should be supported. Calling app check for work profile and fully managed device
11308 // is already done in DevicePolicyManager.
11309 // This check is an extra caution to be sure device is fully managed or not.
11310 final UserManager um = mContext.getSystemService(UserManager.class);
11311 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
11312 if (um.isManagedProfile(profile.getIdentifier())) {
11313 return true;
11314 }
11315 if (SdkLevel.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
11316 return false;
11317 }
11318
James Mattis45d81842021-01-10 14:24:24 -080011319 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011320 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011321 *
11322 * See the documentation for the individual preferences for a description of the supported
11323 * behaviors.
11324 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011325 * @param profile If the device owner is set, any profile is allowed.
11326 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011327 * @param preferences the list of profile network preferences for the
11328 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011329 * @param listener an optional listener to listen for completion of the operation.
11330 */
11331 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011332 public void setProfileNetworkPreferences(
11333 @NonNull final UserHandle profile,
11334 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090011335 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011336 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011337 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011338
11339 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011340 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11341 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11342 .build();
11343 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011344 }
11345
paulhu3ffffe72021-09-16 10:15:22 +080011346 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011347 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011348 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011349 }
11350 if (profile.getIdentifier() < 0) {
11351 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11352 + "UserHandle.CURRENT not supported)");
11353 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011354 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11355 throw new IllegalArgumentException("Profile must be a managed profile "
11356 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011357 }
paulhuaa0743d2021-05-26 21:56:03 +080011358
Chalard Jean0606fc82022-12-14 20:34:43 +090011359 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011360 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011361 for (final ProfileNetworkPreference preference : preferences) {
11362 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011363 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011364 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011365 switch (preference.getPreference()) {
11366 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11367 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011368 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011369 if (preference.getPreferenceEnterpriseId() != 0) {
11370 throw new IllegalArgumentException(
11371 "Invalid enterprise identifier in setProfileNetworkPreferences");
11372 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011373 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011374 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11375 blockingNonEnterprise = true;
11376 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011377 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11378 allowFallback = false;
11379 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011380 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011381 // This code is needed even though there is a check later on,
11382 // because isRangeAlreadyInPreferenceList assumes that every preference
11383 // has a UID list.
11384 if (hasDefaultPreference) {
11385 throw new IllegalArgumentException(
11386 "Default profile preference should not be set along with other "
11387 + "preference");
11388 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011389 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11390 throw new IllegalArgumentException(
11391 "Invalid enterprise identifier in setProfileNetworkPreferences");
11392 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011393 final Set<UidRange> uidRangeSet =
11394 getUidListToBeAppliedForNetworkPreference(profile, preference);
11395 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11396 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11397 } else {
11398 throw new IllegalArgumentException(
11399 "Overlapping uid range in setProfileNetworkPreferences");
11400 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011401 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011402 nc.addEnterpriseId(
11403 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011404 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11405 break;
11406 default:
11407 throw new IllegalArgumentException(
11408 "Invalid preference in setProfileNetworkPreferences");
11409 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011410 preferenceList.add(new ProfileNetworkPreferenceInfo(
11411 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011412 if (hasDefaultPreference && preferenceList.size() > 1) {
11413 throw new IllegalArgumentException(
11414 "Default profile preference should not be set along with other preference");
11415 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011416 }
11417 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011418 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011419 }
11420
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011421 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
11422 @NonNull final UserHandle profile,
11423 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
11424 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080011425 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
11426 profileNetworkPreference.getIncludedUids());
11427
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011428 if (uidRangeSet.size() > 0) {
11429 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
11430 throw new IllegalArgumentException(
11431 "Allow uid range is outside the uid range of profile.");
11432 }
11433 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080011434 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011435 profileNetworkPreference.getExcludedUids());
11436 if (disallowUidRangeSet.size() > 0) {
11437 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
11438 throw new IllegalArgumentException(
11439 "disallow uid range is outside the uid range of profile.");
11440 }
11441 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
11442 disallowUidRangeSet);
11443 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011444 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011445 uidRangeSet.add(profileUids);
11446 }
11447 }
11448 return uidRangeSet;
11449 }
11450
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011451 private boolean isEnterpriseIdentifierValid(
11452 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011453 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011454 return true;
11455 }
11456 return false;
11457 }
11458
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011459 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090011460 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011461 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090011462 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011463 // The NRI for a user should contain the request for capabilities.
11464 // If fallback to default network is needed then NRI should include
11465 // the request for the default network. Create an image of it to
11466 // have the correct UIDs in it (also a request can only be part of one NRI, because
11467 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011468 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
11469 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011470 if (pref.allowFallback) {
11471 nrs.add(createDefaultInternetRequestForTransport(
11472 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11473 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011474 if (VDBG) {
11475 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
11476 pref.capabilities.getUids()));
11477 }
11478
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011479 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080011480 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080011481 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011482 result.add(nri);
11483 }
11484 return result;
11485 }
11486
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011487 /**
11488 * Compare if the given UID range sets have the same UIDs.
11489 *
11490 */
11491 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090011492 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011493 @NonNull Set<UidRange> uidRangeSet) {
11494 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
11495 return false;
11496 }
Chalard Jean0606fc82022-12-14 20:34:43 +090011497 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011498 if (UidRangeUtils.doesRangeSetOverlap(
11499 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
11500 return true;
11501 }
11502 }
11503 return false;
11504 }
11505
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011506 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090011507 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011508 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011509 /*
11510 * handleSetProfileNetworkPreference is always called for single user.
11511 * preferenceList only contains preferences for different uids within the same user
11512 * (enforced by getUidListToBeAppliedForNetworkPreference).
11513 * Clear all the existing preferences for the user before applying new preferences.
11514 *
11515 */
Chalard Jean0606fc82022-12-14 20:34:43 +090011516 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
11517 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011518 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
11519 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011520
paulhu74128522021-09-28 02:29:03 +000011521 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
11522 addPerAppDefaultNetworkRequests(
11523 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080011524 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080011525
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011526 // Finally, rematch.
11527 rematchAllNetworksAndRequests();
11528
11529 if (null != listener) {
11530 try {
11531 listener.onComplete();
11532 } catch (RemoteException e) {
11533 loge("Listener for setProfileNetworkPreference has died");
11534 }
11535 }
11536 }
11537
paulhu51f77dc2021-06-07 02:34:20 +000011538 @VisibleForTesting
11539 @NonNull
11540 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
11541 @NonNull final Set<Integer> uids) {
11542 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11543 if (uids.size() == 0) {
11544 // Should not create NetworkRequestInfo if no preferences. Without uid range in
11545 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
11546 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
11547 return nris;
11548 }
11549
11550 final List<NetworkRequest> requests = new ArrayList<>();
11551 // The NRI should be comprised of two layers:
11552 // - The request for the mobile network preferred.
11553 // - The request for the default network, for fallback.
11554 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090011555 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000011556 requests.add(createDefaultInternetRequestForTransport(
11557 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11558 final Set<UidRange> ranges = new ArraySet<>();
11559 for (final int uid : uids) {
11560 ranges.add(new UidRange(uid, uid));
11561 }
11562 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080011563 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080011564 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000011565 return nris;
11566 }
11567
11568 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000011569 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000011570 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
11571 addPerAppDefaultNetworkRequests(
11572 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000011573 // Finally, rematch.
11574 rematchAllNetworksAndRequests();
11575 }
11576
Patrick Rohr2857ac42022-01-21 14:58:16 +010011577 private void handleIngressRateLimitChanged() {
11578 final long oldIngressRateLimit = mIngressRateLimit;
11579 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
11580 mContext);
11581 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
11582 if (canNetworkBeRateLimited(networkAgent)) {
11583 // If rate limit has previously been enabled, remove the old limit first.
11584 if (oldIngressRateLimit >= 0) {
11585 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
11586 }
11587 if (mIngressRateLimit >= 0) {
11588 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
11589 mIngressRateLimit);
11590 }
11591 }
11592 }
11593 }
11594
11595 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090011596 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
11597 if (!SdkLevel.isAtLeastT()) return false;
11598
Patrick Rohrff3b3f82022-02-09 15:15:52 +010011599 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
11600 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
11601 // internet connectivity can be rate limited.
11602 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
11603 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010011604 return false;
11605 }
11606
11607 final String iface = networkAgent.linkProperties.getInterfaceName();
11608 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010011609 // This may happen in tests, but if there is no interface then there is nothing that
11610 // can be rate limited.
11611 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010011612 return false;
11613 }
11614 return true;
11615 }
11616
James Mattis45d81842021-01-10 14:24:24 -080011617 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080011618 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
11619 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080011620 }
11621
11622 /**
11623 * Used by automotive devices to set the network preferences used to direct traffic at an
11624 * application level as per the given OemNetworkPreferences. An example use-case would be an
11625 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
11626 * vehicle via a particular network.
11627 *
11628 * Calling this will overwrite the existing preference.
11629 *
James Mattisda32cfe2021-01-26 16:23:52 -080011630 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090011631 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080011632 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080011633 */
James Mattis47db0582021-01-01 14:13:35 -080011634 @Override
James Mattis45d81842021-01-10 14:24:24 -080011635 public void setOemNetworkPreference(
11636 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011637 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080011638
James Mattisfa270db2021-05-31 17:11:10 -070011639 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11640 // Only bypass the permission/device checks if this is a valid test request.
11641 if (isValidTestOemNetworkPreference(preference)) {
11642 enforceManageTestNetworksPermission();
11643 } else {
11644 enforceAutomotiveDevice();
11645 enforceOemNetworkPreferencesPermission();
11646 validateOemNetworkPreferences(preference);
11647 }
James Mattis45d81842021-01-10 14:24:24 -080011648
James Mattis45d81842021-01-10 14:24:24 -080011649 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
11650 new Pair<>(preference, listener)));
11651 }
11652
James Mattisfa270db2021-05-31 17:11:10 -070011653 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000011654 * Sets the specified UIDs to get/receive the VPN as the only default network.
11655 *
11656 * Calling this will overwrite the existing network preference for this session, and the
11657 * specified UIDs won't get any default network when no VPN is connected.
11658 *
11659 * @param session The VPN session which manages the passed UIDs.
11660 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
11661 * setting for this session if the array is empty. Null is not allowed, the
11662 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
11663 * @hide
11664 */
11665 @Override
11666 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
11667 Objects.requireNonNull(ranges);
11668 enforceNetworkStackOrSettingsPermission();
11669 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
11670 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
11671 throw new IllegalArgumentException(
11672 "setVpnNetworkPreference: Passed UID ranges overlap");
11673 }
11674
11675 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
11676 new VpnNetworkPreferenceInfo(session,
11677 new ArraySet<UidRange>(Arrays.asList(ranges)))));
11678 }
11679
11680 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
11681 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
11682
11683 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
11684 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
11685
11686 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
11687 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
11688 // Finally, rematch.
11689 rematchAllNetworksAndRequests();
11690 }
11691
11692 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
11693 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
11694 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11695 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
11696 final List<NetworkRequest> requests = new ArrayList<>();
11697 // Request VPN only, so other networks won't be the fallback options when VPN is not
11698 // connected temporarily.
11699 requests.add(createVpnRequest());
11700 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
11701 setNetworkRequestUids(requests, uidRanges);
11702 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
11703 }
11704 return nris;
11705 }
11706
11707 /**
James Mattisfa270db2021-05-31 17:11:10 -070011708 * Check the validity of an OEM network preference to be used for testing purposes.
11709 * @param preference the preference to validate
11710 * @return true if this is a valid OEM network preference test request.
11711 */
11712 private boolean isValidTestOemNetworkPreference(
11713 @NonNull final OemNetworkPreferences preference) {
11714 // Allow for clearing of an existing OemNetworkPreference used for testing.
11715 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
11716 // changes after this check is complete. This is an unlikely scenario as calling of this API
11717 // is controlled by the OEM therefore the added complexity is not worth adding given those
11718 // circumstances. That said, it is an edge case to be aware of hence this comment.
11719 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
11720 && isTestOemNetworkPreference(mOemNetworkPreferences);
11721 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
11722 }
11723
11724 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
11725 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
11726 return prefMap.size() == 1
11727 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
11728 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
11729 }
11730
James Mattis45d81842021-01-10 14:24:24 -080011731 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
11732 for (@OemNetworkPreferences.OemNetworkPreference final int pref
11733 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070011734 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
11735 throw new IllegalArgumentException(
11736 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
11737 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080011738 }
11739 }
11740 }
11741
11742 private void handleSetOemNetworkPreference(
11743 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011744 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080011745 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11746 if (DBG) {
11747 log("set OEM network preferences :" + preference.toString());
11748 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011749
James Mattiscb1e0362021-04-06 17:07:42 -070011750 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000011751 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
11752 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
11753 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080011754 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080011755
11756 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011757 try {
11758 listener.onComplete();
11759 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080011760 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011761 }
James Mattis45d81842021-01-10 14:24:24 -080011762 }
11763 }
11764
paulhu74128522021-09-28 02:29:03 +000011765 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080011766 // Skip the requests which are set by other network preference. Because the uid range rules
11767 // should stay in netd.
11768 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080011769 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080011770 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080011771 }
11772
James Mattis3ce3d3c2021-02-09 18:18:28 -080011773 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
11774 ensureRunningOnConnectivityServiceThread();
11775 mDefaultNetworkRequests.addAll(nris);
11776 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
11777 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080011778 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000011779 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
11780 nrisToRegister.addAll(
11781 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
11782 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011783 }
11784
11785 /**
11786 * All current requests that are tracking the default network need to be assessed as to whether
11787 * or not the current set of per-application default requests will be changing their default
11788 * network. If so, those requests will need to be updated so that they will send callbacks for
11789 * default network changes at the appropriate time. Additionally, those requests tracking the
11790 * default that were previously updated by this flow will need to be reassessed.
11791 * @return the nris which will need to be updated.
11792 */
11793 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
11794 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
11795 // Get the distinct nris to check since for multilayer requests, it is possible to have the
11796 // same nri in the map's values for each of its NetworkRequest objects.
11797 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080011798 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011799 // Include this nri if it is currently being tracked.
11800 if (isPerAppTrackedNri(nri)) {
11801 defaultCallbackRequests.add(nri);
11802 continue;
11803 }
11804 // We only track callbacks for requests tracking the default.
11805 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
11806 continue;
11807 }
11808 // Include this nri if it will be tracked by the new per-app default requests.
11809 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011810 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080011811 if (isNriGoingToBeTracked) {
11812 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080011813 }
11814 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080011815 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080011816 }
11817
James Mattis3ce3d3c2021-02-09 18:18:28 -080011818 /**
11819 * Create nris for those network requests that are currently tracking the default network that
11820 * are being controlled by a per-application default.
11821 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
11822 * foundation when creating the nri. Important items include the calling uid's original
11823 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
11824 * requests are assumed to have already been validated as needing to be updated.
11825 * @return the Set of nris to use when registering network requests.
11826 */
11827 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
11828 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
11829 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
11830 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
11831 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011832 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011833
Chalard Jean9473c982021-07-29 20:03:04 +090011834 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080011835 if (trackingNri == mDefaultRequest) {
11836 callbackRequestsToRegister.add(new NetworkRequestInfo(
11837 callbackRequest,
11838 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
11839 continue;
11840 }
11841
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011842 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011843 callbackRequestsToRegister.add(new NetworkRequestInfo(
11844 callbackRequest,
11845 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011846 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090011847 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080011848 }
11849 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080011850 }
11851
Chalard Jean17215832021-03-01 14:06:28 +090011852 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
11853 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090011854 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011855 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090011856 }
11857 }
11858
James Mattis45d81842021-01-10 14:24:24 -080011859 /**
11860 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
11861 */
11862 @VisibleForTesting
11863 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011864 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080011865 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011866 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080011867 final SparseArray<Set<Integer>> uids =
11868 createUidsFromOemNetworkPreferences(preference);
11869 for (int i = 0; i < uids.size(); i++) {
11870 final int key = uids.keyAt(i);
11871 final Set<Integer> value = uids.valueAt(i);
11872 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
11873 // No need to add an nri without any requests.
11874 if (0 == nri.mRequests.size()) {
11875 continue;
11876 }
11877 nris.add(nri);
11878 }
11879
11880 return nris;
11881 }
11882
11883 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
11884 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070011885 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080011886 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080011887 final List<UserHandle> users =
11888 mContext.getSystemService(UserManager.class).getUserHandles(true);
11889 if (null == users || users.size() == 0) {
11890 if (VDBG || DDBG) {
11891 log("No users currently available for setting the OEM network preference.");
11892 }
James Mattisb6b6a432021-06-01 22:30:36 -070011893 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080011894 }
James Mattis45d81842021-01-10 14:24:24 -080011895 for (final Map.Entry<String, Integer> entry :
11896 preference.getNetworkPreferences().entrySet()) {
11897 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070011898 // Add the rules for all users as this policy is device wide.
11899 for (final UserHandle user : users) {
11900 try {
11901 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
11902 if (!prefToUids.contains(pref)) {
11903 prefToUids.put(pref, new ArraySet<>());
11904 }
11905 prefToUids.get(pref).add(uid);
11906 } catch (PackageManager.NameNotFoundException e) {
11907 // Although this may seem like an error scenario, it is ok that uninstalled
11908 // packages are sent on a network preference as the system will watch for
11909 // package installations associated with this network preference and update
11910 // accordingly. This is done to minimize race conditions on app install.
11911 continue;
James Mattis45d81842021-01-10 14:24:24 -080011912 }
James Mattis45d81842021-01-10 14:24:24 -080011913 }
11914 }
James Mattisb6b6a432021-06-01 22:30:36 -070011915 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080011916 }
11917
11918 private NetworkRequestInfo createNriFromOemNetworkPreferences(
11919 @OemNetworkPreferences.OemNetworkPreference final int preference,
11920 @NonNull final Set<Integer> uids) {
11921 final List<NetworkRequest> requests = new ArrayList<>();
11922 // Requests will ultimately be evaluated by order of insertion therefore it matters.
11923 switch (preference) {
11924 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
11925 requests.add(createUnmeteredNetworkRequest());
11926 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070011927 requests.add(createDefaultInternetRequestForTransport(
11928 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080011929 break;
11930 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
11931 requests.add(createUnmeteredNetworkRequest());
11932 requests.add(createOemPaidNetworkRequest());
11933 break;
11934 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
11935 requests.add(createOemPaidNetworkRequest());
11936 break;
11937 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
11938 requests.add(createOemPrivateNetworkRequest());
11939 break;
James Mattisfa270db2021-05-31 17:11:10 -070011940 case OEM_NETWORK_PREFERENCE_TEST:
11941 requests.add(createUnmeteredNetworkRequest());
11942 requests.add(createTestNetworkRequest());
11943 requests.add(createDefaultRequest());
11944 break;
11945 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
11946 requests.add(createTestNetworkRequest());
11947 break;
James Mattis45d81842021-01-10 14:24:24 -080011948 default:
11949 // This should never happen.
11950 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
11951 + " called with invalid preference of " + preference);
11952 }
11953
James Mattisfa270db2021-05-31 17:11:10 -070011954 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090011955 for (final int uid : uids) {
11956 ranges.add(new UidRange(uid, uid));
11957 }
11958 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080011959 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080011960 }
11961
11962 private NetworkRequest createUnmeteredNetworkRequest() {
11963 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11964 .addCapability(NET_CAPABILITY_NOT_METERED)
11965 .addCapability(NET_CAPABILITY_VALIDATED);
11966 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
11967 }
11968
11969 private NetworkRequest createOemPaidNetworkRequest() {
11970 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11971 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11972 .addCapability(NET_CAPABILITY_OEM_PAID)
11973 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11974 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11975 }
11976
11977 private NetworkRequest createOemPrivateNetworkRequest() {
11978 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
11979 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11980 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
11981 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11982 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11983 }
11984
11985 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070011986 final NetworkCapabilities netcap = new NetworkCapabilities();
11987 netcap.addCapability(NET_CAPABILITY_INTERNET);
11988 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
11989 return netcap;
11990 }
11991
11992 private NetworkRequest createTestNetworkRequest() {
11993 final NetworkCapabilities netcap = new NetworkCapabilities();
11994 netcap.clearAll();
11995 netcap.addTransportType(TRANSPORT_TEST);
11996 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080011997 }
James Mattis47db0582021-01-01 14:13:35 -080011998 }
markchien738ad912021-12-09 18:15:45 +080011999
12000 @Override
12001 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
12002 enforceNetworkStackOrSettingsPermission();
12003
12004 try {
12005 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012006 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012007 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012008 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012009 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012010 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012011 throw new IllegalStateException(e);
12012 }
12013 }
12014
12015 @Override
12016 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
12017 enforceNetworkStackOrSettingsPermission();
12018
12019 try {
12020 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012021 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012022 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012023 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012024 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012025 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012026 throw new IllegalStateException(e);
12027 }
12028 }
markchiene1561fa2021-12-09 22:00:56 +080012029
12030 @Override
markchien3c04e662022-03-22 16:29:56 +080012031 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080012032 enforceNetworkStackOrSettingsPermission();
12033
markchien3c04e662022-03-22 16:29:56 +080012034 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
12035 int firewallRule = getFirewallRuleType(chain, rule);
12036
12037 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
12038 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
12039 }
12040
markchiene1561fa2021-12-09 22:00:56 +080012041 try {
markchien3c04e662022-03-22 16:29:56 +080012042 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012043 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080012044 throw new IllegalStateException(e);
12045 }
12046 }
markchien98a6f952022-01-13 23:43:53 +080012047
Motomu Utsumi900b8062023-01-19 16:16:49 +090012048 @Override
12049 public int getUidFirewallRule(final int chain, final int uid) {
12050 enforceNetworkStackOrSettingsPermission();
12051 return mBpfNetMaps.getUidRule(chain, uid);
12052 }
12053
markchien3c04e662022-03-22 16:29:56 +080012054 private int getFirewallRuleType(int chain, int rule) {
12055 final int defaultRule;
12056 switch (chain) {
12057 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000012058 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
12059 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000012060 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080012061 defaultRule = FIREWALL_RULE_ALLOW;
12062 break;
12063 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
12064 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
12065 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
12066 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
12067 defaultRule = FIREWALL_RULE_DENY;
12068 break;
12069 default:
12070 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
12071 }
12072 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
12073
12074 return rule;
12075 }
12076
Motomu Utsumied1848c2023-03-28 18:08:12 +090012077 private void closeSocketsForFirewallChainLocked(final int chain)
12078 throws ErrnoException, SocketException, InterruptedIOException {
12079 if (mBpfNetMaps.isFirewallAllowList(chain)) {
12080 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
12081 // So, close all non-system socket owned by uids that are not explicitly allowed
12082 Set<Range<Integer>> ranges = new ArraySet<>();
12083 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
12084 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
12085 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
12086 } else {
12087 // Denylist means the firewall allows all by default, uids must be explicitly denied
12088 // So, close socket owned by uids that are explicitly denied
12089 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
12090 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
12091 }
12092 }
12093
markchien98a6f952022-01-13 23:43:53 +080012094 @Override
12095 public void setFirewallChainEnabled(final int chain, final boolean enable) {
12096 enforceNetworkStackOrSettingsPermission();
12097
12098 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012099 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012100 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080012101 throw new IllegalStateException(e);
12102 }
Motomu Utsumied1848c2023-03-28 18:08:12 +090012103
12104 if (SdkLevel.isAtLeastU() && enable) {
12105 try {
12106 closeSocketsForFirewallChainLocked(chain);
12107 } catch (ErrnoException | SocketException | InterruptedIOException e) {
12108 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
12109 }
12110 }
markchien98a6f952022-01-13 23:43:53 +080012111 }
12112
markchien00a0bed2022-01-13 23:46:13 +080012113 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012114 public boolean getFirewallChainEnabled(final int chain) {
12115 enforceNetworkStackOrSettingsPermission();
12116
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000012117 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012118 }
12119
12120 @Override
markchien00a0bed2022-01-13 23:46:13 +080012121 public void replaceFirewallChain(final int chain, final int[] uids) {
12122 enforceNetworkStackOrSettingsPermission();
12123
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000012124 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080012125 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080012126
12127 @Override
12128 public IBinder getCompanionDeviceManagerProxyService() {
12129 enforceNetworkStackPermission(mContext);
12130 return mCdmps;
12131 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070012132}