blob: b17af9978d1645af15472f597be03adc768c45f6 [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000018
Haoyu Baib5da5752012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Mark Fasheh7c999d82023-05-04 20:23:11 +000020import static android.app.ActivityManager.UidFrozenStateChangedCallback.UID_FROZEN_STATE_FROZEN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090021import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
22import static android.content.pm.PackageManager.FEATURE_WATCH;
23import static android.content.pm.PackageManager.FEATURE_WIFI;
24import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
Chalard Jean9a396cc2018-02-21 18:43:54 +090025import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090026import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
27import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
28import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
29import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
33import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090034import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
35import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000036import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
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 Utsumi278db582023-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 Fasheh7c999d82023-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 Utsumi93a22182023-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 VANbee2ee12023-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 VANbee2ee12023-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 Utsumi93a22182023-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 Utsumi93a22182023-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 Fasheh7c999d82023-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 Utsumi278db582023-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 Utsumi93a22182023-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 Utsumid44a33a2023-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 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001522 }
1523
junyulaie7c7d2a2021-01-26 15:29:15 +08001524 public ConnectivityService(Context context) {
1525 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001526 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1527 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001528 }
1529
1530 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001531 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1532 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001533 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001534
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001535 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001536 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001537 mSystemProperties = mDeps.getSystemProperties();
1538 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001539 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001540 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001541 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1542 // Pass limit - 1 to maintain backward compatibility.
1543 // TODO: Remove the workaround.
1544 mNetworkRequestCounter =
1545 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1546 mSystemNetworkRequestCounter =
1547 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001548
Hugo Benichi208c0102016-07-28 17:53:06 +09001549 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001550 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1551 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001552 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001553 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001554 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001555 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1556 mDefaultNetworkRequests.add(mDefaultRequest);
1557 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001558
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001559 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001560 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001561
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001562 // The default WiFi request is a background request so that apps using WiFi are
1563 // migrated to a better network (typically ethernet) when one comes up, instead
1564 // of staying on WiFi forever.
1565 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1566 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1567
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001568 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1569 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1570 NetworkRequest.Type.BACKGROUND_REQUEST);
1571
Chalard Jean0702f982021-09-16 21:50:07 +09001572 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1573 // TODO: Consider making the timer customizable.
1574 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1575 mCellularRadioTimesharingCapable =
1576 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1577
Paul Hu51f816b2022-08-11 14:43:47 +00001578 mNetd = netd;
1579 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001580 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001581 mPermissionMonitor =
1582 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001583 mHandlerThread.start();
1584 mHandler = new InternalHandler(mHandlerThread.getLooper());
1585 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001586 mConnectivityDiagnosticsHandler =
1587 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001588
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001589 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001590 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001591
junyulaie7c7d2a2021-01-26 15:29:15 +08001592 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001593 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001594 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001595 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001596
Wink Saville32506bc2013-06-29 21:10:57 -07001597 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001598 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001599 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001600 mCarrierPrivilegeAuthenticator =
1601 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001602
Sudheer Shanka9967d462021-03-18 19:09:25 +00001603 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001604 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1605 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001606 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001607
1608 final PowerManager powerManager = (PowerManager) context.getSystemService(
1609 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001610 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001611 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001612
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001613 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1614 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001615 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001616 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001617 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001618 mProtectedNetworks.add(p);
1619 } else {
1620 if (DBG) loge("Ignoring protectedNetwork " + p);
1621 }
1622 }
1623
soma, kawata29444ae2019-05-23 09:30:40 +09001624 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1625
James Mattis02220e22021-03-13 19:27:21 -08001626 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001627 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001628 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001629 final IntentFilter userIntentFilter = new IntentFilter();
1630 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1631 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1632 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1633 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001634
James Mattis02220e22021-03-13 19:27:21 -08001635 // Listen to package add/removes for netd
1636 final IntentFilter packageIntentFilter = new IntentFilter();
1637 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1638 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1639 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1640 packageIntentFilter.addDataScheme("package");
1641 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001642 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001643
lucaslind5c2d072021-02-20 18:59:47 +08001644 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001645
Chalard Jean46bfbf02022-02-02 00:56:25 +09001646 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001647 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001648 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001649 } catch (RemoteException | ServiceSpecificException e) {
1650 loge("Error registering event listener :" + e);
1651 }
1652
Erik Kline05f2b402015-04-30 12:58:40 +09001653 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1654 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001655
chiachangwang7c17c282023-02-02 05:58:59 +00001656 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001657 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001658 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001659
1660 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001661 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001662 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1663 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001664 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001665 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1666 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001667
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001668 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001669 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001670 mNetworkRanker =
1671 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1672
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001673 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001674
Chiachang Wangc1215d32020-10-20 15:38:58 +08001675 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001676 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001677
Chalard Jean28018572020-12-21 18:36:52 +09001678 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1679 // request that doesn't allow fallback to the default network. It should never be visible
1680 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1681 // arguments like the handler or the DnsResolver.
1682 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001683 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001684 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001685 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001686 new LinkProperties(), new NetworkCapabilities(),
1687 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001688 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1689 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001690
1691 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001692 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1693 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1694 // Even if it could, running on S would at least require mocking out the BPF map,
1695 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1696 // the bpf syscall. http://aosp/1907693
1697 if (SdkLevel.isAtLeastT()) {
1698 mDscpPolicyTracker = new DscpPolicyTracker();
1699 }
Tyler Wear72388212021-09-09 14:49:02 -07001700 } catch (ErrnoException e) {
1701 loge("Unable to create DscpPolicyTracker");
1702 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001703
1704 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1705 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001706
1707 if (SdkLevel.isAtLeastT()) {
1708 mCdmps = new CompanionDeviceManagerProxyService(context);
1709 } else {
1710 mCdmps = null;
1711 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001712
1713 if (SdkLevel.isAtLeastU()
1714 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION)) {
1715 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1716 new UidFrozenStateChangedCallback() {
1717 @Override
1718 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1719 if (uids.length != frozenStates.length) {
1720 Log.wtf(TAG, "uids has length " + uids.length
1721 + " but frozenStates has length " + frozenStates.length);
1722 return;
1723 }
1724
1725 final UidFrozenStateChangedArgs args =
1726 new UidFrozenStateChangedArgs(uids, frozenStates);
1727
1728 mHandler.sendMessage(
1729 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1730 }
1731 };
1732
1733 final ActivityManager activityManager =
1734 mContext.getSystemService(ActivityManager.class);
1735 activityManager.registerUidFrozenStateChangedCallback(
1736 (Runnable r) -> r.run(), frozenStateChangedCallback);
1737 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001738 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001739
Xiao Ma0a171c02022-01-23 16:14:51 +00001740 /**
1741 * Check whether or not the device supports Ethernet transport.
1742 */
1743 public static boolean deviceSupportsEthernet(final Context context) {
1744 final PackageManager pm = context.getPackageManager();
1745 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1746 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1747 }
1748
Chalard Jean46adcf32018-04-18 20:18:38 +09001749 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001750 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1751 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001752 }
1753
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001754 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1755 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001756 final NetworkCapabilities netCap = new NetworkCapabilities();
1757 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001758 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001759 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001760 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001761 return netCap;
1762 }
1763
James Mattis45d81842021-01-10 14:24:24 -08001764 private NetworkRequest createDefaultRequest() {
1765 return createDefaultInternetRequestForTransport(
1766 TYPE_NONE, NetworkRequest.Type.REQUEST);
1767 }
1768
lucaslin3ba7cc22022-12-19 02:35:33 +00001769 private NetworkRequest createVpnRequest() {
1770 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1771 .withoutDefaultCapabilities()
1772 .addTransportType(TRANSPORT_VPN)
1773 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1774 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1775 .build();
1776 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1777 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1778 }
1779
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001780 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001781 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001782 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001783 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001784 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001785 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001786 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001787 netCap.addTransportType(transportType);
1788 }
James Mattis45d81842021-01-10 14:24:24 -08001789 return createNetworkRequest(type, netCap);
1790 }
1791
1792 private NetworkRequest createNetworkRequest(
1793 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001794 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001795 }
1796
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001797 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1798 NetworkRequest.Type type) {
1799 final NetworkCapabilities netCap = new NetworkCapabilities();
1800 netCap.clearAll();
1801 netCap.addCapability(capability);
1802 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1803 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1804 }
1805
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001806 // Used only for testing.
1807 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001808 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001809 // changing ContentResolver to make registerContentObserver non-final).
1810 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1811 // by subclassing SettingsObserver.
1812 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001813 void updateAlwaysOnNetworks() {
1814 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001815 }
1816
Erik Kline9a62f012018-03-21 07:18:33 -07001817 // See FakeSettingsProvider comment above.
1818 @VisibleForTesting
1819 void updatePrivateDnsSettings() {
1820 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1821 }
1822
paulhu51f77dc2021-06-07 02:34:20 +00001823 @VisibleForTesting
1824 void updateMobileDataPreferredUids() {
1825 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1826 }
1827
Patrick Rohr2857ac42022-01-21 14:58:16 +01001828 @VisibleForTesting
1829 void updateIngressRateLimit() {
1830 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1831 }
1832
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001833 private void handleAlwaysOnNetworkRequest(
1834 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001835 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001836 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001837 handleAlwaysOnNetworkRequest(networkRequest, enable);
1838 }
1839
1840 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001841 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001842 if (enable == isEnabled) {
1843 return; // Nothing to do.
1844 }
1845
1846 if (enable) {
1847 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001848 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001849 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001850 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001851 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001852 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1853 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001854 }
1855 }
1856
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001857 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001858 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1859 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1860 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1861 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001862 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1863 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001864 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001865 }
1866
paulhu51f77dc2021-06-07 02:34:20 +00001867 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001868 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001869 private void registerSettingsCallbacks() {
1870 // Watch for global HTTP proxy changes.
1871 mSettingsObserver.observe(
1872 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1873 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1874
Chalard Jean46bfbf02022-02-02 00:56:25 +09001875 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001876 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001877 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001878 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1879
Chalard Jean46bfbf02022-02-02 00:56:25 +09001880 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001881 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001882 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001883 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001884
1885 // Watch for mobile data preferred uids changes.
1886 mSettingsObserver.observe(
1887 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1888 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001889
1890 // Watch for ingress rate limit changes.
1891 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01001892 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01001893 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1894 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001895 }
1896
Erik Kline31b4a9e2018-01-11 21:07:29 +09001897 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001898 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1899 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001900 }
1901 }
1902
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001903 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001904 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1905 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001906 return mNextNetworkRequestId++;
1907 }
1908
junyulai74f9a8b2018-06-13 15:00:37 +08001909 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09001910 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08001911 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001912 if (network == null) {
1913 return null;
1914 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001915 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001916 }
1917
1918 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001919 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001920 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001921 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001922 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001923
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001924 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001925 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001926 private NetworkAgentInfo getVpnForUid(int uid) {
1927 synchronized (mNetworkForNetId) {
1928 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1929 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09001930 if (nai.isVPN() && nai.everConnected()
1931 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001932 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001933 }
1934 }
1935 }
1936 return null;
1937 }
1938
Chalard Jean46bfbf02022-02-02 00:56:25 +09001939 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001940 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001941 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001942 final NetworkAgentInfo nai = getVpnForUid(uid);
1943 if (nai != null) return nai.declaredUnderlyingNetworks;
1944 return null;
1945 }
1946
Lorenzo Colittia7574052021-01-19 01:33:05 +09001947 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001948 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001949
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001950 final Network[] networks = getVpnUnderlyingNetworks(uid);
1951 if (networks != null) {
1952 // getUnderlyingNetworks() returns:
1953 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1954 // empty array => the VPN explicitly said "no default network".
1955 // non-empty array => the VPN specified one or more default networks; we use the
1956 // first one.
1957 if (networks.length > 0) {
1958 nai = getNetworkAgentInfoForNetwork(networks[0]);
1959 } else {
1960 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001961 }
1962 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001963 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001964 }
1965
1966 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001967 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001968 */
paulhu7aeba372020-12-30 00:42:19 +08001969 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1970 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001971 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001972 if (ignoreBlocked) {
1973 return false;
1974 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001975 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001976 final long ident = Binder.clearCallingIdentity();
1977 try {
1978 final boolean metered = nc == null ? true : nc.isMetered();
1979 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1980 } finally {
1981 Binder.restoreCallingIdentity(ident);
1982 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001983 }
1984
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001985 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001986 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1987 return;
1988 }
Hugo Benichi47011212017-03-30 10:46:05 +09001989 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001990 synchronized (mBlockedAppUids) {
1991 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001992 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001993 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001994 blocked = false;
1995 } else {
1996 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001997 }
1998 }
Hugo Benichi47011212017-03-30 10:46:05 +09001999 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2000 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2001 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002002 }
2003
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002004 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002005 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2006 return;
2007 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002008 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002009 final int requestId = nri.getActiveRequest() != null
2010 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002011 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002012 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002013 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002014 }
2015
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002016 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002017 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002018 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002019 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002020 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002021 @NonNull
2022 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2023 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002024 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2025 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2026 // but only exists if an app asks about them or requests them. Ensure the requesting app
2027 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002028 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002029 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2030 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2031 null /* extraInfo */);
2032 }
2033 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002034 return filtered;
2035 }
2036
2037 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2038 boolean ignoreBlocked) {
2039 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2040 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002041 }
2042
2043 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002044 * Return NetworkInfo for the active (i.e., connected) network interface.
2045 * It is assumed that at most one network is active at a time. If more
2046 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002047 * @return the info for the active network, or {@code null} if none is
2048 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002049 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002050 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002051 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002052 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002053 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002054 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002055 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2056 if (nai == null) return null;
2057 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2058 maybeLogBlockedNetworkInfo(networkInfo, uid);
2059 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002060 }
2061
Paul Jensen1f567382015-02-13 14:18:39 -05002062 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002063 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002064 public Network getActiveNetwork() {
2065 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002066 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002067 }
2068
2069 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002070 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002071 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002072 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002073 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002074 }
2075
Chalard Jean46bfbf02022-02-02 00:56:25 +09002076 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002077 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002078 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2079 if (vpnNai != null) {
2080 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2081 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2082 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002083 }
Paul Jensen1f567382015-02-13 14:18:39 -05002084 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002085
James Mattis2516da32021-01-31 17:06:19 -08002086 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002087 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2088 ignoreBlocked)) {
2089 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002090 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002091 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002092 }
2093
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002094 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002095 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002096 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002097 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002098 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2099 if (nai == null) return null;
2100 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002101 }
2102
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002103 /** Returns a NetworkInfo object for a network that doesn't exist. */
2104 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2105 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2106 getNetworkTypeName(networkType), "" /* subtypeName */);
2107 info.setIsAvailable(true);
2108 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2109 // background data is restricted.
2110 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2111 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2112 ? DetailedState.BLOCKED
2113 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002114 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2115 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002116 return info;
2117 }
2118
Lorenzo Colittia7574052021-01-19 01:33:05 +09002119 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002120 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2121 return null;
2122 }
2123 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002124 if (nai == null) {
2125 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002126 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002127 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2128 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002129 }
2130
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002131 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002132 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002133 public NetworkInfo getNetworkInfo(int networkType) {
2134 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002135 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002136 if (getVpnUnderlyingNetworks(uid) != null) {
2137 // A VPN is active, so we may need to return one of its underlying networks. This
2138 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002139 // getNetworkAgentInfoForUid.
2140 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2141 if (nai == null) return null;
2142 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2143 if (networkInfo.getType() == networkType) {
2144 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002145 }
2146 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002147 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002148 }
2149
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002150 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002151 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002152 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002153 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002154 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002155 if (nai == null) return null;
2156 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002157 }
2158
2159 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002160 public NetworkInfo[] getAllNetworkInfo() {
2161 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002162 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002163 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2164 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002165 NetworkInfo info = getNetworkInfo(networkType);
2166 if (info != null) {
2167 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002168 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002169 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002170 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002171 }
2172
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002173 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002174 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002175 public Network getNetworkForType(int networkType) {
2176 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002177 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2178 return null;
2179 }
2180 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2181 if (nai == null) {
2182 return null;
2183 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002184 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002185 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2186 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002187 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002188 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002189 }
2190
2191 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002192 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002193 public Network[] getAllNetworks() {
2194 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002195 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002196 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002197 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002198 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002199 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002200 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002201 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002202 }
2203
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002204 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002205 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002206 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002207 // The basic principle is: if an app's traffic could possibly go over a
2208 // network, without the app doing anything multinetwork-specific,
2209 // (hence, by "default"), then include that network's capabilities in
2210 // the array.
2211 //
2212 // In the normal case, app traffic only goes over the system's default
2213 // network connection, so that's the only network returned.
2214 //
2215 // With a VPN in force, some app traffic may go into the VPN, and thus
2216 // over whatever underlying networks the VPN specifies, while other app
2217 // traffic may go over the system default network (e.g.: a split-tunnel
2218 // VPN, or an app disallowed by the VPN), so the set of networks
2219 // returned includes the VPN's underlying networks and the system
2220 // default.
2221 enforceAccessPermission();
2222
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002223 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002224
James Mattis2516da32021-01-31 17:06:19 -08002225 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2226 if (!nri.isBeingSatisfied()) {
2227 continue;
2228 }
2229 final NetworkAgentInfo nai = nri.getSatisfier();
2230 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2231 if (null != nc
2232 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2233 && !result.containsKey(nai.network)) {
2234 result.put(
2235 nai.network,
2236 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002237 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002238 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2239 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002240 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002241 }
2242
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002243 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002244 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002245 if (null != networks) {
2246 for (final Network network : networks) {
2247 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2248 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002249 result.put(
2250 network,
2251 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002252 nc,
2253 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002254 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002255 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002256 }
2257 }
2258 }
2259
2260 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2261 out = result.values().toArray(out);
2262 return out;
2263 }
2264
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002265 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002266 public boolean isNetworkSupported(int networkType) {
2267 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002268 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002269 }
2270
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002271 /**
2272 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002273 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002274 * @return the ip properties for the active network, or {@code null} if
2275 * none is active
2276 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002277 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002278 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002279 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002280 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002281 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2282 if (nai == null) return null;
2283 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002284 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002285 }
2286
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002287 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002288 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002289 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002290 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002291 final LinkProperties lp = getLinkProperties(nai);
2292 if (lp == null) return null;
2293 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002294 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002295 }
2296
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002297 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002298 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002299 public LinkProperties getLinkProperties(Network network) {
2300 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002301 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2302 if (lp == null) return null;
2303 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002304 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002305 }
2306
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002307 @Nullable
2308 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002309 if (nai == null) {
2310 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002311 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002312 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002313 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002314 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002315 }
2316
lucaslinc582d502022-01-27 09:07:00 +08002317 @Override
2318 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002319 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002320 @NonNull String packageName, @Nullable String callingAttributionTag) {
2321 Objects.requireNonNull(packageName);
2322 Objects.requireNonNull(lp);
2323 enforceNetworkStackOrSettingsPermission();
2324 if (!checkAccessPermission(-1 /* pid */, uid)) {
2325 return null;
2326 }
2327 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2328 }
2329
Qingxi Lib2748102020-01-08 12:51:49 -08002330 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2331 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2332 }
2333
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002334 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002335 if (nai == null) return null;
2336 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002337 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002338 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002339 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002340 }
2341
2342 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002343 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2344 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002345 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002346 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002347 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002348 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002349 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002350 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002351 }
2352
lucaslinc582d502022-01-27 09:07:00 +08002353 @Override
lucaslind2b06132022-03-02 10:56:57 +08002354 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2355 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2356 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002357 Objects.requireNonNull(nc);
2358 Objects.requireNonNull(packageName);
2359 enforceNetworkStackOrSettingsPermission();
2360 if (!checkAccessPermission(-1 /* pid */, uid)) {
2361 return null;
2362 }
2363 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2364 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2365 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2366 callingAttributionTag);
2367 }
2368
lucaslin69e1aa92022-03-22 18:15:09 +08002369 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2370 if (nc.getUnderlyingNetworks() != null
2371 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2372 nc.setUnderlyingNetworks(null);
2373 }
2374 }
2375
Qingxi Libb8da982020-01-17 17:54:27 -08002376 @VisibleForTesting
2377 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002378 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002379 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2380 // this would be expensive (one more permission check every time any NC callback is
2381 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2382 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2383 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002384 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002385 if (!checkSettingsPermission(callerPid, callerUid)) {
2386 newNc.setUids(null);
2387 newNc.setSSID(null);
2388 }
Etan Cohen107ae952018-12-30 17:59:59 -08002389 if (newNc.getNetworkSpecifier() != null) {
2390 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2391 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002392 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2393 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002394 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2395 newNc.setAdministratorUids(new int[0]);
2396 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002397 if (!checkAnyPermissionOf(mContext,
Benedict Wong53de25f2021-03-24 14:01:51 -07002398 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002399 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002400 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002401 }
lucaslin69e1aa92022-03-22 18:15:09 +08002402 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002403
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002404 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002405 }
2406
Roshan Pius98f59ec2021-02-23 08:47:39 -08002407 /**
2408 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002409 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002410 * NetworkCapabilities.
2411 * Note: This wrapper does not support any sort of invalidation and thus must not be
2412 * persistent or long-lived. It may only be used for the time necessary to
2413 * compute the redactions required by one particular NetworkCallback or
2414 * synchronous call.
2415 */
2416 private class RedactionPermissionChecker {
2417 private final int mCallingPid;
2418 private final int mCallingUid;
2419 @NonNull private final String mCallingPackageName;
2420 @Nullable private final String mCallingAttributionTag;
2421
2422 private Boolean mHasLocationPermission = null;
2423 private Boolean mHasLocalMacAddressPermission = null;
2424 private Boolean mHasSettingsPermission = null;
2425
2426 RedactionPermissionChecker(int callingPid, int callingUid,
2427 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2428 mCallingPid = callingPid;
2429 mCallingUid = callingUid;
2430 mCallingPackageName = callingPackageName;
2431 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002432 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002433
2434 private boolean hasLocationPermissionInternal() {
2435 final long token = Binder.clearCallingIdentity();
2436 try {
2437 return mLocationPermissionChecker.checkLocationPermission(
2438 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2439 null /* message */);
2440 } finally {
2441 Binder.restoreCallingIdentity(token);
2442 }
2443 }
2444
2445 /**
2446 * Returns whether the app holds location permission or not (might return cached result
2447 * if the permission was already checked before).
2448 */
2449 public boolean hasLocationPermission() {
2450 if (mHasLocationPermission == null) {
2451 // If there is no cached result, perform the check now.
2452 mHasLocationPermission = hasLocationPermissionInternal();
2453 }
2454 return mHasLocationPermission;
2455 }
2456
2457 /**
2458 * Returns whether the app holds local mac address permission or not (might return cached
2459 * result if the permission was already checked before).
2460 */
2461 public boolean hasLocalMacAddressPermission() {
2462 if (mHasLocalMacAddressPermission == null) {
2463 // If there is no cached result, perform the check now.
2464 mHasLocalMacAddressPermission =
2465 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2466 }
2467 return mHasLocalMacAddressPermission;
2468 }
2469
2470 /**
2471 * Returns whether the app holds settings permission or not (might return cached
2472 * result if the permission was already checked before).
2473 */
2474 public boolean hasSettingsPermission() {
2475 if (mHasSettingsPermission == null) {
2476 // If there is no cached result, perform the check now.
2477 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2478 }
2479 return mHasSettingsPermission;
2480 }
2481 }
2482
2483 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2484 @NetworkCapabilities.NetCapability long redaction) {
2485 return (redactions & redaction) != 0;
2486 }
2487
2488 /**
2489 * Use the provided |applicableRedactions| to check the receiving app's
2490 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2491 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2492 * before being sent to the corresponding app.
2493 */
2494 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2495 @NetworkCapabilities.RedactionType long applicableRedactions,
2496 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2497 boolean includeLocationSensitiveInfo) {
2498 long redactions = applicableRedactions;
2499 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2500 if (includeLocationSensitiveInfo
2501 && redactionPermissionChecker.hasLocationPermission()) {
2502 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2503 }
2504 }
2505 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2506 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2507 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2508 }
2509 }
2510 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2511 if (redactionPermissionChecker.hasSettingsPermission()) {
2512 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2513 }
2514 }
2515 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002516 }
2517
Qingxi Lib2748102020-01-08 12:51:49 -08002518 @VisibleForTesting
2519 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002520 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002521 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002522 int callingPid, int callingUid, @NonNull String callingPkgName,
2523 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002524 if (nc == null) {
2525 return null;
2526 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002527 // Avoid doing location permission check if the transport info has no location sensitive
2528 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002529 final RedactionPermissionChecker redactionPermissionChecker =
2530 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2531 callingAttributionTag);
2532 final long redactions = retrieveRequiredRedactions(
2533 nc.getApplicableRedactions(), redactionPermissionChecker,
2534 includeLocationSensitiveInfo);
2535 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002536 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002537 // TODO : calling UID is redacted because apps should generally not know what UID is
2538 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002539 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002540 newNc.setOwnerUid(INVALID_UID);
2541 return newNc;
2542 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002543 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2544 if (nc.hasTransport(TRANSPORT_VPN)) {
2545 // Owner UIDs already checked above. No need to re-check.
2546 return newNc;
2547 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002548 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2549 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002550 // compatibility for older apps.
2551 if (!includeLocationSensitiveInfo
2552 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002553 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002554 newNc.setOwnerUid(INVALID_UID);
2555 return newNc;
2556 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002557 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002558 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002559 newNc.setOwnerUid(INVALID_UID);
2560 }
Qingxi Lib2748102020-01-08 12:51:49 -08002561 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002562 }
2563
lucaslinc582d502022-01-27 09:07:00 +08002564 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002565 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2566 LinkProperties lp, int callerPid, int callerUid) {
2567 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002568 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2569 // this would be expensive (one more permission check every time any LP callback is
2570 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2571 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2572 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002573
2574 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2575 final boolean needsSanitization =
2576 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2577 if (!needsSanitization) {
2578 return new LinkProperties(lp);
2579 }
2580
2581 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002582 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002583 }
2584
2585 final LinkProperties newLp = new LinkProperties(lp);
2586 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2587 // object gets parceled.
2588 newLp.setCaptivePortalApiUrl(null);
2589 newLp.setCaptivePortalData(null);
2590 return newLp;
2591 }
2592
Roshan Pius08c94fb2020-01-16 12:17:17 -08002593 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2594 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002595 // There is no need to track the effective UID of the request here. If the caller
2596 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002597 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002598 // Unprivileged apps can only pass in null or their own UID.
2599 if (nc.getUids() == null) {
2600 // If the caller passes in null, the callback will also match networks that do not
2601 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2602 // In this case, redact everything in the request immediately. This ensures that the
2603 // app is not able to get any redacted information by filing an unredacted request
2604 // and observing whether the request matches something.
2605 if (nc.getNetworkSpecifier() != null) {
2606 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2607 }
2608 } else {
2609 nc.setSingleUid(callerUid);
2610 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002611 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002612 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002613 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002614
2615 // Clear owner UID; this can never come from an app.
2616 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002617 }
2618
Chalard Jean38354d12018-03-20 19:13:57 +09002619 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002620 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002621 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2622 }
2623 }
2624
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002625 @Override
2626 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2627 enforceAccessPermission();
2628 final int callerUid = Binder.getCallingUid();
2629 final long token = Binder.clearCallingIdentity();
2630 try {
2631 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2632 } finally {
2633 Binder.restoreCallingIdentity(token);
2634 }
2635 }
2636
junyulaiebd15162021-03-03 12:09:05 +08002637 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002638 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002639 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002640 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002641 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002642
Serik Beketayev05130302021-01-15 16:47:25 -08002643 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002644 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002645 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2646 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002647 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002648 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002649 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002650 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2651 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002652 }
2653 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002654 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002655 }
2656
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002657 @Override
junyulaiebd15162021-03-03 12:09:05 +08002658 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002659 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002660 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002661 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002662
2663 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2664 for (Network network : getAllNetworks()) {
2665 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09002666 final boolean includeNetwork = (nai != null) && nai.isCreated();
2667 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002668 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2669 // NetworkCapabilities, which may contain UIDs of apps to which the
2670 // network applies. Should the UIDs be cleared so as not to leak or
2671 // interfere ?
2672 result.add(nai.getNetworkStateSnapshot());
2673 }
2674 }
2675 return result;
2676 }
2677
2678 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002679 public boolean isActiveNetworkMetered() {
2680 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002681
Qingxi Lib2748102020-01-08 12:51:49 -08002682 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002683 if (caps != null) {
2684 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2685 } else {
2686 // Always return the most conservative value
2687 return true;
2688 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002689 }
2690
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002691 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002692 * Ensures that the system cannot call a particular method.
2693 */
2694 private boolean disallowedBecauseSystemCaller() {
2695 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002696 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2697 // for devices launched with Q and above. However, existing devices upgrading to Q and
2698 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002699 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002700 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002701 log("This method exists only for app backwards compatibility"
2702 + " and must not be called by system services.");
2703 return true;
2704 }
2705 return false;
2706 }
2707
paulhub2c28682021-08-18 18:35:54 +08002708 private int getAppUid(final String app, final UserHandle user) {
2709 final PackageManager pm =
2710 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2711 final long token = Binder.clearCallingIdentity();
2712 try {
2713 return pm.getPackageUid(app, 0 /* flags */);
2714 } catch (PackageManager.NameNotFoundException e) {
2715 return -1;
2716 } finally {
2717 Binder.restoreCallingIdentity(token);
2718 }
2719 }
2720
2721 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2722 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2723 if (getAppUid(packageName, user) != callingUid) {
2724 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2725 }
2726 }
2727
Lorenzo Colitti23862912018-09-28 11:31:55 +09002728 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002729 * Ensure that a network route exists to deliver traffic to the specified
2730 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002731 * @param networkType the type of the network over which traffic to the
2732 * specified host is to be routed
2733 * @param hostAddress the IP address of the host to which the route is
2734 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002735 * @return {@code true} on success, {@code false} on failure
2736 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002737 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002738 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2739 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002740 if (disallowedBecauseSystemCaller()) {
2741 return false;
2742 }
paulhub2c28682021-08-18 18:35:54 +08002743 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002744 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002745 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002746 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002747 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002748
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002749 InetAddress addr;
2750 try {
2751 addr = InetAddress.getByAddress(hostAddress);
2752 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002753 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002754 return false;
2755 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002756
The Android Open Source Project28527d22009-03-03 19:31:44 -08002757 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002758 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002759 return false;
2760 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002761
2762 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2763 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002764 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002765 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2766 } else {
2767 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2768 }
2769 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002770 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002771
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002772 DetailedState netState;
2773 synchronized (nai) {
2774 netState = nai.networkInfo.getDetailedState();
2775 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002776
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002777 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002778 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002779 log("requestRouteToHostAddress on down network "
2780 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002781 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002782 }
2783 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002784 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002785
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002786 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002787 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002788 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002789 LinkProperties lp;
2790 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002791 synchronized (nai) {
2792 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002793 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002794 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002795 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002796 if (DBG) {
2797 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2798 }
Wink Saville32506bc2013-06-29 21:10:57 -07002799 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002800 } finally {
2801 Binder.restoreCallingIdentity(token);
2802 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002803 }
2804
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002805 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002806 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002807 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002808 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002809 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002810 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002811 if (bestRoute.getGateway().equals(addr)) {
2812 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002813 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002814 } else {
2815 // if we will connect to this through another route, add a direct route
2816 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002817 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002818 }
2819 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002820 if (DBG) log("Adding legacy route " + bestRoute +
2821 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002822
2823 final String dst = bestRoute.getDestinationLinkAddress().toString();
2824 final String nextHop = bestRoute.hasGateway()
2825 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002826 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002827 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2828 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002829 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002830 return false;
2831 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002832 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002833 }
2834
paulhu7c0a2e62021-01-08 00:51:49 +08002835 class DnsResolverUnsolicitedEventCallback extends
2836 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002837 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002838 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002839 try {
2840 mHandler.sendMessage(mHandler.obtainMessage(
2841 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002842 new PrivateDnsValidationUpdate(event.netId,
2843 InetAddresses.parseNumericAddress(event.ipAddress),
2844 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002845 } catch (IllegalArgumentException e) {
2846 loge("Error parsing ip address in validation event");
2847 }
2848 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002849
2850 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002851 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2852 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002853 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2854 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2855 // event callback for certain nai. e.g. cellular. Register here to pass to
2856 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002857 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002858 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2859 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002860 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002861 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002862 }
2863 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002864
2865 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002866 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2867 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2868 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002869 }
dalyk1720e542018-03-05 12:42:22 -05002870
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002871 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002872 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002873 return this.VERSION;
2874 }
2875
2876 @Override
2877 public String getInterfaceHash() {
2878 return this.HASH;
2879 }
paulhu7c0a2e62021-01-08 00:51:49 +08002880 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002881
2882 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002883 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2884 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002885
paulhu7c0a2e62021-01-08 00:51:49 +08002886 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002887 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002888 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002889 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002890 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002891 }
2892 }
2893
Sudheer Shanka9967d462021-03-18 19:09:25 +00002894 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002895 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002896 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002897 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2898 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002899 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002900 };
2901
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002902 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002903 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002904 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002905 }
2906
Mark Fasheh7c999d82023-05-04 20:23:11 +00002907 static final class UidFrozenStateChangedArgs {
2908 final int[] mUids;
2909 final int[] mFrozenStates;
2910
2911 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
2912 mUids = uids;
2913 mFrozenStates = frozenStates;
2914 }
2915 }
2916
2917 private void handleFrozenUids(int[] uids, int[] frozenStates) {
2918 final ArraySet<Range<Integer>> ranges = new ArraySet<>();
2919
2920 for (int i = 0; i < uids.length; i++) {
2921 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
2922 Integer uidAsInteger = Integer.valueOf(uids[i]);
2923 ranges.add(new Range(uidAsInteger, uidAsInteger));
2924 }
2925 }
2926
2927 if (!ranges.isEmpty()) {
2928 final Set<Integer> exemptUids = new ArraySet<>();
2929 try {
2930 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
2931 } catch (Exception e) {
2932 loge("Exception in socket destroy: " + e);
2933 }
2934 }
2935 }
2936
2937 @VisibleForTesting
2938 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
2939
Paul Jensen83f5d572014-08-29 09:54:01 -04002940 private void enforceInternetPermission() {
2941 mContext.enforceCallingOrSelfPermission(
2942 android.Manifest.permission.INTERNET,
2943 "ConnectivityService");
2944 }
2945
The Android Open Source Project28527d22009-03-03 19:31:44 -08002946 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002947 mContext.enforceCallingOrSelfPermission(
2948 android.Manifest.permission.ACCESS_NETWORK_STATE,
2949 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002950 }
2951
lucaslinc582d502022-01-27 09:07:00 +08002952 private boolean checkAccessPermission(int pid, int uid) {
2953 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
2954 == PERMISSION_GRANTED;
2955 }
2956
paulhua6ee2122021-02-22 15:40:43 +08002957 /**
2958 * Performs a strict and comprehensive check of whether a calling package is allowed to
2959 * change the state of network, as the condition differs for pre-M, M+, and
2960 * privileged/preinstalled apps. The caller is expected to have either the
2961 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2962 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2963 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2964 * permission and cannot be revoked. See http://b/23597341
2965 *
2966 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2967 * of this app will be updated to the current time.
2968 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002969 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002970 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2971 == PackageManager.PERMISSION_GRANTED) {
2972 return;
2973 }
2974
2975 if (callingPkg == null) {
2976 throw new SecurityException("Calling package name is null.");
2977 }
2978
2979 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2980 final int uid = mDeps.getCallingUid();
2981 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2982 callingPkg, callingAttributionTag, null /* message */);
2983
2984 if (mode == AppOpsManager.MODE_ALLOWED) {
2985 return;
2986 }
2987
2988 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2989 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2990 return;
2991 }
2992
2993 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2994 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2995 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002996 }
2997
Charles He9369e612017-05-15 17:07:18 +01002998 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002999 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003000 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003001 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003002 }
3003
Quang Luong98858d62023-02-11 00:25:24 +00003004 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003005 enforceAnyPermissionOf(mContext,
3006 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003007 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003008 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3009 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3010 }
3011
paulhu8e96a752019-08-12 16:25:11 +08003012 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003013 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003014 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003015 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003016 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003017 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003018 }
3019
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003020 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003021 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003022 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003023 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003024 android.Manifest.permission.NETWORK_SETTINGS,
3025 android.Manifest.permission.NETWORK_FACTORY,
3026 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3027 }
3028
3029 private void enforceNetworkFactoryOrTestNetworksPermission() {
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,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003033 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3034 android.Manifest.permission.NETWORK_FACTORY,
3035 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3036 }
3037
lucaslin69e1aa92022-03-22 18:15:09 +08003038 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3039 return PERMISSION_GRANTED == mContext.checkPermission(
3040 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3041 || PERMISSION_GRANTED == mContext.checkPermission(
3042 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3043 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003044 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003045 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003046 }
3047
Chalard Jean9a396cc2018-02-21 18:43:54 +09003048 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003049 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003050 android.Manifest.permission.NETWORK_SETTINGS,
3051 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003052 }
3053
3054 private boolean checkSettingsPermission(int pid, int uid) {
3055 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003056 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3057 || PERMISSION_GRANTED == mContext.checkPermission(
3058 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003059 }
3060
paulhu8e96a752019-08-12 16:25:11 +08003061 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003062 enforceNetworkStackPermissionOr(mContext,
3063 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003064 }
3065
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003066 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003067 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003068 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003069 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003070 }
3071
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003072 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003073 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003074 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3075 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003076 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003077 }
3078
James Mattis8378aec2021-01-26 14:05:36 -08003079 private void enforceOemNetworkPreferencesPermission() {
3080 mContext.enforceCallingOrSelfPermission(
3081 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3082 "ConnectivityService");
3083 }
3084
James Mattisfa270db2021-05-31 17:11:10 -07003085 private void enforceManageTestNetworksPermission() {
3086 mContext.enforceCallingOrSelfPermission(
3087 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3088 "ConnectivityService");
3089 }
3090
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003091 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003092 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003093 android.Manifest.permission.NETWORK_STACK,
3094 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003095 }
3096
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003097 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003098 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003099 android.Manifest.permission.NETWORK_STACK,
3100 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3101 }
3102
paulhu1a407652019-03-22 16:35:06 +08003103 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003104 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003105 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003106 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3107 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003108 }
3109
Paul Hu8fc2a552022-05-04 18:44:42 +08003110 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3111 boolean checkUidsAllowedList) {
3112 if (PermissionUtils.checkAnyPermissionOf(mContext,
3113 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3114 return true;
3115 }
3116
3117 // fallback to ConnectivityInternalPermission
3118 // TODO: Remove this fallback check after all apps have declared
3119 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3120 if (PermissionUtils.checkAnyPermissionOf(mContext,
3121 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3122 return true;
3123 }
3124
3125 // Check whether uid is in allowed on restricted networks list.
3126 if (checkUidsAllowedList
3127 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3128 return true;
3129 }
3130 return false;
3131 }
3132
3133 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3134 final int callingUid = mDeps.getCallingUid();
3135 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3136 throw new SecurityException("ConnectivityService: user " + callingUid
3137 + " has no permission to access restricted network.");
3138 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003139 }
3140
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003141 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003142 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003143 }
3144
Roshan Pius98f59ec2021-02-23 08:47:39 -08003145 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3146 return PERMISSION_GRANTED == mContext.checkPermission(
3147 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3148 }
3149
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003150 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003151 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003152 }
3153
3154 private void sendInetConditionBroadcast(NetworkInfo info) {
3155 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3156 }
3157
Wink Saville4f0de1e2011-08-04 15:01:58 -07003158 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003159 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003160 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003161 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003162 if (info.isFailover()) {
3163 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3164 info.setFailover(false);
3165 }
3166 if (info.getReason() != null) {
3167 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3168 }
3169 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003170 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3171 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003172 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003173 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003174 return intent;
3175 }
3176
3177 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3178 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3179 }
3180
Michael Groover73f69482023-01-27 11:01:25 -06003181 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3182 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003183 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3184 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003185 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003186 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003187 if (!mSystemReady
3188 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003189 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003190 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003191 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003192 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003193 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003194 }
3195
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003196 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003197 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003198 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003199 final NetworkInfo ni = intent.getParcelableExtra(
3200 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003201 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3202 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003203 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003204 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003205 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003206 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003207 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003208 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003209 } finally {
3210 Binder.restoreCallingIdentity(ident);
3211 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003212 }
3213 }
3214
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003215 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3216 NetworkInfo info) {
3217 // Delivery group policy APIs are only available on U+.
3218 if (!SdkLevel.isAtLeastU()) return;
3219
3220 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3221 try {
3222 // This allows us to discard older broadcasts still waiting to be delivered
3223 // which have the same namespace and key.
3224 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3225 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3226 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003227 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003228 } catch (UnsupportedApiLevelException e) {
3229 Log.wtf(TAG, "Using unsupported API" + e);
3230 }
3231 }
3232
3233 @VisibleForTesting
3234 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3235 final StringBuilder sb = new StringBuilder();
3236 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3237 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3238 sb.append(info.getExtraInfo());
3239 return sb.toString();
3240 }
3241
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003242 /**
Aaron Huang96011892020-06-27 07:18:23 +08003243 * Called by SystemServer through ConnectivityManager when the system is ready.
3244 */
3245 @Override
3246 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003247 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003248 throw new SecurityException("Calling Uid is not system uid.");
3249 }
3250 systemReadyInternal();
3251 }
3252
3253 /**
3254 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003255 */
3256 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003257 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003258 // Load flags after PackageManager is ready to query module version
3259 mFlags.loadFlags(mDeps, mContext);
3260
Aaron Huang9a57acf2020-12-08 10:03:29 +08003261 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3262 // listening network request which is sent by MultipathPolicyTracker won't be added
3263 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3264 // be called after PermissionMonitor#startMonitoring().
3265 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3266 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3267 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003268 final ConditionVariable startMonitoringDone = new ConditionVariable();
3269 mHandler.post(() -> {
3270 mPermissionMonitor.startMonitoring();
3271 startMonitoringDone.open();
3272 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003273 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003274 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003275
Hugo Benichie5220992017-04-26 14:53:28 +09003276 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003277 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003278 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003279 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003280 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003281 }
3282 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003283
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003284 // Create network requests for always-on networks.
3285 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003286
3287 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003288 // Note that updating can be skipped here if the list is empty only because no uid
3289 // rules are applied before system ready. Normally, the empty uid list means to clear
3290 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003291 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3292 updateMobileDataPreferredUids();
3293 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003294
3295 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
3296 if (SdkLevel.isAtLeastT()) {
3297 mBpfNetMaps.setPullAtomCallback(mContext);
3298 }
Paul Hu3c8c8102022-08-25 07:06:16 +00003299 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3300 // have permission problem. While CV#block() is unbounded in time and can in principle block
3301 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3302 // could have blocked forever too.
3303 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003304 }
3305
The Android Open Source Project28527d22009-03-03 19:31:44 -08003306 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003307 * Start listening for default data network activity state changes.
3308 */
3309 @Override
3310 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003311 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003312 }
3313
3314 /**
3315 * Stop listening for default data network activity state changes.
3316 */
3317 @Override
3318 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003319 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003320 }
3321
3322 /**
3323 * Check whether the default network radio is currently active.
3324 */
3325 @Override
3326 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003327 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003328 }
3329
3330 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003331 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003332 * and set it on it's iface.
3333 */
Junyu Lai970963e2022-10-25 15:46:47 +08003334 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003335 final String iface = newLp.getInterfaceName();
3336 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003337 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003338 // Silently ignore unset MTU value.
3339 return;
3340 }
Hansen Kurli04252032022-12-07 11:21:49 +00003341 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3342 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3343 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003344 return;
3345 }
Hansen Kurli04252032022-12-07 11:21:49 +00003346 // Cannot set MTU without interface name
3347 if (TextUtils.isEmpty(iface)) {
3348 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003349 return;
3350 }
sy.yun4aa73922013-09-02 05:24:09 +09003351
Hansen Kurli04252032022-12-07 11:21:49 +00003352 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3353 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003354 return;
3355 }
3356
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003357 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003358 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003359 mNetd.interfaceSetMtu(iface, mtu);
3360 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003361 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003362 }
3363 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003364
Chenbo Feng15416292018-11-08 17:36:21 -08003365 @VisibleForTesting
3366 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003367
Junyu Lai970963e2022-10-25 15:46:47 +08003368 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003369 String[] values = null;
3370 if (tcpBufferSizes != null) {
3371 values = tcpBufferSizes.split(",");
3372 }
3373
3374 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003375 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003376 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3377 values = tcpBufferSizes.split(",");
3378 }
3379
3380 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3381
3382 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003383 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003384
Chenbo Feng15416292018-11-08 17:36:21 -08003385 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3386 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3387 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003388 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003389 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003390 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003391 }
3392 }
3393
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003394 @Override
3395 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003396 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003397 NETWORK_RESTORE_DELAY_PROP_NAME);
3398 if(restoreDefaultNetworkDelayStr != null &&
3399 restoreDefaultNetworkDelayStr.length() != 0) {
3400 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003401 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003402 } catch (NumberFormatException e) {
3403 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003404 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003405 // if the system property isn't set, use the value for the apn type
3406 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3407
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003408 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3409 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003410 }
3411 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003412 }
3413
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003414 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003415 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003416 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003417 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003418 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003419 // Start gathering diagnostic information.
3420 netDiags.add(new NetworkDiagnostics(
3421 nai.network,
3422 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003423 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003424 DIAG_TIME_MS));
3425 }
3426
3427 for (NetworkDiagnostics netDiag : netDiags) {
3428 pw.println();
3429 netDiag.waitForMeasurements();
3430 netDiag.dump(pw);
3431 }
3432 }
3433
The Android Open Source Project28527d22009-03-03 19:31:44 -08003434 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003435 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3436 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003437 if (!checkDumpPermission(mContext, TAG, writer)) return;
3438
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003439 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003440 }
3441
lucaslin99473f62020-12-10 15:10:54 +08003442 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3443 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3444 != PackageManager.PERMISSION_GRANTED) {
3445 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003446 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003447 + " due to missing android.permission.DUMP permission");
3448 return false;
3449 } else {
3450 return true;
3451 }
3452 }
3453
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003454 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003455 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003456
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003457 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003458 dumpNetworkDiagnostics(pw);
3459 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003460 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003461 dumpNetworks(pw);
3462 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003463 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003464 dumpNetworkRequests(pw);
3465 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003466 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3467 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3468 dumpTrafficController(pw, fd, verbose);
3469 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003470 }
Erik Kline9647f382015-06-05 17:47:34 +09003471
Junyu Lai0da479b2022-04-20 15:06:29 +08003472 pw.println("NetworkProviders for:");
3473 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003474 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003475 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003476 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003477 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003478 pw.println();
3479
Chalard Jean5b409c72021-02-04 13:12:59 +09003480 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003481 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003482 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003483 pw.println("none");
3484 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003485 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003486 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003487 pw.println();
3488
James Mattis8b298a02021-06-01 22:34:04 -07003489 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003490 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003491 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003492 pw.decreaseIndent();
3493 pw.println();
3494
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003495 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003496 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003497 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003498 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003499 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003500
junyulaif2c67e42018-08-07 19:50:45 +08003501 pw.println("Status for known UIDs:");
3502 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003503 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003504 for (int i = 0; i < size; i++) {
3505 // Don't crash if the array is modified while dumping in bugreports.
3506 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003507 final int uid = mUidBlockedReasons.keyAt(i);
3508 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3509 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003510 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003511 } catch (ArrayIndexOutOfBoundsException e) {
3512 pw.println(" ArrayIndexOutOfBoundsException");
3513 } catch (ConcurrentModificationException e) {
3514 pw.println(" ConcurrentModificationException");
3515 }
3516 }
3517 pw.println();
3518 pw.decreaseIndent();
3519
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003520 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003521 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003522 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003523 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003524 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003525
Junyu Lai0da479b2022-04-20 15:06:29 +08003526 pw.println("Network Offers:");
3527 pw.increaseIndent();
3528 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3529 pw.println(offerInfo.offer);
3530 }
3531 pw.decreaseIndent();
3532 pw.println();
3533
Robert Greenwalt94e22142014-07-30 16:31:24 -07003534 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003535
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003536 pw.println();
markchien5e866652019-09-30 14:40:57 +08003537 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003538
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003539 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003540 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003541
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003542 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003543
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003544 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003545 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003546 pw.println("mNetworkRequestInfoLogs (most recent first):");
3547 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003548 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003549 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003550
3551 pw.println();
3552 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3553 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003554 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003555 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003556
3557 pw.println();
3558 pw.println("NetTransition WakeLock activity (most recent first):");
3559 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003560 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3561 pw.println("total releases: " + mTotalWakelockReleases);
3562 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3563 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3564 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3565 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3566 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3567 }
James Mattiscb1e0362021-04-06 17:07:42 -07003568 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003569
3570 pw.println();
3571 pw.println("bandwidth update requests (by uid):");
3572 pw.increaseIndent();
3573 synchronized (mBandwidthRequests) {
3574 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3575 pw.println("[" + mBandwidthRequests.keyAt(i)
3576 + "]: " + mBandwidthRequests.valueAt(i));
3577 }
3578 }
3579 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003580 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003581
James Mattiscb1e0362021-04-06 17:07:42 -07003582 pw.println();
3583 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3584 pw.increaseIndent();
3585 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003586 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003587 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003588
3589 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003590
3591 pw.println();
3592 pw.println("Permission Monitor:");
3593 pw.increaseIndent();
3594 mPermissionMonitor.dump(pw);
3595 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003596
3597 pw.println();
3598 pw.println("Legacy network activity:");
3599 pw.increaseIndent();
3600 mNetworkActivityTracker.dump(pw);
3601 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003602 }
3603
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003604 private void dumpNetworks(IndentingPrintWriter pw) {
3605 for (NetworkAgentInfo nai : networksSortedById()) {
3606 pw.println(nai.toString());
3607 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003608 pw.println("Nat464Xlat:");
3609 pw.increaseIndent();
3610 nai.dumpNat464Xlat(pw);
3611 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003612 pw.println(String.format(
3613 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3614 nai.numForegroundNetworkRequests(),
3615 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3616 nai.numBackgroundNetworkRequests(),
3617 nai.numNetworkRequests()));
3618 pw.increaseIndent();
3619 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3620 pw.println(nai.requestAt(i).toString());
3621 }
3622 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003623 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003624 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003625 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003626 pw.decreaseIndent();
3627 pw.decreaseIndent();
3628 }
3629 }
3630
James Mattis8b298a02021-06-01 22:34:04 -07003631 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3632 if (!mProfileNetworkPreferences.isEmpty()) {
3633 pw.println("Profile preferences:");
3634 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09003635 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07003636 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003637 }
James Mattis8b298a02021-06-01 22:34:04 -07003638 if (!mOemNetworkPreferences.isEmpty()) {
3639 pw.println("OEM preferences:");
3640 pw.increaseIndent();
3641 pw.println(mOemNetworkPreferences);
3642 pw.decreaseIndent();
3643 }
3644 if (!mMobileDataPreferredUids.isEmpty()) {
3645 pw.println("Mobile data preferred UIDs:");
3646 pw.increaseIndent();
3647 pw.println(mMobileDataPreferredUids);
3648 pw.decreaseIndent();
3649 }
James Mattis45d81842021-01-10 14:24:24 -08003650
James Mattis8b298a02021-06-01 22:34:04 -07003651 pw.println("Default requests:");
3652 pw.increaseIndent();
3653 dumpPerAppDefaultRequests(pw);
3654 pw.decreaseIndent();
3655 }
3656
3657 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003658 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3659 if (mDefaultRequest == defaultRequest) {
3660 continue;
3661 }
3662
James Mattis8b298a02021-06-01 22:34:04 -07003663 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3664 final String networkOutput;
3665 if (null == satisfier) {
3666 networkOutput = "null";
3667 } else if (mNoServiceNetwork.equals(satisfier)) {
3668 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003669 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003670 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003671 }
James Mattis8b298a02021-06-01 22:34:04 -07003672 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3673 ? "" : " asUid: " + defaultRequest.mAsUid;
3674 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3675 + defaultRequest.mPid + asUidString + "]";
3676 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3677 + " Preference order: " + defaultRequest.mPreferenceOrder
3678 + " Tracked UIDs: " + defaultRequest.getUids();
3679 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003680 }
3681 }
3682
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003683 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003684 NetworkRequestInfo[] infos = null;
3685 while (infos == null) {
3686 try {
3687 infos = requestsSortedById();
3688 } catch (ConcurrentModificationException e) {
3689 // mNetworkRequests should only be accessed from handler thread, except dump().
3690 // As dump() is never called in normal usage, it would be needlessly expensive
3691 // to lock the collection only for its benefit. Instead, retry getting the
3692 // requests if ConcurrentModificationException is thrown during dump().
3693 }
3694 }
3695 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003696 pw.println(nri.toString());
3697 }
3698 }
3699
Ken Chene6d511f2022-01-25 11:10:42 +08003700 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
3701 boolean verbose) {
3702 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09003703 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08003704 } catch (ServiceSpecificException e) {
3705 pw.println(e.getMessage());
3706 } catch (IOException e) {
3707 loge("Dump BPF maps failed, " + e);
3708 }
3709 }
3710
Chalard Jean524f0b12021-10-25 21:11:56 +09003711 private void dumpAllRequestInfoLogsToLogcat() {
3712 try (PrintWriter logPw = new PrintWriter(new Writer() {
3713 @Override
3714 public void write(final char[] cbuf, final int off, final int len) {
3715 // This method is called with 0-length and 1-length arrays for empty strings
3716 // or strings containing only the DEL character.
3717 if (len <= 1) return;
3718 Log.e(TAG, new String(cbuf, off, len));
3719 }
3720 @Override public void flush() {}
3721 @Override public void close() {}
3722 })) {
3723 mNetworkRequestInfoLogs.dump(logPw);
3724 }
3725 }
3726
Hugo Benichia480ba52018-09-03 08:19:02 +09003727 /**
3728 * Return an array of all current NetworkAgentInfos sorted by network id.
3729 */
3730 private NetworkAgentInfo[] networksSortedById() {
3731 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003732 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003733 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003734 return networks;
3735 }
3736
3737 /**
3738 * Return an array of all current NetworkRequest sorted by request id.
3739 */
James Mattis258ea3c2020-11-15 15:04:40 -08003740 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003741 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003742 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003743 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003744 // Sort the array based off the NRI containing the min requestId in its requests.
3745 Arrays.sort(requests,
3746 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3747 Comparator.comparingInt(req -> req.requestId)).requestId
3748 )
3749 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003750 return requests;
3751 }
3752
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003753 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003754 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003755 if (officialNai != null && officialNai.equals(nai)) return true;
3756 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003757 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003758 " - " + nai);
3759 }
3760 return false;
3761 }
3762
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003763 private boolean isDisconnectRequest(Message msg) {
3764 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
3765 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
3766 return info.getState() == NetworkInfo.State.DISCONNECTED;
3767 }
3768
Robert Greenwalt2034b912009-08-12 16:08:25 -07003769 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003770 private class NetworkStateTrackerHandler extends Handler {
3771 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003772 super(looper);
3773 }
3774
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003775 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003776 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3777 final NetworkAgentInfo nai = arg.first;
3778 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003779 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003780 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003781 }
3782 return;
3783 }
3784
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003785 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003786 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003787 return;
3788 }
3789
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003790 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003791 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09003792 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
3793 final NetworkCapabilities sanitized =
3794 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09003795 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003796 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003797 break;
3798 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003799 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003800 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003801 processLinkPropertiesFromAgent(nai, newLp);
3802 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003803 break;
3804 }
3805 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003806 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003807 updateNetworkInfo(nai, info);
3808 break;
3809 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003810 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003811 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003812 break;
3813 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003814 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09003815 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003816 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003817 // Note that if the NAI had been connected, this would affect the
3818 // score, and therefore would require re-mixing the score and performing
3819 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003820 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003821 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3822 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003823 // Mark the network as temporarily accepting partial connectivity so that it
3824 // will be validated (and possibly become default) even if it only provides
3825 // partial internet access. Note that if user connects to partial connectivity
3826 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3827 // out of wifi coverage) and if the same wifi is available again, the device
3828 // will auto connect to this wifi even though the wifi has "no internet".
3829 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003830 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003831 break;
3832 }
junyulai011b1f12019-01-03 18:50:15 +08003833 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003834 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003835 break;
3836 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003837 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003838 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003839 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003840
3841 if (isLegacyLockdownNai(nai)
3842 && (underlying == null || underlying.size() != 1)) {
3843 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3844 + " must have exactly one underlying network: " + underlying);
3845 }
3846
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003847 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3848 nai.declaredUnderlyingNetworks = (underlying != null)
3849 ? underlying.toArray(new Network[0]) : null;
3850
3851 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3852 if (DBG) {
3853 log(nai.toShortString() + " changed underlying networks to "
3854 + Arrays.toString(nai.declaredUnderlyingNetworks));
3855 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003856 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003857 notifyIfacesChangedForNetworkStats();
3858 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003859 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003860 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003861 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3862 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3863 nai.teardownDelayMs = msg.arg1;
3864 } else {
3865 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3866 }
Chalard Jean550b5212021-03-05 23:07:53 +09003867 break;
3868 }
3869 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3870 nai.setLingerDuration((int) arg.second);
3871 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003872 }
Tyler Wear72388212021-09-09 14:49:02 -07003873 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3874 DscpPolicy policy = (DscpPolicy) arg.second;
3875 if (mDscpPolicyTracker != null) {
3876 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3877 }
3878 break;
3879 }
3880 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3881 if (mDscpPolicyTracker != null) {
3882 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3883 }
3884 break;
3885 }
3886 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3887 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08003888 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07003889 }
3890 break;
3891 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09003892 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09003893 if (!nai.everConnected()) {
3894 Log.d(TAG, "unregisterAfterReplacement on never-connected "
3895 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09003896 teardownUnneededNetwork(nai);
3897 break;
3898 }
3899
3900 if (nai.isDestroyed()) {
3901 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
3902 + ", ignoring");
3903 break;
3904 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003905
3906 final int timeoutMs = (int) arg.second;
3907 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3908 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
3909 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
3910 }
3911
3912 // Marking a network awaiting replacement is used to ensure that any requests
3913 // satisfied by the network do not switch to another network until a
3914 // replacement is available or the wait for a replacement times out.
3915 // If the network is inactive (i.e., nascent or lingering), then there are no
3916 // such requests, and there is no point keeping it. Just tear it down.
3917 // Note that setLingerDuration(0) cannot be used to do this because the network
3918 // could be nascent.
3919 nai.clearInactivityState();
3920 if (unneeded(nai, UnneededFor.TEARDOWN)) {
3921 Log.d(TAG, nai.toShortString()
3922 + " marked awaiting replacement is unneeded, tearing down instead");
3923 teardownUnneededNetwork(nai);
3924 break;
3925 }
3926
3927 Log.d(TAG, "Marking " + nai.toShortString()
3928 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
3929 destroyNativeNetwork(nai);
3930
3931 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
3932 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
3933 // consider the fact that the network could already have disconnected or been
3934 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
3935 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
3936 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
3937 mKeepaliveTracker.handleStopAllKeepalives(nai,
3938 SocketKeepalive.ERROR_INVALID_NETWORK);
3939
3940 nai.updateScoreForNetworkAgentUpdate();
3941 // This rematch is almost certainly not going to result in any changes, because
3942 // the destroyed flag is only just above the "current satisfier wins"
3943 // tie-breaker. But technically anything that affects scoring should rematch.
3944 rematchAllNetworksAndRequests();
3945 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
3946 break;
3947 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003948 }
3949 }
3950
3951 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003952 final int netId = msg.arg2;
3953 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003954 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09003955 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003956 switch (msg.what) {
3957 default:
3958 return false;
lucasline117e2e2019-10-22 18:27:33 +08003959 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08003960 if (nai == null) {
3961 break;
3962 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003963 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
3964 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08003965 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003966 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08003967 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003968 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08003969 if (probePrivateDnsCompleted) {
3970 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3971 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003972 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003973 }
3974 // Only show the notification when the private DNS is broken and the
3975 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003976 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003977 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3978 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003979 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003980 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3981 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3982 // private DNS is broken, it means this network is being reevaluated.
3983 // Either probing private DNS is not necessary any more or it hasn't been
3984 // done yet. In either case, the networkCapabilities should be updated to
3985 // reflect the new status.
3986 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003987 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003988 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003989 }
3990 break;
3991 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003992 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003993 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3994
Erik Kline31b4a9e2018-01-11 21:07:29 +09003995 if (nai == null) break;
3996
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003997 handleNetworkTested(nai, results.mTestResult,
3998 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003999 break;
4000 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004001 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004002 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004003 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004004 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004005 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004006 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004007 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4008 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004009 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004010 if (nai == null) {
4011 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4012 break;
4013 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004014 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004015 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004016 (PendingIntent) msg.obj,
4017 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004018 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004019 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004020 break;
4021 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004022 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004023 if (nai == null) break;
4024
Erik Kline9a62f012018-03-21 07:18:33 -07004025 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004026 break;
4027 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004028 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004029 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004030 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004031 break;
4032 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004033 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004034 return true;
4035 }
4036
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004037 private void handleNetworkTested(
4038 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004039 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4040 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004041 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004042
4043 // If there is any kind of working networking, then the NAI has been evaluated
4044 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4045 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004046 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004047 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004048 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4049 // any callback that receives onAvailable for that rematch receives an extra caps
4050 // callback. To prevent that, update the score in the agent so the updates below won't
4051 // see an update to both caps and score at the same time.
4052 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004053 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4054
he_won.hwang881307a2022-03-15 21:23:52 +09004055 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4056 // Assume the validation failure is due to a temporary failure after roaming
4057 // and ignore it. NetworkMonitor will continue to retry validation. If it
4058 // continues to fail after the block timeout expires, the network will be
4059 // marked unvalidated. If it succeeds, then validation state will not change.
4060 return;
4061 }
4062
Chalard Jean254bd162022-08-25 13:04:51 +09004063 final boolean wasValidated = nai.isValidated();
4064 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004065 final boolean wasPortal = nai.captivePortalDetected();
4066 nai.setPartialConnectivity(partial);
4067 nai.setCaptivePortalDetected(portal);
4068 nai.updateScoreForNetworkAgentUpdate();
4069 final boolean partialConnectivityChanged = (wasPartial != partial);
4070 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004071
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004072 if (DBG) {
4073 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4074 ? " with redirect to " + redirectUrl
4075 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004076 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004077 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004078 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004079 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004080 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004081 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004082 if (valid) {
4083 handleFreshlyValidatedNetwork(nai);
4084 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4085 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004086 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004087 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004088 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004089 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004090 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004091 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004092 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004093 NotificationType.PRIVATE_DNS_BROKEN);
4094 // If network becomes valid, the hasShownBroken should be reset for
4095 // that network so that the notification will be fired when the private
4096 // DNS is broken again.
4097 nai.networkAgentConfig.hasShownBroken = false;
4098 }
4099 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004100 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004101 } else if (portalChanged) {
4102 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
4103 == getCaptivePortalMode()) {
4104 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4105 nai.onPreventAutomaticReconnect();
4106 teardownUnneededNetwork(nai);
4107 return;
4108 } else {
4109 updateCapabilitiesForNetwork(nai);
4110 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004111 } else if (becameEvaluated) {
4112 // If valid or partial connectivity changed, updateCapabilities* has
4113 // done the rematch.
4114 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004115 }
4116 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004117
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004118 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004119 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004120 nai.onValidationStatusChanged(
4121 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4122 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004123
4124 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004125 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004126 // immediately. Re-notify partial connectivity silently if no internet
4127 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004128 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004129 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004130 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4131 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004132 }
4133
Chalard Jean254bd162022-08-25 13:04:51 +09004134 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004135 handleNetworkUnvalidated(nai);
4136 }
4137 }
4138
Calvin Ondada1452016-10-11 15:10:46 -07004139 private int getCaptivePortalMode() {
4140 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004141 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4142 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004143 }
4144
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004145 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4146 switch (msg.what) {
4147 default:
4148 return false;
4149 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4150 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4151 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4152 handleLingerComplete(nai);
4153 }
4154 break;
4155 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004156 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4157 handleNetworkAgentRegistered(msg);
4158 break;
4159 }
4160 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4161 handleNetworkAgentDisconnected(msg);
4162 break;
4163 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004164 }
4165 return true;
4166 }
4167
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004168 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004169 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004170 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004171 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004172 maybeHandleNetworkAgentMessage(msg);
4173 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004174 }
4175 }
4176
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004177 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004178 private final int mNetId;
4179 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004180
4181 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004182 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004183 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004184 }
4185
4186 @Override
4187 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4188 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004189 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004190 }
4191
4192 @Override
4193 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004194 // Legacy version of notifyNetworkTestedWithExtras.
4195 // Would only be called if the system has a NetworkStack module older than the
4196 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004197 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004198 }
4199
4200 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004201 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004202 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4203 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004204 final Message msg = mTrackerHandler.obtainMessage(
4205 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004206 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004207 new NetworkTestedResults(
4208 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004209 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004210
4211 // Invoke ConnectivityReport generation for this Network test event.
4212 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4213 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004214
Cody Kestingf1120be2020-08-03 18:01:40 -07004215 // NetworkMonitor reports the network validation result as a bitmask while
4216 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4217 // logical value for ConnectivityDiagnostics.
4218 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4219 p.result);
4220
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004221 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004222 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004223 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4224 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4225
Aaron Huang959d3642021-01-21 15:47:41 +08004226 ConnectivityReportEvent reportEvent =
4227 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4228 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004229 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004230 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004231 }
4232
4233 @Override
4234 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4235 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4236 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004237 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004238 }
4239
4240 @Override
lucasline117e2e2019-10-22 18:27:33 +08004241 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4242 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4243 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004244 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004245 }
4246
4247 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004248 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4249 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4250 EVENT_CAPPORT_DATA_CHANGED,
4251 0, mNetId, data));
4252 }
4253
4254 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004255 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004256 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004257 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004258
4259 final PendingIntent pendingIntent;
4260 // Only the system server can register notifications with package "android"
4261 final long token = Binder.clearCallingIdentity();
4262 try {
paulhu7746e4e2020-06-09 19:07:03 +08004263 pendingIntent = PendingIntent.getBroadcast(
4264 mContext,
4265 0 /* requestCode */,
4266 intent,
4267 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004268 } finally {
4269 Binder.restoreCallingIdentity(token);
4270 }
4271 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4272 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004273 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004274 }
4275
4276 @Override
4277 public void hideProvisioningNotification() {
4278 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004279 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004280 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004281
4282 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004283 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004284 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004285 }
4286
4287 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004288 public int getInterfaceVersion() {
4289 return this.VERSION;
4290 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004291
4292 @Override
4293 public String getInterfaceHash() {
4294 return this.HASH;
4295 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004296 }
4297
Cody Kestingf1120be2020-08-03 18:01:40 -07004298 /**
4299 * Converts the given NetworkMonitor-specific validation result bitmask to a
4300 * ConnectivityDiagnostics-specific validation result int.
4301 */
4302 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4303 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4304 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4305 }
4306 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4307 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4308 }
4309 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4310 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4311 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4312 }
4313
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004314 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004315 log("Data stall detected with methods: " + p.detectionMethod);
4316
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004317 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004318 int detectionMethod = 0;
4319 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4320 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4321 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4322 }
4323 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4324 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4325 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4326 p.tcpMetricsCollectionPeriodMillis);
4327 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004328 }
4329
Cody Kestingf53a0752020-04-15 12:33:28 -07004330 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004331 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004332 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004333
4334 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4335 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4336 // the cost of going through two handlers.
4337 mConnectivityDiagnosticsHandler.sendMessage(msg);
4338 }
4339
Cody Kestingb37958e2020-05-15 10:36:01 -07004340 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4341 return (p.detectionMethod & detectionMethod) != 0;
4342 }
4343
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004344 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4345 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004346 }
4347
Erik Klinea73af002018-06-26 18:53:43 +09004348 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4349 if (nai == null) return;
4350 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4351 // in order to restart a validation pass from within netd.
4352 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4353 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004354 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004355 }
4356 }
4357
Erik Kline31b4a9e2018-01-11 21:07:29 +09004358 private void handlePrivateDnsSettingsChanged() {
4359 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4360
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004361 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004362 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004363 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004364 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4365 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004366 }
4367 }
4368
Erik Kline9a62f012018-03-21 07:18:33 -07004369 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4370 // Private DNS only ever applies to networks that might provide
4371 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004372 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004373
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004374 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004375 // schedule DNS resolutions. If a DNS resolution is required the
4376 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004377 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004378
4379 // With Private DNS bypass support, we can proceed to update the
4380 // Private DNS config immediately, even if we're in strict mode
4381 // and have not yet resolved the provider name into a set of IPs.
4382 updatePrivateDns(nai, cfg);
4383 }
4384
4385 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4386 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004387 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004388 }
4389
dalyk1720e542018-03-05 12:42:22 -05004390 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4391 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4392 if (nai == null) {
4393 return;
4394 }
4395 mDnsManager.updatePrivateDnsValidation(update);
4396 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4397 }
4398
paulhu7c0a2e62021-01-08 00:51:49 +08004399 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004400 int prefixLength) {
4401 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4402 if (nai == null) return;
4403
paulhu7c0a2e62021-01-08 00:51:49 +08004404 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4405 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004406
4407 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004408 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004409 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004410 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004411 prefixLength);
4412 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004413 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004414 return;
4415 }
4416 }
4417
Lorenzo Colittid523d142020-04-01 20:16:30 +09004418 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004419 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4420 }
4421
Hai Shalome58bdc62021-01-11 18:45:34 -08004422 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004423 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004424 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004425 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4426 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4427 }
4428
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004429 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004430 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004431 * @param nai the agent info to update
4432 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004433 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004434 */
junyulai2b6f0c22021-02-03 20:15:30 +08004435 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4436 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4437 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004438 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004439 // one lingered request, set inactive.
4440 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004441 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004442 if (DBG) log("Unsetting inactive " + nai.toShortString());
4443 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004444 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004445 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004446 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004447 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4448 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004449 }
junyulai2b6f0c22021-02-03 20:15:30 +08004450 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004451 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004452 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004453 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004454 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004455 }
4456
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004457 private void handleNetworkAgentRegistered(Message msg) {
4458 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4459 if (!mNetworkAgentInfos.contains(nai)) {
4460 return;
4461 }
4462
4463 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4464 if (VDBG) log("NetworkAgent registered");
4465 } else {
4466 loge("Error connecting NetworkAgent");
4467 mNetworkAgentInfos.remove(nai);
4468 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004469 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004470 synchronized (mNetworkForNetId) {
4471 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004472 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004473 mNetIdManager.releaseNetId(nai.network.getNetId());
4474 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004475 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004476 }
4477 }
4478 }
Paul Jensend5f53392014-11-25 15:26:53 -05004479
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004480 @VisibleForTesting
4481 protected static boolean shouldCreateNetworksImmediately() {
4482 // Before U, physical networks are only created when the agent advances to CONNECTED.
4483 // In U and above, all networks are immediately created when the agent is registered.
4484 return SdkLevel.isAtLeastU();
4485 }
4486
4487 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4488 @NonNull NetworkInfo.State state) {
4489 if (nai.isCreated()) return false;
4490 if (state == NetworkInfo.State.CONNECTED) return true;
4491 if (state != NetworkInfo.State.CONNECTING) {
4492 // TODO: throw if no WTFs are observed in the field.
4493 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4494 return false;
4495 }
4496 return nai.isVPN() || shouldCreateNetworksImmediately();
4497 }
4498
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004499 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004500 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004501 }
4502
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004503 @VisibleForTesting
4504 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004505 // T+ devices should use unregisterAfterReplacement.
he_won.hwang881307a2022-03-15 21:23:52 +09004506 if (SdkLevel.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004507
4508 // If the network never roamed, return false. The check below is not sufficient if time
4509 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4510 if (nai.lastRoamTime == 0) return false;
4511
he_won.hwang881307a2022-03-15 21:23:52 +09004512 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4513 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004514 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004515 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004516 final long currentTimeMs = SystemClock.elapsedRealtime();
4517 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004518 if (timeSinceLastRoam <= blockTimeOut) {
4519 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4520 return true;
4521 }
4522 }
4523 return false;
4524 }
4525
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004526 private void handleNetworkAgentDisconnected(Message msg) {
4527 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004528 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004529 }
4530
Chalard Jeand9fffc32018-05-11 20:19:20 +09004531 // Destroys a network, remove references to it from the internal state managed by
4532 // ConnectivityService, free its interfaces and clean up.
4533 // Must be called on the Handler thread.
4534 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004535 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004536
4537 if (!mNetworkAgentInfos.contains(nai)) return;
4538
Chalard Jeand9fffc32018-05-11 20:19:20 +09004539 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004540 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004541 }
lucaslinb25c9a62019-02-12 15:30:13 +08004542 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004543 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004544 // A network agent has disconnected.
4545 // TODO - if we move the logic to the network agent (have them disconnect
4546 // because they lost all their requests or because their score isn't good)
4547 // then they would disconnect organically, report their new state and then
4548 // disconnect the channel.
4549 if (nai.networkInfo.isConnected()) {
4550 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4551 null, null);
4552 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004553 final boolean wasDefault = isDefaultNetwork(nai);
4554 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004555 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004556 }
4557 notifyIfacesChangedForNetworkStats();
4558 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4559 // by other networks that are already connected. Perhaps that can be done by
4560 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4561 // of rematchAllNetworksAndRequests
4562 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004563 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004564
4565 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004566 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4567 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08004568 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004569 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004570 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004571 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004572 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004573 synchronized (mNetworkForNetId) {
4574 // Remove the NetworkAgent, but don't mark the netId as
4575 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004576 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004577 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004578 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08004579 // Update allowed network lists in netd. This should be called after removing nai
4580 // from mNetworkAgentInfos.
4581 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004582 // Remove all previously satisfied requests.
4583 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004584 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004585 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004586 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004587 if (currentNetwork != null
4588 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004589 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004590 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4591 // rematch not to keep disconnected agents instead of setting it here ; this
4592 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004593 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004594 for (final NetworkOfferInfo noi : mNetworkOffers) {
4595 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004596 }
James Mattise3ef1912020-12-20 11:09:58 -08004597
Chalard Jean5b409c72021-02-04 13:12:59 +09004598 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004599 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004600 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004601 // network, because while incorrect this is the closest to the old (also
4602 // incorrect) behavior.
4603 mNetworkActivityTracker.updateDataActivityTracking(
4604 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004605 ensureNetworkTransitionWakelock(nai.toShortString());
4606 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004607 }
4608 }
junyulai2b6f0c22021-02-03 20:15:30 +08004609 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004610 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004611 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004612 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004613 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004614 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004615 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004616
4617 // Immediate teardown.
4618 if (nai.teardownDelayMs == 0) {
4619 destroyNetwork(nai);
4620 return;
4621 }
4622
4623 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004624 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304625 try {
4626 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4627 } catch (RemoteException e) {
4628 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4629 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004630 }
4631 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4632 }
4633
4634 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004635 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004636 // Tell netd to clean up the configuration for this network
4637 // (routing rules, DNS, etc).
4638 // This may be slow as it requires a lot of netd shelling out to ip and
4639 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004640 // after we've rematched networks with requests (which might change the default
4641 // network or service a new request from an app), so network traffic isn't interrupted
4642 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004643 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004644 }
Chalard Jean254bd162022-08-25 13:04:51 +09004645 if (!nai.isCreated() && !SdkLevel.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004646 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4647 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4648 // false if the network was never created.
4649 // TODO: delete when S is no longer supported.
4650 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004651 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004652 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004653 }
4654
Ken Chen6df7a902021-04-09 15:08:42 +08004655 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004656 try {
4657 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004658 final NativeNetworkConfig config;
4659 if (nai.isVPN()) {
4660 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004661 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004662 return false;
4663 }
4664 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4665 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004666 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08004667 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004668 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004669 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004670 getNetworkPermission(nai.networkCapabilities),
4671 false /* secure */,
4672 VpnManager.TYPE_VPN_NONE,
4673 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08004674 }
Ken Chen6df7a902021-04-09 15:08:42 +08004675 mNetd.networkCreate(config);
4676 mDnsResolver.createNetworkCache(nai.network.getNetId());
4677 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4678 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004679 return true;
4680 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004681 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004682 return false;
4683 }
4684 }
4685
Ken Chen6df7a902021-04-09 15:08:42 +08004686 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004687 if (mDscpPolicyTracker != null) {
4688 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
4689 }
Luke Huangfdd11f82019-04-09 18:41:49 +08004690 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004691 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004692 } catch (RemoteException | ServiceSpecificException e) {
4693 loge("Exception destroying network(networkDestroy): " + e);
4694 }
4695 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004696 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004697 } catch (RemoteException | ServiceSpecificException e) {
4698 loge("Exception destroying network: " + e);
4699 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004700 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
4701 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
4702 // gets created, could add data to DnsManager data structures that will never get deleted.
4703 mDnsManager.removeNetwork(nai.network);
4704
4705 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09004706 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004707 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
4708 }
4709
Chalard Jean254bd162022-08-25 13:04:51 +09004710 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004711 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08004712 }
4713
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004714 // If this method proves to be too slow then we can maintain a separate
4715 // pendingIntent => NetworkRequestInfo map.
4716 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4717 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004718 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4719 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4720 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004721 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004722 return entry.getValue();
4723 }
4724 }
4725 return null;
4726 }
4727
Chalard Jean524f0b12021-10-25 21:11:56 +09004728 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4729 if (SdkLevel.isAtLeastT()) {
4730 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4731 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4732 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4733 // bug is fixed.
4734 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004735 throw new IllegalStateException("This NRI is already registered. New : " + nri
4736 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004737 }
4738 }
4739 }
4740 }
4741
Chalard Jeanac9ace02022-01-26 16:54:05 +09004742 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4743 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08004744 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004745 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4746 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004747 }
4748 return false;
4749 }
4750
James Mattisf7027322020-12-13 16:28:14 -08004751 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004752 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004753 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4754 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4755 final NetworkRequestInfo existingRequest =
4756 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004757 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004758 if (DBG) {
4759 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4760 + nri.mRequests.get(0) + " because their intents matched.");
4761 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004762 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004763 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004764 }
Erik Kline05f2b402015-04-30 12:58:40 +09004765 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004766 }
4767
James Mattisf7027322020-12-13 16:28:14 -08004768 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004769 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004770 }
4771
James Mattis3ce3d3c2021-02-09 18:18:28 -08004772 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004773 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004774 for (final NetworkRequestInfo nri : nris) {
4775 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004776 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004777 for (final NetworkRequest req : nri.mRequests) {
4778 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004779 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004780 if (req.isListen()) {
4781 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4782 if (req.networkCapabilities.hasSignalStrength()
4783 && network.satisfiesImmutableCapabilitiesOf(req)) {
4784 updateSignalStrengthThresholds(network, "REGISTER", req);
4785 }
James Mattisf7027322020-12-13 16:28:14 -08004786 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004787 }
4788 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004789
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004790 // If this NRI has a satisfier already, it is replacing an older request that
4791 // has been removed. Track it.
4792 final NetworkRequest activeRequest = nri.getActiveRequest();
4793 if (null != activeRequest) {
4794 // If there is an active request, then for sure there is a satisfier.
4795 nri.getSatisfier().addRequest(activeRequest);
4796 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004797 }
James Mattisf7027322020-12-13 16:28:14 -08004798
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004799 if (mFlags.noRematchAllRequestsOnRegister()) {
4800 rematchNetworksAndRequests(nris);
4801 } else {
4802 rematchAllNetworksAndRequests();
4803 }
James Mattis45d81842021-01-10 14:24:24 -08004804
Chalard Jean0354d8c2021-01-12 10:58:56 +09004805 // Requests that have not been matched to a network will not have been sent to the
4806 // providers, because the old satisfier and the new satisfier are the same (null in this
4807 // case). Send these requests to the providers.
4808 for (final NetworkRequestInfo nri : nris) {
4809 for (final NetworkOfferInfo noi : mNetworkOffers) {
4810 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004811 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004812 }
4813 }
4814
James Mattisf7027322020-12-13 16:28:14 -08004815 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4816 final int callingUid) {
4817 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004818 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004819 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4820 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4821 handleReleaseNetworkRequest(
4822 nri.mRequests.get(0),
4823 callingUid,
4824 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004825 }
4826 }
4827
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004828 // Determines whether the network is the best (or could become the best, if it validated), for
4829 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4830 // on the value of reason:
4831 //
4832 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4833 // then it should be torn down.
4834 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4835 // then it should be lingered.
4836 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004837 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004838
Chalard Jean254bd162022-08-25 13:04:51 +09004839 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09004840 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4841 return false;
4842 }
4843
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004844 final int numRequests;
4845 switch (reason) {
4846 case TEARDOWN:
4847 numRequests = nai.numRequestNetworkRequests();
4848 break;
4849 case LINGER:
4850 numRequests = nai.numForegroundNetworkRequests();
4851 break;
4852 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004853 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004854 return true;
4855 }
4856
Chalard Jean947acd42021-03-08 22:29:27 +09004857 if (numRequests > 0) return false;
4858
Paul Jensende49eb12015-06-25 15:30:08 -04004859 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004860 if (reason == UnneededFor.LINGER
4861 && !nri.isMultilayerRequest()
4862 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004863 // Background requests don't affect lingering.
4864 continue;
4865 }
4866
James Mattis3d229892020-11-16 16:46:28 -08004867 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004868 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004869 }
4870 }
Paul Jensende49eb12015-06-25 15:30:08 -04004871 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004872 }
4873
James Mattis3d229892020-11-16 16:46:28 -08004874 private boolean isNetworkPotentialSatisfier(
4875 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4876 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004877 // request, return immediately. For multilayer requests, check to see if any of the
4878 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004879 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4880 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004881 return false;
4882 }
4883 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004884 // This multilayer listen request is satisfied therefore no further requests need to be
4885 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004886 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004887 return false;
4888 }
James Mattis3d229892020-11-16 16:46:28 -08004889 // As non-multilayer listen requests have already returned, the below would only happen
4890 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004891 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004892 continue;
4893 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09004894 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08004895 // there is hope for it to become one if it validated, then it is needed.
4896 if (candidate.satisfies(req)) {
4897 // As soon as a network is found that satisfies a request, return. Specifically for
4898 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4899 // is important so as to not evaluate lower priority requests further in
4900 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004901 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4902 ? nri.getSatisfier() : null;
4903 // Note that this catches two important cases:
4904 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4905 // is currently satisfying the request. This is desirable when
4906 // cellular ends up validating but WiFi does not.
4907 // 2. Unvalidated WiFi will not be reaped when validated cellular
4908 // is currently satisfying the request. This is desirable when
4909 // WiFi ends up validating and out scoring cellular.
4910 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004911 }
4912 }
4913
4914 return false;
4915 }
4916
Erik Kline0c04b742016-07-07 16:50:58 +09004917 private NetworkRequestInfo getNriForAppRequest(
4918 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004919 // Looking up the app passed param request in mRequests isn't possible since it may return
4920 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4921 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004922 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4923 // to avoid potential race conditions when validating a package->uid mapping when sending
4924 // the callback on the very low-chance that an application shuts down prior to the callback
4925 // being sent.
4926 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4927 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004928
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004929 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004930 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004931 log(String.format("UID %d attempted to %s for unowned request %s",
4932 callingUid, requestedOperation, nri));
4933 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004934 }
Erik Kline0c04b742016-07-07 16:50:58 +09004935 }
4936
4937 return nri;
4938 }
4939
James Mattisf7027322020-12-13 16:28:14 -08004940 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4941 final String callingMethod) {
4942 if (nri.isMultilayerRequest()) {
4943 throw new IllegalStateException(
4944 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004945 }
4946 }
4947
James Mattisf7027322020-12-13 16:28:14 -08004948 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004949 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004950 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4951 // single NetworkRequest and thus does not apply to multilayer requests.
4952 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4953 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004954 return;
4955 }
James Mattis2516da32021-01-31 17:06:19 -08004956 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004957 return;
4958 }
James Mattisf7027322020-12-13 16:28:14 -08004959 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4960 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004961 }
4962 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004963 callCallbackForRequest(
4964 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004965 }
4966
James Mattisf7027322020-12-13 16:28:14 -08004967 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4968 final int callingUid,
4969 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004970 final NetworkRequestInfo nri =
4971 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4972 if (nri == null) {
4973 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004974 }
James Mattisf7027322020-12-13 16:28:14 -08004975 if (VDBG || (DBG && request.isRequest())) {
4976 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004977 }
4978 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004979 if (callOnUnavailable) {
4980 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4981 }
Erik Kline155a59a2015-11-25 12:49:38 +09004982 }
Erik Kline0c04b742016-07-07 16:50:58 +09004983
James Mattisa076c532020-12-02 14:12:41 -08004984 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004985 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004986 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004987 if (null == mNetworkRequests.remove(req)) {
4988 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4989 continue;
4990 }
James Mattisa076c532020-12-02 14:12:41 -08004991 if (req.isListen()) {
4992 removeListenRequestFromNetworks(req);
4993 }
4994 }
James Mattis8f036802021-06-20 16:26:01 -07004995 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004996 if (mDefaultNetworkRequests.remove(nri)) {
4997 // If this request was one of the defaults, then the UID rules need to be updated
4998 // WARNING : if the app(s) for which this network request is the default are doing
4999 // traffic, this will kill their connected sockets, even if an equivalent request
5000 // is going to be reinstated right away ; unconnected traffic will go on the default
5001 // until the new default is set, which will happen very soon.
5002 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5003 // remove ranges for those requests that won't have a replacement
5004 final NetworkAgentInfo satisfier = nri.getSatisfier();
5005 if (null != satisfier) {
5006 try {
paulhu0e79d952021-06-09 16:11:35 +08005007 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5008 satisfier.network.getNetId(),
5009 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005010 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005011 } catch (RemoteException e) {
5012 loge("Exception setting network preference default network", e);
5013 }
5014 }
5015 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005016
Junyu Lai00d92df2022-07-05 11:01:52 +08005017 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005018 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005019 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005020
5021 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005022 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005023 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005024 }
5025 }
5026
Chalard Jean0354d8c2021-01-12 10:58:56 +09005027 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5028 // needed for this offer.
5029 for (final NetworkOfferInfo noi : mNetworkOffers) {
5030 for (final NetworkRequest req : nri.mRequests) {
5031 if (req.isRequest() && noi.offer.neededFor(req)) {
5032 noi.offer.onNetworkUnneeded(req);
5033 }
5034 }
5035 }
James Mattisa076c532020-12-02 14:12:41 -08005036 }
5037
James Mattis3ce3d3c2021-02-09 18:18:28 -08005038 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5039 for (final NetworkRequestInfo nri : nris) {
5040 if (mDefaultRequest == nri) {
5041 // Make sure we never remove the default request.
5042 continue;
5043 }
5044 handleRemoveNetworkRequest(nri);
5045 }
5046 }
5047
James Mattisa076c532020-12-02 14:12:41 -08005048 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5049 // listens don't have a singular affected Network. Check all networks to see
5050 // if this listen request applies and remove it.
5051 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5052 nai.removeRequest(req.requestId);
5053 if (req.networkCapabilities.hasSignalStrength()
5054 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5055 updateSignalStrengthThresholds(nai, "RELEASE", req);
5056 }
5057 }
5058 }
5059
5060 /**
5061 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5062 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5063 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5064 */
5065 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5066 boolean wasKept = false;
5067 final NetworkAgentInfo nai = nri.getSatisfier();
5068 if (nai != null) {
5069 final int requestLegacyType = nri.getActiveRequest().legacyType;
5070 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5071 nai.removeRequest(nri.getActiveRequest().requestId);
5072 if (VDBG || DDBG) {
5073 log(" Removing from current network " + nai.toShortString()
5074 + ", leaving " + nai.numNetworkRequests() + " requests.");
5075 }
5076 // If there are still lingered requests on this network, don't tear it down,
5077 // but resume lingering instead.
5078 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005079 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005080 notifyNetworkLosing(nai, now);
5081 }
5082 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5083 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5084 teardownUnneededNetwork(nai);
5085 } else {
5086 wasKept = true;
5087 }
James Mattisa076c532020-12-02 14:12:41 -08005088 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5089 // Went from foreground to background.
5090 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005091 }
5092
Erik Kline0c04b742016-07-07 16:50:58 +09005093 // Maintain the illusion. When this request arrived, we might have pretended
5094 // that a network connected to serve it, even though the network was already
5095 // connected. Now that this request has gone away, we might have to pretend
5096 // that the network disconnected. LegacyTypeTracker will generate that
5097 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005098 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005099 boolean doRemove = true;
5100 if (wasKept) {
5101 // check if any of the remaining requests for this network are for the
5102 // same legacy type - if so, don't remove the nai
5103 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5104 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005105 if (otherRequest.legacyType == requestLegacyType
5106 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005107 if (DBG) log(" still have other legacy request - leaving");
5108 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005109 }
5110 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005111 }
5112
Erik Kline0c04b742016-07-07 16:50:58 +09005113 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005114 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005115 }
5116 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005117 }
5118 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005119
Junyu Lai00d92df2022-07-05 11:01:52 +08005120 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005121 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005122 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5123 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5124 }
5125
Lorenzo Colittid6459092016-07-04 12:55:44 +09005126 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005127 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005128 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005129 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005130 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005131 }
5132
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005133 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005134 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5135 enforceNetworkStackSettingsOrSetup();
5136 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5137 encodeBool(accept), encodeBool(always), network));
5138 }
5139
5140 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005141 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005142 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005143 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5144 }
5145
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005146 @Override
5147 public void setTestAllowBadWifiUntil(long timeMs) {
5148 enforceSettingsPermission();
5149 if (!Build.isDebuggable()) {
5150 throw new IllegalStateException("Does not support in non-debuggable build");
5151 }
5152
5153 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5154 throw new IllegalArgumentException("It should not exceed "
5155 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5156 }
5157
5158 mHandler.sendMessage(
5159 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5160 }
5161
chiachangwange0192a72023-02-06 13:25:01 +00005162 @Override
5163 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5164 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005165
5166 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5167 throw new IllegalArgumentException("Argument should not exceed "
5168 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5169 }
5170
5171 mHandler.sendMessage(
5172 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5173 }
5174
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005175 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5176 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5177 " accept=" + accept + " always=" + always);
5178
5179 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5180 if (nai == null) {
5181 // Nothing to do.
5182 return;
5183 }
5184
Chalard Jean254bd162022-08-25 13:04:51 +09005185 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005186 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005187 return;
5188 }
5189
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005190 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005191 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005192 }
5193
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005194 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5195 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005196 // If network becomes partial connectivity and user already accepted to use this
5197 // network, we should respect the user's option and don't need to popup the
5198 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005199 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005200 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005201 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005202 }
5203
5204 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005205 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005206 }
5207
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005208 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005209 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005210 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005211 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005212 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005213 }
5214
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005215 }
5216
lucaslin2240ef62019-03-12 13:08:03 +08005217 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5218 boolean always) {
5219 if (DBG) {
5220 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5221 + " always=" + always);
5222 }
5223
5224 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5225 if (nai == null) {
5226 // Nothing to do.
5227 return;
5228 }
5229
Chalard Jean254bd162022-08-25 13:04:51 +09005230 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005231 // The network validated while the dialog box was up. Take no action.
5232 return;
5233 }
5234
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005235 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5236 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005237 }
5238
5239 // TODO: Use the current design or save the user choice into IpMemoryStore.
5240 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005241 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005242 }
5243
5244 if (!accept) {
5245 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005246 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005247 // Tear down the network.
5248 teardownUnneededNetwork(nai);
5249 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005250 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5251 // result in a partial connectivity result which will be processed by
5252 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005253 //
5254 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5255 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005256 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005257 }
5258 }
5259
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005260 private void handleSetAvoidUnvalidated(Network network) {
5261 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005262 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005263 // Nothing to do. The network either disconnected or revalidated.
5264 return;
5265 }
Chalard Jean254bd162022-08-25 13:04:51 +09005266 if (0L == nai.getAvoidUnvalidated()) {
5267 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005268 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005269 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005270 }
5271 }
5272
Chalard Jean5fb43c72022-09-08 19:03:14 +09005273 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005274 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005275 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005276 mHandler.sendMessageDelayed(
Chalard Jean5fb43c72022-09-08 19:03:14 +09005277 mHandler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005278 }
5279
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005280 @Override
5281 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005282 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005283 mHandler.post(() -> {
5284 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5285 if (nai == null) return;
5286 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005287 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005288 });
5289 }
5290
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005291 /**
5292 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5293 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005294 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005295 * @param appExtras Bundle to use as intent extras for the captive portal application.
5296 * Must be treated as opaque to avoid preventing the captive portal app to
5297 * update its arguments.
5298 */
5299 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005300 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005301 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5302 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005303
5304 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5305 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005306 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5307 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005308 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5309
lucaslin75ff7022020-12-17 04:14:35 +08005310 final long token = Binder.clearCallingIdentity();
5311 try {
5312 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5313 } finally {
5314 Binder.restoreCallingIdentity(token);
5315 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005316 }
5317
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005318 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5319 private final Network mNetwork;
5320
5321 private CaptivePortalImpl(Network network) {
5322 mNetwork = network;
5323 }
5324
5325 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005326 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005327 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5328 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005329 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5330 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5331 // Since the network will be disconnected, skip notifying NetworkMonitor
5332 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005333 }
5334
Chiachang Wang938bfba2020-01-09 13:50:55 +08005335 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005336 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005337 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005338 }
5339
5340 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005341 public void appRequest(final int request) {
5342 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5343 if (nm == null) return;
5344
5345 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005346 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005347 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005348 }
5349 }
5350
5351 @Nullable
5352 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5353 // getNetworkAgentInfoForNetwork is thread-safe
5354 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5355 if (nai == null) return null;
5356
5357 // nai.networkMonitor() is thread-safe
5358 return nai.networkMonitor();
5359 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005360 }
5361
Hugo Benichic9048bc2016-09-14 23:23:08 +00005362 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005363 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005364 }
5365
Chalard Jean020b93a2022-09-01 13:20:14 +09005366 private boolean activelyPreferBadWifi() {
5367 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5368 }
5369
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005370 /**
5371 * Return whether the device should maintain continuous, working connectivity by switching away
5372 * from WiFi networks having no connectivity.
5373 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5374 */
5375 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005376 if (!checkNetworkStackPermission()) {
5377 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5378 }
5379 return avoidBadWifi();
5380 }
5381
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005382 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005383 ensureRunningOnConnectivityServiceThread();
5384 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005385 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005386 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005387 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005388 if (avoidBadWifi) {
5389 // If the device is now avoiding bad wifi, remove notifications that might have
5390 // been put up when the device didn't.
5391 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5392 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005393 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005394 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5395 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5396 for (final NetworkOfferInfo noi : offersToUpdate) {
5397 updateOfferScore(noi.offer);
5398 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005399 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005400 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005401 }
5402
Erik Kline95ecfee2016-10-02 18:02:14 +09005403 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005404 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005405 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005406 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005407 if (!configRestrict) {
5408 pw.println("Bad Wi-Fi avoidance: unrestricted");
5409 return;
5410 }
5411
5412 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5413 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005414 pw.println("Config restrict: " + configRestrict);
5415 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005416
Chalard Jeane0fdea32022-09-14 21:44:22 +09005417 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005418 String description;
5419 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005420 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005421 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005422 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005423 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005424 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005425 description = "avoid";
5426 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005427 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005428 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005429 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005430
5431 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5432 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005433 if (null == configValue) {
5434 description = "unset";
5435 } else if (configValue) {
5436 description = "force true";
5437 } else {
5438 description = "force false";
5439 }
5440 pw.println("Actively prefer bad wifi conf: " + description);
5441 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005442 pw.println("Network overrides:");
5443 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005444 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005445 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005446 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005447 }
5448 }
5449 pw.decreaseIndent();
5450 pw.decreaseIndent();
5451 }
5452
paulhu7746e4e2020-06-09 19:07:03 +08005453 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5454 // unify the method.
5455 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5456 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5457 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5458 return settingsComponent != null
5459 ? settingsComponent.getPackageName() : "com.android.settings";
5460 }
5461
lucaslinb1e8e382019-01-24 15:55:30 +08005462 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005463 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005464 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005465 switch (type) {
5466 case NO_INTERNET:
5467 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005468 // High priority because it is only displayed for explicitly selected networks.
5469 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005470 break;
lucasline117e2e2019-10-22 18:27:33 +08005471 case PRIVATE_DNS_BROKEN:
5472 action = Settings.ACTION_WIRELESS_SETTINGS;
5473 // High priority because we should let user know why there is no internet.
5474 highPriority = true;
5475 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005476 case LOST_INTERNET:
5477 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005478 // High priority because it could help the user avoid unexpected data usage.
5479 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005480 break;
lucaslin2240ef62019-03-12 13:08:03 +08005481 case PARTIAL_CONNECTIVITY:
5482 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005483 // Don't bother the user with a high-priority notification if the network was not
5484 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005485 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005486 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005487 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005488 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005489 return;
5490 }
5491
5492 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005493 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005494 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005495 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005496 // Some OEMs have their own Settings package. Thus, need to get the current using
5497 // Settings package name instead of just use default name "com.android.settings".
5498 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5499 intent.setClassName(settingsPkgName,
5500 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005501 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005502
paulhu2af50222020-10-11 22:52:27 +08005503 PendingIntent pendingIntent = PendingIntent.getActivity(
5504 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005505 0 /* requestCode */,
5506 intent,
paulhu2af50222020-10-11 22:52:27 +08005507 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005508
Serik Beketayevec8ad212020-12-07 22:43:07 -08005509 mNotifier.showNotification(
5510 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005511 }
5512
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005513 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5514 // Don't prompt if the network is validated, and don't prompt on captive portals
5515 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005516 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005517 return false;
5518 }
5519
5520 // If a network has partial connectivity, always prompt unless the user has already accepted
5521 // partial connectivity and selected don't ask again. This ensures that if the device
5522 // automatically connects to a network that has partial Internet access, the user will
5523 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005524 // because we have prompted them.
5525 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005526 return true;
5527 }
5528
5529 // If a network has no Internet access, only prompt if the network was explicitly selected
5530 // and if the user has not already told us to use the network regardless of whether it
5531 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005532 if (nai.networkAgentConfig.explicitlySelected
5533 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005534 return true;
5535 }
5536
5537 return false;
5538 }
5539
Chalard Jean5fb43c72022-09-08 19:03:14 +09005540 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5541 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005542
Chalard Jean5fb43c72022-09-08 19:03:14 +09005543 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5544 if (null == nai) return;
5545
5546 if (nai.setEvaluated()) {
5547 // If setEvaluated() returned true, the network never had any form of connectivity.
5548 // This may have an impact on request matching if bad WiFi avoidance is off and the
5549 // network was found not to have Internet access.
5550 nai.updateScoreForNetworkAgentUpdate();
5551 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005552
5553 // Also, if this is WiFi and it should be preferred actively, now is the time to
5554 // prompt the user that they walked past and connected to a bad WiFi.
5555 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5556 && !avoidBadWifi()
5557 && activelyPreferBadWifi()) {
5558 // The notification will be removed if the network validates or disconnects.
5559 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5560 return;
5561 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005562 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005563
Chalard Jean5fb43c72022-09-08 19:03:14 +09005564 if (!shouldPromptUnvalidated(nai)) return;
5565
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005566 // Stop automatically reconnecting to this network in the future. Automatically connecting
5567 // to a network that provides no or limited connectivity is not useful, because the user
5568 // cannot use that network except through the notification shown by this method, and the
5569 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005570 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005571
Chalard Jean254bd162022-08-25 13:04:51 +09005572 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005573 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005574 } else {
5575 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5576 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005577 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005578
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005579 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5580 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005581 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005582
lucaslin2240ef62019-03-12 13:08:03 +08005583 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5584 return;
5585 }
5586
5587 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005588 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005589 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005590 }
5591
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005592 @Override
5593 public int getMultipathPreference(Network network) {
5594 enforceAccessPermission();
5595
5596 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005597 if (nai != null && nai.networkCapabilities
5598 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005599 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5600 }
5601
Aaron Huang9a57acf2020-12-08 10:03:29 +08005602 final NetworkPolicyManager netPolicyManager =
5603 mContext.getSystemService(NetworkPolicyManager.class);
5604
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005605 final long token = Binder.clearCallingIdentity();
5606 final int networkPreference;
5607 try {
5608 networkPreference = netPolicyManager.getMultipathPreference(network);
5609 } finally {
5610 Binder.restoreCallingIdentity(token);
5611 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005612 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005613 return networkPreference;
5614 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005615 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5616 }
5617
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005618 @Override
5619 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005620 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005621 }
5622
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005623 private class InternalHandler extends Handler {
5624 public InternalHandler(Looper looper) {
5625 super(looper);
5626 }
5627
5628 @Override
5629 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005630 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005631 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005632 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005633 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005634 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005635 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005636 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005637 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005638 break;
5639 }
Jason Monka69f1b02013-10-10 14:02:51 -04005640 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005641 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5642 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005643 break;
5644 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005645 case EVENT_REGISTER_NETWORK_PROVIDER: {
5646 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005647 break;
5648 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005649 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5650 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005651 break;
5652 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005653 case EVENT_REGISTER_NETWORK_OFFER: {
5654 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5655 break;
5656 }
5657 case EVENT_UNREGISTER_NETWORK_OFFER: {
5658 final NetworkOfferInfo offer =
5659 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5660 if (null != offer) {
5661 handleUnregisterNetworkOffer(offer);
5662 }
5663 break;
5664 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005665 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005666 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5667 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5668 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005669 break;
5670 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005671 case EVENT_REGISTER_NETWORK_REQUEST:
5672 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005673 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005674 break;
5675 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005676 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5677 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005678 handleRegisterNetworkRequestWithIntent(msg);
5679 break;
5680 }
Erik Kline155a59a2015-11-25 12:49:38 +09005681 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5682 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5683 handleTimedOutNetworkRequest(nri);
5684 break;
5685 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005686 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5687 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5688 break;
5689 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005690 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005691 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5692 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005693 break;
5694 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005695 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005696 Network network = (Network) msg.obj;
5697 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005698 break;
5699 }
lucaslin2240ef62019-03-12 13:08:03 +08005700 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5701 Network network = (Network) msg.obj;
5702 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5703 toBool(msg.arg2));
5704 break;
5705 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005706 case EVENT_SET_AVOID_UNVALIDATED: {
5707 handleSetAvoidUnvalidated((Network) msg.obj);
5708 break;
5709 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09005710 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
5711 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005712 break;
5713 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005714 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5715 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005716 break;
5717 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00005718 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
5719 // handler thread.
5720 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005721 mKeepaliveTracker.handleStartKeepalive(msg);
5722 break;
5723 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00005724 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09005725 final AutomaticOnOffKeepalive ki =
5726 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
5727 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005728
chiachangwang676c84e2023-02-14 09:22:05 +00005729 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005730 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005731 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00005732 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005733 for (NetworkAgentInfo n : mNetworkAgentInfos) {
5734 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00005735 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
5736 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005737 }
5738 }
5739
5740 // If the network no longer exists, then the keepalive should have been
5741 // cleaned up already. There is no point trying to resume keepalives.
5742 if (!networkFound) return;
5743
chiachangwang676c84e2023-02-14 09:22:05 +00005744 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005745 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang676c84e2023-02-14 09:22:05 +00005746 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005747 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00005748 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005749 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005750 }
5751 break;
5752 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005753 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005754 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09005755 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
5756 (IBinder) msg.obj);
5757 if (ki == null) {
5758 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00005759 return;
5760 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09005761 final int reason = msg.arg2;
5762 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005763 break;
5764 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005765 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5766 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5767 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005768 break;
5769 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005770 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5771 handlePrivateDnsSettingsChanged();
5772 break;
dalyk1720e542018-03-05 12:42:22 -05005773 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5774 handlePrivateDnsValidationUpdate(
5775 (PrivateDnsValidationUpdate) msg.obj);
5776 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005777 case EVENT_UID_BLOCKED_REASON_CHANGED:
5778 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005779 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005780 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5781 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5782 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005783 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005784 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5785 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005786 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005787 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005788 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005789 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09005790 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
5791 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005792 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005793 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005794 }
lucaslin1193a5d2021-01-21 02:04:15 +08005795 case EVENT_REPORT_NETWORK_ACTIVITY:
5796 mNetworkActivityTracker.handleReportNetworkActivity();
5797 break;
paulhu51f77dc2021-06-07 02:34:20 +00005798 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5799 handleMobileDataPreferredUidsChanged();
5800 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005801 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5802 final long timeMs = ((Long) msg.obj).longValue();
5803 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5804 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005805 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5806 handleIngressRateLimitChanged();
5807 break;
Hansen Kurli55396972022-10-28 03:31:17 +00005808 case EVENT_USER_DOES_NOT_WANT:
5809 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5810 if (nai == null) break;
5811 nai.onPreventAutomaticReconnect();
5812 nai.disconnect();
5813 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00005814 case EVENT_SET_VPN_NETWORK_PREFERENCE:
5815 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
5816 break;
chiachangwange0192a72023-02-06 13:25:01 +00005817 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
5818 final long time = ((Long) msg.obj).longValue();
5819 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
5820 break;
5821 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00005822 case EVENT_UID_FROZEN_STATE_CHANGED:
5823 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
5824 handleFrozenUids(args.mUids, args.mFrozenStates);
5825 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005826 }
5827 }
5828 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005829
Lorenzo Colittid6459092016-07-04 12:55:44 +09005830 @Override
markchien5776f962019-12-16 20:15:20 +08005831 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005832 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08005833 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005834 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5835 Context.TETHERING_SERVICE);
5836 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005837 }
5838
Lorenzo Colittid6459092016-07-04 12:55:44 +09005839 @Override
markchien5776f962019-12-16 20:15:20 +08005840 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005841 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08005842 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005843 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5844 Context.TETHERING_SERVICE);
5845 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005846 }
5847
Lorenzo Colittid6459092016-07-04 12:55:44 +09005848 @Override
markchien5776f962019-12-16 20:15:20 +08005849 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005850 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005851 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005852 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5853 Context.TETHERING_SERVICE);
5854 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005855 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005856
markchien5776f962019-12-16 20:15:20 +08005857
Lorenzo Colittid6459092016-07-04 12:55:44 +09005858 @Override
markchien5776f962019-12-16 20:15:20 +08005859 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005860 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005861 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005862 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5863 Context.TETHERING_SERVICE);
5864
5865 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005866 }
5867
Lorenzo Colittid6459092016-07-04 12:55:44 +09005868 @Override
markchien5776f962019-12-16 20:15:20 +08005869 @Deprecated
5870 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08005871 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005872 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5873 Context.TETHERING_SERVICE);
5874
5875 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005876 }
5877
Udam Saini8f7d6a72017-06-07 12:06:28 -07005878 @Override
markchien5776f962019-12-16 20:15:20 +08005879 @Deprecated
5880 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08005881 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005882 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5883 Context.TETHERING_SERVICE);
5884 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005885 }
5886
Robert Greenwalte0b00512014-07-02 09:59:16 -07005887 // Called when we lose the default network and have no replacement yet.
5888 // This will automatically be cleared after X seconds or a new default network
5889 // becomes CONNECTED, whichever happens first. The timer is started by the
5890 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005891 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005892 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005893 if (mNetTransitionWakeLock.isHeld()) {
5894 return;
5895 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005896 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005897 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5898 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005899 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005900 mWakelockLogs.log("ACQUIRE for " + forWhom);
5901 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005902 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005903 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005904 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005905 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005906
Hugo Benichi471b62a2017-03-30 23:18:10 +09005907 // Called when we gain a new default network to release the network transition wakelock in a
5908 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5909 // message is cancelled.
5910 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005911 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005912 if (!mNetTransitionWakeLock.isHeld()) {
5913 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005914 }
5915 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005916 // Cancel self timeout on wakelock hold.
5917 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5918 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5919 mHandler.sendMessageDelayed(msg, 1000);
5920 }
5921
5922 // Called when either message of ensureNetworkTransitionWakelock or
5923 // scheduleReleaseNetworkTransitionWakelock is processed.
5924 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5925 String event = eventName(eventId);
5926 synchronized (this) {
5927 if (!mNetTransitionWakeLock.isHeld()) {
5928 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005929 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005930 return;
5931 }
5932 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005933 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5934 mTotalWakelockDurationMs += lockDuration;
5935 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5936 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005937 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005938 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005939 }
5940
Robert Greenwalt986c7412010-09-08 15:24:47 -07005941 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005942 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005943 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005944 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005945 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005946 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005947 }
5948
Lorenzo Colittid6459092016-07-04 12:55:44 +09005949 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005950 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005951 enforceAccessPermission();
5952 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005953 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005954 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005955
5956 final NetworkAgentInfo nai;
5957 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005958 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005959 } else {
5960 nai = getNetworkAgentInfoForNetwork(network);
5961 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005962
5963 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005964 mHandler.obtainMessage(
5965 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005966 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005967
Hugo Benichid6b510a2017-04-06 17:22:18 +09005968 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005969 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005970 if (nai == null
5971 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005972 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005973 return;
5974 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005975 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09005976 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005977 mConnectivityDiagnosticsHandler.sendMessage(
5978 mConnectivityDiagnosticsHandler.obtainMessage(
5979 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5980 new ReportedNetworkConnectivityInfo(
5981 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005982 return;
5983 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005984 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005985 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005986 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005987 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005988 // Validating a network that has not yet connected could result in a call to
5989 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09005990 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005991 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005992 }
paulhu7aeba372020-12-30 00:42:19 +08005993 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5994 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005995 return;
5996 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005997
5998 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5999 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6000 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6001 // completed.
6002 mConnectivityDiagnosticsHandler.sendMessage(
6003 mConnectivityDiagnosticsHandler.obtainMessage(
6004 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6005 new ReportedNetworkConnectivityInfo(
6006 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006007 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006008 }
6009
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006010 // TODO: call into netd.
6011 private boolean queryUserAccess(int uid, Network network) {
6012 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6013 if (nai == null) return false;
6014
6015 // Any UID can use its default network.
6016 if (nai == getDefaultNetworkForUid(uid)) return true;
6017
6018 // Privileged apps can use any network.
6019 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6020 return true;
6021 }
6022
6023 // An unprivileged UID can use a VPN iff the VPN applies to it.
6024 if (nai.isVPN()) {
6025 return nai.networkCapabilities.appliesToUid(uid);
6026 }
6027
6028 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6029 // sockets, i.e., if it is the owner.
6030 final NetworkAgentInfo vpn = getVpnForUid(uid);
6031 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6032 && uid != vpn.networkCapabilities.getOwnerUid()) {
6033 return false;
6034 }
6035
6036 // The UID's permission must be at least sufficient for the network. Since the restricted
6037 // permission was already checked above, that just leaves background networks.
6038 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6039 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6040 }
6041
6042 // Unrestricted network. Anyone gets to use it.
6043 return true;
6044 }
6045
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006046 /**
6047 * Returns information about the proxy a certain network is using. If given a null network, it
6048 * it will return the proxy for the bound network for the caller app or the default proxy if
6049 * none.
6050 *
6051 * @param network the network we want to get the proxy information for.
6052 * @return Proxy information if a network has a proxy configured, or otherwise null.
6053 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006054 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006055 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006056 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006057 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006058 if (network == null) {
6059 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006060 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006061 true);
6062 if (activeNetwork == null) {
6063 return null;
6064 }
6065 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006066 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006067 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6068 // caller may not have.
6069 return getLinkPropertiesProxyInfo(network);
6070 }
6071 // No proxy info available if the calling UID does not have network access.
6072 return null;
6073 }
6074
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006075
6076 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006077 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6078 if (nai == null) return null;
6079 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006080 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6081 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006082 }
6083 }
6084
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006085 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006086 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006087 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006088 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006089 }
6090
Chalard Jean777e2e52018-06-07 18:02:37 +09006091 @Override
6092 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006093 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006094 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006095 }
6096
Junyu Lai970963e2022-10-25 15:46:47 +08006097 private void handleApplyDefaultProxy(@Nullable ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04006098 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05006099 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07006100 proxy = null;
6101 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006102 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006103 }
6104
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006105 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6106 // when any network changes proxy.
6107 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6108 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006109 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6110 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006111 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6112
Chalard Jean7d97afc2018-06-07 17:41:29 +09006113 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006114 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006115 }
6116 }
6117
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006118 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006119 final private HashMap<Uri, Integer> mUriEventMap;
6120 final private Context mContext;
6121 final private Handler mHandler;
6122
6123 SettingsObserver(Context context, Handler handler) {
6124 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006125 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006126 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006127 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006128 }
6129
Erik Kline05f2b402015-04-30 12:58:40 +09006130 void observe(Uri uri, int what) {
6131 mUriEventMap.put(uri, what);
6132 final ContentResolver resolver = mContext.getContentResolver();
6133 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006134 }
6135
6136 @Override
6137 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006138 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006139 }
6140
6141 @Override
6142 public void onChange(boolean selfChange, Uri uri) {
6143 final Integer what = mUriEventMap.get(uri);
6144 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006145 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006146 } else {
6147 loge("No matching event to send for URI=" + uri);
6148 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006149 }
6150 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006151
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006152 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006153 Log.d(TAG, s);
6154 }
6155
6156 private static void logw(String s) {
6157 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006158 }
6159
Daniel Brightf9e945b2020-06-15 16:10:01 -07006160 private static void logwtf(String s) {
6161 Log.wtf(TAG, s);
6162 }
6163
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006164 private static void logwtf(String s, Throwable t) {
6165 Log.wtf(TAG, s, t);
6166 }
6167
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006168 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006169 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006170 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006171
Hugo Benichi39621362017-02-11 17:04:43 +09006172 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006173 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006174 }
6175
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006176 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006177 * Return the information of all ongoing VPNs.
6178 *
6179 * <p>This method is used to update NetworkStatsService.
6180 *
6181 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006182 */
junyulai2050bed2021-01-23 09:46:34 +08006183 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006184 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006185 if (mLockdownEnabled) {
6186 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006187 }
junyulai2050bed2021-01-23 09:46:34 +08006188 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006189 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006190 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006191 if (info != null) {
6192 infoList.add(info);
6193 }
6194 }
junyulai2050bed2021-01-23 09:46:34 +08006195 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006196 }
6197
6198 /**
6199 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006200 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006201 */
junyulai2050bed2021-01-23 09:46:34 +08006202 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006203 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006204 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6205 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006206 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6207 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6208 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006209 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6210 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006211 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006212 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006213 }
6214 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006215
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006216 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006217
6218 List<String> interfaces = new ArrayList<>();
6219 for (Network network : underlyingNetworks) {
6220 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6221 if (underlyingNai == null) continue;
6222 LinkProperties lp = underlyingNai.linkProperties;
6223 for (String iface : lp.getAllInterfaceNames()) {
6224 if (!TextUtils.isEmpty(iface)) {
6225 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006226 }
6227 }
Benedict Wong34857f82019-06-12 17:46:15 +00006228 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006229
6230 if (interfaces.isEmpty()) return null;
6231
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006232 // Must be non-null or NetworkStatsService will crash.
6233 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6234 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006235 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006236 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006237
junyulai2050bed2021-01-23 09:46:34 +08006238 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6239 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006240 }
6241
James Mattisd31bdfa2020-12-23 16:37:26 -08006242 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006243 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6244 Network[] underlyingNetworks) {
6245 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006246 if (underlyingNetworks == null && defaultNetwork != null) {
6247 // null underlying networks means to track the default.
6248 underlyingNetworks = new Network[] { defaultNetwork };
6249 }
6250 return underlyingNetworks;
6251 }
6252
6253 // Returns true iff |network| is an underlying network of |nai|.
6254 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6255 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6256 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006257 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006258 final Network[] underlying = underlyingNetworksOrDefault(
6259 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006260 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006261 }
6262
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006263 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006264 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006265 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006266 * When underlying networks change, such networks may have to update capabilities to reflect
6267 * things like the metered bit, their transports, and so on. The capabilities are calculated
6268 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006269 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006270 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006271 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006272 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006273 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006274 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006275 }
6276 }
6277 }
6278
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006279 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6280 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6281 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6282 // a VPN is not up.
6283 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6284 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6285 for (UidRange range : blockedUidRanges) {
6286 if (range.contains(uid)) return true;
6287 }
6288 return false;
6289 }
6290
6291 @Override
6292 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006293 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006294 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6295 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6296 }
6297
6298 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6299 if (DBG) {
6300 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6301 + Arrays.toString(ranges));
6302 }
6303 // Cannot use a Set since the list of UID ranges might contain duplicates.
6304 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6305 for (int i = 0; i < ranges.length; i++) {
6306 if (requireVpn) {
6307 newVpnBlockedUidRanges.add(ranges[i]);
6308 } else {
6309 newVpnBlockedUidRanges.remove(ranges[i]);
6310 }
6311 }
6312
6313 try {
6314 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6315 } catch (RemoteException | ServiceSpecificException e) {
6316 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6317 + Arrays.toString(ranges) + "): netd command failed: " + e);
6318 }
6319
Motomu Utsumib08654c2022-05-11 05:56:26 +00006320 if (SdkLevel.isAtLeastT()) {
6321 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6322 }
6323
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006324 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6325 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006326 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6327 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006328 }
6329
6330 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6331 }
6332
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006333 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006334 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006335 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006336 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006337 }
6338
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006339 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6340 return mLockdownEnabled
6341 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6342 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006343 }
6344
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006345 private NetworkAgentInfo getLegacyLockdownNai() {
6346 if (!mLockdownEnabled) {
6347 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006348 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006349 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006350 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6351 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006352
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006353 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006354 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6355 // a local variable. There is no need to make a copy because its contents cannot change.
6356 final Network[] underlying = nai.declaredUnderlyingNetworks;
6357 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006358 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006359 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006360
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006361 // The legacy lockdown VPN always uses the default network.
6362 // If the VPN's underlying network is no longer the current default network, it means that
6363 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006364 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6365 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006366 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006367 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006368 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006369 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006370
6371 return nai;
6372 };
6373
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006374 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6375 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6376 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006377 private DetailedState getLegacyLockdownState(DetailedState origState) {
6378 if (origState != DetailedState.CONNECTED) {
6379 return origState;
6380 }
6381 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6382 ? DetailedState.CONNECTING
6383 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006384 }
6385
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006386 private void filterForLegacyLockdown(NetworkInfo ni) {
6387 if (!mLockdownEnabled || !ni.isConnected()) return;
6388 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6389 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6390 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6391 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6392 // network, this time with a state of CONNECTED.
6393 //
6394 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6395 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6396 // is not too far off the truth, since an always-on VPN, when not connected, is always
6397 // trying to reconnect.
6398 if (getLegacyLockdownNai() == null) {
6399 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6400 }
6401 }
6402
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006403 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006404 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006405 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006406 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006407 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6408 return;
6409 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006410 final long ident = Binder.clearCallingIdentity();
6411 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006412 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006413 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006414 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006415 } finally {
6416 Binder.restoreCallingIdentity(ident);
6417 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006418 }
Wink Savillecb117d32013-08-29 14:57:08 -07006419
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006420 @Override
6421 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006422 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006423 final long ident = Binder.clearCallingIdentity();
6424 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006425 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006426 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006427 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6428 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006429 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006430 } finally {
6431 Binder.restoreCallingIdentity(ident);
6432 }
6433 }
6434
James Mattis02220e22021-03-13 19:27:21 -08006435 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006436 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6437 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6438 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006439 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006440 }
6441
James Mattis02220e22021-03-13 19:27:21 -08006442 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006443 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006444 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006445 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6446 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006447 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006448 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6449 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6450 }
junyulaid91e7052020-08-28 13:44:33 +08006451 }
6452
James Mattis02220e22021-03-13 19:27:21 -08006453 private void onPackageChanged(@NonNull final String packageName) {
6454 // This is necessary in case a package is added or removed, but also when it's replaced to
6455 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6456 // as one in the preferences, then it should follow the same routing as that other package,
6457 // which means updating the rules is never to be needed in this case (whether it joins or
6458 // leaves a UID with a preference).
6459 if (isMappedInOemNetworkPreference(packageName)) {
6460 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6461 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006462
6463 // Invalidates cache entry when the package is updated.
6464 synchronized (mSelfCertifiedCapabilityCache) {
6465 mSelfCertifiedCapabilityCache.remove(packageName);
6466 }
James Mattis02220e22021-03-13 19:27:21 -08006467 }
6468
6469 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006470 @Override
6471 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006472 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006473 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006474 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006475
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006476 // User should be filled for below intents, check the existence.
6477 if (user == null) {
6478 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6479 return;
6480 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006481
Lorenzo Colitticd675292021-02-04 17:32:07 +09006482 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006483 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006484 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006485 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006486 } else {
junyulaid91e7052020-08-28 13:44:33 +08006487 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006488 }
6489 }
6490 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006491
James Mattis02220e22021-03-13 19:27:21 -08006492 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6493 @Override
6494 public void onReceive(Context context, Intent intent) {
6495 ensureRunningOnConnectivityServiceThread();
6496 switch (intent.getAction()) {
6497 case Intent.ACTION_PACKAGE_ADDED:
6498 case Intent.ACTION_PACKAGE_REMOVED:
6499 case Intent.ACTION_PACKAGE_REPLACED:
6500 onPackageChanged(intent.getData().getSchemeSpecificPart());
6501 break;
6502 default:
6503 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6504 }
6505 }
6506 };
6507
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006508 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006509 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006510
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006511 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006512 public final String name;
6513 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006514 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006515 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006516
lifraf3a3492021-03-10 13:58:14 +08006517 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6518 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006519 this.name = name;
6520 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006521 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006522 mDeathRecipient = deathRecipient;
6523
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006524 if (mDeathRecipient == null) {
6525 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006526 }
6527 }
6528
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006529 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006530 try {
6531 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6532 } catch (RemoteException e) {
6533 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006534 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006535 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006536 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006537
James Mattis4fce5d12020-11-12 15:53:42 -08006538 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6539 for (int i = 0; i < requests.size(); i++) {
6540 ensureNetworkRequestHasType(requests.get(i));
6541 }
6542 }
6543
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006544 private void ensureNetworkRequestHasType(NetworkRequest request) {
6545 if (request.type == NetworkRequest.Type.NONE) {
6546 throw new IllegalArgumentException(
6547 "All NetworkRequests in ConnectivityService must have a type");
6548 }
6549 }
6550
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006551 /**
6552 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006553 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006554 */
James Mattis258ea3c2020-11-15 15:04:40 -08006555 @VisibleForTesting
6556 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006557 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6558 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006559 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006560
James Mattisa076c532020-12-02 14:12:41 -08006561 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6562 void setSatisfier(
6563 @Nullable final NetworkAgentInfo satisfier,
6564 @Nullable final NetworkRequest activeRequest) {
6565 mSatisfier = satisfier;
6566 mActiveRequest = activeRequest;
6567 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006568
James Mattisd31bdfa2020-12-23 16:37:26 -08006569 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006570 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006571 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006572 private NetworkAgentInfo mSatisfier;
6573 NetworkAgentInfo getSatisfier() {
6574 return mSatisfier;
6575 }
6576
6577 // The request in mRequests assigned to a network agent. This is null if none of the
6578 // requests in mRequests can be satisfied. This member has the constraint of only being
6579 // accessible on the handler thread.
6580 @Nullable
6581 private NetworkRequest mActiveRequest;
6582 NetworkRequest getActiveRequest() {
6583 return mActiveRequest;
6584 }
6585
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006586 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006587 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006588 @Nullable
6589 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006590
6591 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006592 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006593 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006594 final int mPid;
6595 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006596 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006597 @Nullable
6598 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006599
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006600 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006601 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006602
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006603 // Effective UID of this request. This is different from mUid when a privileged process
6604 // files a request on behalf of another UID. This UID is used to determine blocked status,
6605 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6606 // maximum limit of registered callbacks per UID.
6607 final int mAsUid;
6608
paulhu48291862021-07-14 14:53:57 +08006609 // Preference order of this request.
6610 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006611
James Mattis3ce3d3c2021-02-09 18:18:28 -08006612 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6613 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6614 // maintained for keying off of. This is only a concern when the original nri
6615 // mNetworkRequests changes which happens currently for apps that register callbacks to
6616 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6617 // that match the per-app default nri that currently tracks the calling app's uid so that
6618 // callbacks are fired at the appropriate time. When the callbacks fire,
6619 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6620 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6621 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6622 @NonNull
6623 private final NetworkRequest mNetworkRequestForCallback;
6624 NetworkRequest getNetworkRequestForCallback() {
6625 return mNetworkRequestForCallback;
6626 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006627
James Mattisd31bdfa2020-12-23 16:37:26 -08006628 /**
6629 * Get the list of UIDs this nri applies to.
6630 */
6631 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006632 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006633 // networkCapabilities.getUids() returns a defensive copy.
6634 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006635 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6636 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006637 }
6638
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006639 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6640 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006641 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006642 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006643 }
6644
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006645 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006646 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006647 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006648 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006649 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006650 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006651 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006652 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006653 mBinder = null;
6654 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006655 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006656 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006657 mPerUidCounter = getRequestCounter(this);
6658 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006659 /**
6660 * Location sensitive data not included in pending intent. Only included in
6661 * {@link NetworkCallback}.
6662 */
6663 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006664 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006665 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006666 }
6667
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006668 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006669 @Nullable final IBinder binder,
6670 @NetworkCallback.Flag int callbackFlags,
6671 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006672 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6673 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006674 }
6675
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006676 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006677 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006678 @Nullable final IBinder binder,
6679 @NetworkCallback.Flag int callbackFlags,
6680 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006681 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006682 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006683 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006684 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006685 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006686 mBinder = binder;
6687 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006688 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006689 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006690 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006691 mPerUidCounter = getRequestCounter(this);
6692 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006693 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006694 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006695 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006696 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006697 }
6698
James Mattis3ce3d3c2021-02-09 18:18:28 -08006699 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6700 @NonNull final List<NetworkRequest> r) {
6701 super();
6702 ensureAllNetworkRequestsHaveType(r);
6703 mRequests = initializeRequests(r);
6704 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006705 final NetworkAgentInfo satisfier = nri.getSatisfier();
6706 if (null != satisfier) {
6707 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6708 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09006709 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006710 // As this code creates a new NRI with a new set of requests, figure out which of
6711 // the list of requests should be the active request. It is always the first
6712 // request of the list that can be satisfied by the satisfier since the order of
6713 // requests is a priority order.
6714 // Note even in the presence of a satisfier there may not be an active request,
6715 // when the satisfier is the no-service network.
6716 NetworkRequest activeRequest = null;
6717 for (final NetworkRequest candidate : r) {
6718 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6719 activeRequest = candidate;
6720 break;
6721 }
6722 }
6723 setSatisfier(satisfier, activeRequest);
6724 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006725 mMessenger = nri.mMessenger;
6726 mBinder = nri.mBinder;
6727 mPid = nri.mPid;
6728 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006729 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006730 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006731 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006732 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006733 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006734 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006735 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006736 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006737 }
6738
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006739 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006740 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006741 }
6742
paulhue9913722021-05-26 15:19:20 +08006743 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006744 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006745 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006746 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006747 }
6748
James Mattis2516da32021-01-31 17:06:19 -08006749 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6750 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6751 // false.
6752 boolean isBeingSatisfied() {
6753 return (null != mSatisfier && null != mActiveRequest);
6754 }
6755
James Mattis3d229892020-11-16 16:46:28 -08006756 boolean isMultilayerRequest() {
6757 return mRequests.size() > 1;
6758 }
6759
James Mattis45d81842021-01-10 14:24:24 -08006760 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6761 // Creating a defensive copy to prevent the sender from modifying the list being
6762 // reflected in the return value of this method.
6763 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006764 return Collections.unmodifiableList(tempRequests);
6765 }
6766
James Mattisb1392002021-03-31 13:57:52 -07006767 void linkDeathRecipient() {
6768 if (null != mBinder) {
6769 try {
6770 mBinder.linkToDeath(this, 0);
6771 } catch (RemoteException e) {
6772 binderDied();
6773 }
6774 }
6775 }
6776
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006777 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006778 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006779 try {
6780 mBinder.unlinkToDeath(this, 0);
6781 } catch (NoSuchElementException e) {
6782 // Temporary workaround for b/194394697 pending analysis of additional logs
6783 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6784 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006785 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006786 }
6787
paulhu48291862021-07-14 14:53:57 +08006788 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6789 // Compare two preference orders.
6790 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006791 }
6792
paulhu48291862021-07-14 14:53:57 +08006793 int getPreferenceOrderForNetd() {
6794 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6795 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6796 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006797 }
paulhu48291862021-07-14 14:53:57 +08006798 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006799 }
6800
James Mattis4fce5d12020-11-12 15:53:42 -08006801 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006802 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09006803 // As an immutable collection, mRequests cannot change by the time the
6804 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6805 // is acceptable. Use handleReleaseNetworkRequest and not directly
6806 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6807 // the app already unregistered the request.
6808 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6809 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006810 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006811
James Mattis4fce5d12020-11-12 15:53:42 -08006812 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006813 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006814 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6815 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006816 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006817 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006818 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006819 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006820 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006821 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006822 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006823 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006824 }
6825
Junyu Lai00d92df2022-07-05 11:01:52 +08006826 // Keep backward compatibility since the ServiceSpecificException is used by
6827 // the API surface, see {@link ConnectivityManager#convertServiceException}.
6828 public static class RequestInfoPerUidCounter extends PerUidCounter {
6829 RequestInfoPerUidCounter(int maxCountPerUid) {
6830 super(maxCountPerUid);
6831 }
6832
6833 @Override
6834 public synchronized void incrementCountOrThrow(int uid) {
6835 try {
6836 super.incrementCountOrThrow(uid);
6837 } catch (IllegalStateException e) {
6838 throw new ServiceSpecificException(
6839 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
6840 "Uid " + uid + " exceeded its allotted requests limit");
6841 }
6842 }
6843
6844 @Override
6845 public synchronized void decrementCountOrThrow(int uid) {
6846 throw new UnsupportedOperationException("Use decrementCount instead.");
6847 }
6848
6849 public synchronized void decrementCount(int uid) {
6850 try {
6851 super.decrementCountOrThrow(uid);
6852 } catch (IllegalStateException e) {
6853 logwtf("Exception when decrement per uid request count: ", e);
6854 }
6855 }
6856 }
6857
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006858 // This checks that the passed capabilities either do not request a
6859 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006860 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006861 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006862 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006863 throw new SecurityException("Insufficient permissions to request a specific SSID");
6864 }
paulhu1a407652019-03-22 16:35:06 +08006865
6866 if (nc.hasSignalStrength()
6867 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6868 throw new SecurityException(
6869 "Insufficient permissions to request a specific signal strength");
6870 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006871 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006872
junyulai2217bec2021-04-14 23:33:31 +08006873 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006874 enforceNetworkFactoryPermission();
6875 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006876 }
6877
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006878 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006879 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006880 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006881 // mNetworkRequests may contain the same value multiple times in case of
6882 // multilayer requests. It won't matter in this case because the thresholds
6883 // will then be the same and be deduplicated as they enter the `thresholds` set.
6884 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006885 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6886 for (final NetworkRequest req : nri.mRequests) {
6887 if (req.networkCapabilities.hasSignalStrength()
6888 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6889 thresholds.add(req.networkCapabilities.getSignalStrength());
6890 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006891 }
6892 }
6893 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006894 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006895 }
6896
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006897 private void updateSignalStrengthThresholds(
6898 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006899 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006900
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006901 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006902 String detail;
6903 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6904 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6905 } else {
6906 detail = reason;
6907 }
6908 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006909 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006910 }
6911
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006912 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006913 }
6914
Chalard Jeandd421992021-12-16 23:16:02 +09006915 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006916 if (nc == null) {
6917 return;
6918 }
6919 NetworkSpecifier ns = nc.getNetworkSpecifier();
6920 if (ns == null) {
6921 return;
6922 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006923 if (ns instanceof MatchAllNetworkSpecifier) {
6924 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6925 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006926 }
6927
Chalard Jeandd421992021-12-16 23:16:02 +09006928 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006929 ensureValidNetworkSpecifier(nc);
6930 if (nc.isPrivateDnsBroken()) {
6931 throw new IllegalArgumentException("Can't request broken private DNS");
6932 }
Chalard Jeande665262022-02-25 16:12:12 +09006933 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09006934 throw new IllegalArgumentException("Can't request access UIDs");
6935 }
lucasline117e2e2019-10-22 18:27:33 +08006936 }
6937
Chalard Jeandd421992021-12-16 23:16:02 +09006938 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6939 ensureListenableCapabilities(nc);
6940 final String badCapability = nc.describeFirstNonRequestableCapability();
6941 if (badCapability != null) {
6942 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6943 }
6944 }
6945
Chiachang Wang3bc52762021-11-25 14:17:57 +08006946 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6947 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006948 private boolean isTargetSdkAtleast(int version, int callingUid,
6949 @NonNull String callingPackageName) {
6950 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006951 final PackageManager pm =
6952 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006953 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006954 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006955 if (callingVersion < version) return false;
6956 } catch (PackageManager.NameNotFoundException e) { }
6957 return true;
6958 }
6959
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006960 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006961 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006962 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006963 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006964 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006965 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006966 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6967 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006968 throw new SecurityException("Insufficient permissions to specify legacy type");
6969 }
markchienfac84a22020-03-18 21:16:15 +08006970 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006971 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006972 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006973 // Privileged callers can track the default network of another UID by passing in a UID.
6974 if (asUid != Process.INVALID_UID) {
6975 enforceSettingsPermission();
6976 } else {
6977 asUid = callingUid;
6978 }
junyulaiad010792021-01-11 16:53:38 +08006979 final NetworkRequest.Type reqType;
6980 try {
6981 reqType = NetworkRequest.Type.values()[reqTypeInt];
6982 } catch (ArrayIndexOutOfBoundsException e) {
6983 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6984 }
6985 switch (reqType) {
6986 case TRACK_DEFAULT:
6987 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006988 // is unused and will be replaced by ones appropriate for the UID (usually, the
6989 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006990 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006991 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006992 enforceAccessPermission();
6993 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006994 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00006995 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006996 networkCapabilities = new NetworkCapabilities(defaultNc);
6997 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006998 case BACKGROUND_REQUEST:
6999 enforceNetworkStackOrSettingsPermission();
7000 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007001 case REQUEST:
7002 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7003 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007004 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007005 // TODO: this is incorrect. We mark the request as metered or not depending on
7006 // the state of the app when the request is filed, but we never change the
7007 // request if the app changes network state. http://b/29964605
7008 enforceMeteredApnPolicy(networkCapabilities);
7009 break;
junyulai1b1c8742021-03-12 20:05:08 +08007010 case LISTEN_FOR_BEST:
7011 enforceAccessPermission();
7012 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7013 break;
junyulaiad010792021-01-11 16:53:38 +08007014 default:
7015 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007016 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007017 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007018 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007019 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007020
junyulai1b1c8742021-03-12 20:05:08 +08007021 // Enforce FOREGROUND if the caller does not have permission to use background network.
7022 if (reqType == LISTEN_FOR_BEST) {
7023 restrictBackgroundRequestForCaller(networkCapabilities);
7024 }
7025
7026 // Set the UID range for this request to the single UID of the requester, unless the
7027 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007028 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7029 // are no visible methods to set the UIDs, an app could use reflection to try and get
7030 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007031 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007032 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7033 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007034
Etan Cohen85000162017-02-05 10:42:27 -08007035 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007036 throw new IllegalArgumentException("Bad timeout specified");
7037 }
Etan Cohen9786d922015-11-18 10:56:15 -08007038
James Mattis3ce3d3c2021-02-09 18:18:28 -08007039 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007040 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007041 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007042 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007043 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007044 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007045
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007046 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7047 // copied from the default request above. (This is necessary to ensure, for example, that
7048 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7049 // changes don't alter request matching.
7050 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7051 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007052 throw new IllegalStateException(
7053 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007054 + networkCapabilities + " vs. " + defaultNc);
7055 }
7056
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007057 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007058 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007059 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007060 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007061 }
7062 return networkRequest;
7063 }
7064
James Mattis3ce3d3c2021-02-09 18:18:28 -08007065 /**
7066 * Return the nri to be used when registering a network request. Specifically, this is used with
7067 * requests registered to track the default request. If there is currently a per-app default
7068 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7069 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007070 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7071 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007072 * @param nr the network request for the nri.
7073 * @param msgr the messenger for the nri.
7074 * @param binder the binder for the nri.
7075 * @param callingAttributionTag the calling attribution tag for the nri.
7076 * @return the nri to register.
7077 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007078 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007079 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007080 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007081 @Nullable String callingAttributionTag) {
7082 final List<NetworkRequest> requests;
7083 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7084 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007085 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007086 } else {
7087 requests = Collections.singletonList(nr);
7088 }
Roshan Pius951c0032020-12-22 15:10:42 -08007089 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007090 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007091 }
7092
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007093 private boolean shouldCheckCapabilitiesDeclaration(
7094 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7095 @NonNull final String callingPackageName) {
7096 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7097 // Only run the check if the change is enabled.
7098 if (!mDeps.isChangeEnabled(
7099 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7100 callingPackageName, user)) {
7101 return false;
7102 }
7103
7104 return networkCapabilities.hasCapability(
7105 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7106 || networkCapabilities.hasCapability(
7107 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7108 }
7109
7110 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
7111 @NonNull final NetworkCapabilities networkCapabilities) {
7112 // This check is added to fix the linter error for "current min is 30", which is not going
7113 // to happen because Connectivity service always run in S+.
7114 if (!SdkLevel.isAtLeastS()) {
7115 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7116 return;
7117 }
7118 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007119 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007120 try {
7121 synchronized (mSelfCertifiedCapabilityCache) {
7122 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7123 callerPackageName);
7124 if (applicationNetworkCapabilities == null) {
7125 final PackageManager packageManager = mContext.getPackageManager();
7126 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7127 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7128 callerPackageName
7129 );
7130 final XmlResourceParser parser = packageManager
7131 .getResourcesForApplication(callerPackageName)
7132 .getXml(networkSliceProperty.getResourceId());
7133 applicationNetworkCapabilities =
7134 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7135 mSelfCertifiedCapabilityCache.put(callerPackageName,
7136 applicationNetworkCapabilities);
7137 }
7138
7139 }
7140 } catch (PackageManager.NameNotFoundException ne) {
7141 throw new SecurityException(
7142 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7143 + " property");
7144 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7145 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007146 } finally {
7147 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007148 }
7149
7150 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7151 networkCapabilities);
7152 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007153 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007154 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007155 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7156 callingPackageName)) {
7157 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7158 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007159 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007160 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7161 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7162 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7163 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007164 }
junyulai96bd9fe2022-03-08 17:36:42 +08007165 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007166 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007167 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007168 }
7169 }
7170
fenglu3f357402015-03-20 11:29:56 -07007171 @Override
fenglub00f4882015-04-21 17:12:05 -07007172 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007173 enforceAccessPermission();
7174 NetworkAgentInfo nai = null;
7175 if (network == null) {
7176 return false;
7177 }
7178 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007179 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007180 }
7181 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007182 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007183 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007184 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007185 Integer uidReqs = mBandwidthRequests.get(uid);
7186 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007187 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007188 }
7189 mBandwidthRequests.put(uid, ++uidReqs);
7190 }
fenglu3f357402015-03-20 11:29:56 -07007191 return true;
7192 }
7193 return false;
7194 }
7195
Felipe Leme0a5ae422016-06-20 16:36:29 -07007196 private boolean isSystem(int uid) {
7197 return uid < Process.FIRST_APPLICATION_UID;
7198 }
fenglu3f357402015-03-20 11:29:56 -07007199
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007200 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007201 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007202 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007203 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007204 return;
7205 }
Hugo Benichi39621362017-02-11 17:04:43 +09007206 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7207 // Policy already enforced.
7208 return;
7209 }
paulhuaf50d7d2020-12-24 19:47:34 +08007210 final long ident = Binder.clearCallingIdentity();
7211 try {
7212 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7213 // If UID is restricted, don't allow them to bring up metered APNs.
7214 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7215 }
7216 } finally {
7217 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007218 }
7219 }
7220
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007221 @Override
7222 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007223 PendingIntent operation, @NonNull String callingPackageName,
7224 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007225 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007226 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007227 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007228 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007229 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007230 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007231 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007232 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007233 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007234 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7235 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007236
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007237 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007238 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007239 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7240 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007241 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007242 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7243 nri));
7244 return networkRequest;
7245 }
7246
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007247 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7248 mHandler.sendMessageDelayed(
7249 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007250 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007251 }
7252
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007253 @Override
7254 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007255 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007256 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007257 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007258 }
7259
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007260 // In order to implement the compatibility measure for pre-M apps that call
7261 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7262 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7263 // This ensures it has permission to do so.
7264 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7265 if (nc == null) {
7266 return false;
7267 }
7268 int[] transportTypes = nc.getTransportTypes();
7269 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7270 return false;
7271 }
7272 try {
7273 mContext.enforceCallingOrSelfPermission(
7274 android.Manifest.permission.ACCESS_WIFI_STATE,
7275 "ConnectivityService");
7276 } catch (SecurityException e) {
7277 return false;
7278 }
7279 return true;
7280 }
7281
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007282 @Override
7283 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007284 Messenger messenger, IBinder binder,
7285 @NetworkCallback.Flag int callbackFlags,
7286 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007287 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007288 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7289 enforceAccessPermission();
7290 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007291
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007292 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007293 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007294 Binder.getCallingPid(), callingUid, callingPackageName);
7295 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007296 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7297 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7298 // onLost and onAvailable callbacks when networks move in and out of the background.
7299 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7300 // can't request networks.
7301 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007302 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007303
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007304 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007305 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007306 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007307 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007308 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007309 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007310
7311 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7312 return networkRequest;
7313 }
7314
7315 @Override
7316 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007317 PendingIntent operation, @NonNull String callingPackageName,
7318 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007319 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007320 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007321 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7322 enforceAccessPermission();
7323 }
Chalard Jeandd421992021-12-16 23:16:02 +09007324 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007325 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007326 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007327 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007328 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007329
7330 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007331 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007332 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7333 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007334 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007335
WeiZhang1cc3f172021-06-03 19:02:04 -05007336 mHandler.sendMessage(mHandler.obtainMessage(
7337 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007338 }
7339
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007340 /** Returns the next Network provider ID. */
7341 public final int nextNetworkProviderId() {
7342 return mNextNetworkProviderId.getAndIncrement();
7343 }
7344
Erik Kline0c04b742016-07-07 16:50:58 +09007345 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007346 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007347 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007348 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007349 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007350 }
7351
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007352 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7353 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007354 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7355 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7356 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007357 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007358 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007359 return;
7360 }
7361
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007362 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7363 mNetworkProviderInfos.put(npi.messenger, npi);
7364 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007365 }
7366
7367 @Override
7368 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007369 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007370 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007371 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007372 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007373 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7374 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007375 }
7376
7377 @Override
7378 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007379 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007380 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007381 }
7382
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007383 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007384 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007385 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7386 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007387 Objects.requireNonNull(score);
7388 Objects.requireNonNull(caps);
7389 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007390 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007391 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007392 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7393 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007394 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7395 }
7396
Chalard Jeanbb902a52021-08-18 01:35:19 +09007397 private void updateOfferScore(final NetworkOffer offer) {
7398 final boolean yieldToBadWiFi =
7399 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7400 final NetworkOffer newOffer = new NetworkOffer(
7401 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7402 offer.caps, offer.callback, offer.providerId);
7403 if (offer.equals(newOffer)) return;
7404 handleRegisterNetworkOffer(newOffer);
7405 }
7406
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007407 @Override
7408 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007409 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007410 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7411 }
7412
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007413 private void handleUnregisterNetworkProvider(Messenger messenger) {
7414 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7415 if (npi == null) {
7416 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007417 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007418 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007419 // Unregister all the offers from this provider
7420 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7421 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007422 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007423 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7424 toRemove.add(noi);
7425 }
7426 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007427 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007428 handleUnregisterNetworkOffer(noi);
7429 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007430 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007431 }
7432
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007433 @Override
James Mattisf7027322020-12-13 16:28:14 -08007434 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007435 if (request.hasTransport(TRANSPORT_TEST)) {
7436 enforceNetworkFactoryOrTestNetworksPermission();
7437 } else {
7438 enforceNetworkFactoryPermission();
7439 }
James Mattisf7027322020-12-13 16:28:14 -08007440 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7441 if (nri != null) {
7442 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7443 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7444 mHandler.post(() -> handleReleaseNetworkRequest(
7445 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7446 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007447 }
7448
Paul Jensen1f567382015-02-13 14:18:39 -05007449 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7450 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007451 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007452 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007453 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007454 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007455 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007456
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007457 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007458 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007459 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007460
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007461 // UID ranges for users that are currently blocked by VPNs.
7462 // This array is accessed and iterated on multiple threads without holding locks, so its
7463 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7464 // (on the handler thread).
7465 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7466
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007467 // Must only be accessed on the handler thread
7468 @NonNull
7469 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7470
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007471 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007472 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007473
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007474 // Current OEM network preferences. This object must only be written to on the handler thread.
7475 // Since it is immutable and always non-null, other threads may read it if they only care
7476 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007477 @NonNull
7478 private OemNetworkPreferences mOemNetworkPreferences =
7479 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007480 // Current per-profile network preferences. This object follows the same threading rules as
7481 // the OEM network preferences above.
7482 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007483 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7484 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007485
lucaslin3ba7cc22022-12-19 02:35:33 +00007486 // Current VPN network preferences. This object follows the same threading rules as the OEM
7487 // network preferences above.
7488 @NonNull
7489 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7490 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7491
paulhu51f77dc2021-06-07 02:34:20 +00007492 // A set of UIDs that should use mobile data preferentially if available. This object follows
7493 // the same threading rules as the OEM network preferences above.
7494 @NonNull
7495 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7496
James Mattiscb1e0362021-04-06 17:07:42 -07007497 // OemNetworkPreferences activity String log entries.
7498 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7499 @NonNull
7500 private final LocalLog mOemNetworkPreferencesLogs =
7501 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7502
James Mattis02220e22021-03-13 19:27:21 -08007503 /**
7504 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7505 * @param packageName the package name to check existence of a mapping for.
7506 * @return true if a mapping exists, false otherwise
7507 */
7508 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7509 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7510 }
7511
James Mattise3ef1912020-12-20 11:09:58 -08007512 // The always-on request for an Internet-capable network that apps without a specific default
7513 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007514 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007515 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007516 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007517 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007518 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007519 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007520 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007521
James Mattisd31bdfa2020-12-23 16:37:26 -08007522 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7523 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7524 }
7525
7526 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007527 * Return the default network request currently tracking the given uid.
7528 * @param uid the uid to check.
7529 * @return the NetworkRequestInfo tracking the given uid.
7530 */
7531 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007532 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007533 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007534 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007535 // Checking the first request is sufficient as only multilayer requests will have more
7536 // than one request and for multilayer, all requests will track the same uids.
7537 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007538 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007539 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007540 highestPriorityNri = nri;
7541 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007542 }
7543 }
paulhuaa0743d2021-05-26 21:56:03 +08007544 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007545 }
7546
7547 /**
7548 * Get a copy of the network requests of the default request that is currently tracking the
7549 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007550 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7551 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007552 * @param requestorUid the uid to check the default for.
7553 * @param requestorPackageName the requestor's package name.
7554 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7555 */
7556 @NonNull
7557 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007558 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007559 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007560 getDefaultRequestTrackingUid(asUid).mRequests,
7561 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007562 }
7563
7564 /**
7565 * Copy the given nri's NetworkRequest collection.
7566 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007567 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7568 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007569 * @param requestorUid the uid to set on the copied collection.
7570 * @param requestorPackageName the package name to set on the copied collection.
7571 * @return the copied NetworkRequest collection.
7572 */
7573 @NonNull
7574 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007575 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7576 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007577 final List<NetworkRequest> requests = new ArrayList<>();
7578 for (final NetworkRequest nr : requestsToCopy) {
7579 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007580 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007581 nr.legacyType, nextNetworkRequestId(), nr.type));
7582 }
7583 return requests;
7584 }
7585
7586 @NonNull
7587 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007588 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7589 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007590 // These capabilities are for a TRACK_DEFAULT callback, so:
7591 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7592 // mDefaultRequest and a per-UID default request.
7593 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007594 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007595 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007596 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7597 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007598 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007599 restrictRequestUidsForCallerAndSetRequestorInfo(
7600 netCap, requestorUid, requestorPackageName);
7601 return netCap;
7602 }
7603
7604 /**
7605 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7606 * @param nr the network request to check for equality against.
7607 * @return the nri if one exists, null otherwise.
7608 */
7609 @Nullable
7610 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7611 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7612 if (nri.getNetworkRequestForCallback().equals(nr)) {
7613 return nri;
7614 }
7615 }
7616 return null;
7617 }
7618
7619 /**
7620 * Check if an nri is currently being managed by per-app default networking.
7621 * @param nri the nri to check.
7622 * @return true if this nri is currently being managed by per-app default networking.
7623 */
7624 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7625 // nri.mRequests.get(0) is only different from the original request filed in
7626 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7627 // functionality therefore if these two don't match, it means this particular nri is
7628 // currently being managed by a per-app default.
7629 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7630 }
7631
7632 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007633 * Determine if an nri is a managed default request that disallows default networking.
7634 * @param nri the request to evaluate
7635 * @return true if device-default networking is disallowed
7636 */
7637 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7638 // Check if this nri is a managed default that supports the default network at its
7639 // lowest priority request.
7640 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7641 final NetworkCapabilities lowestPriorityNetCap =
7642 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7643 return isPerAppDefaultRequest(nri)
7644 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7645 lowestPriorityNetCap));
7646 }
7647
Erik Kline05f2b402015-04-30 12:58:40 +09007648 // Request used to optionally keep mobile data active even when higher
7649 // priority networks like Wi-Fi are active.
7650 private final NetworkRequest mDefaultMobileDataRequest;
7651
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007652 // Request used to optionally keep wifi data active even when higher
7653 // priority networks like ethernet are active.
7654 private final NetworkRequest mDefaultWifiRequest;
7655
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007656 // Request used to optionally keep vehicle internal network always active
7657 private final NetworkRequest mDefaultVehicleRequest;
7658
James Mattisd31bdfa2020-12-23 16:37:26 -08007659 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7660 // network with no service. This NAI should never be matched against, nor should any public API
7661 // ever return the associated network. For this reason, this NAI is not in the list of available
7662 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7663 // default requests that don't support using the device default network which will ultimately
7664 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7665 @VisibleForTesting
7666 final NetworkAgentInfo mNoServiceNetwork;
7667
Chalard Jean5b409c72021-02-04 13:12:59 +09007668 // The NetworkAgentInfo currently satisfying the default request, if any.
7669 private NetworkAgentInfo getDefaultNetwork() {
7670 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007671 }
7672
James Mattis2516da32021-01-31 17:06:19 -08007673 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007674 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007675 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7676 // Currently, all network requests will have the same uids therefore checking the first
7677 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007678 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007679 if (null == uids) {
7680 continue;
7681 }
7682 for (final UidRange range : uids) {
7683 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007684 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007685 highestPriorityNri = nri;
7686 }
James Mattis2516da32021-01-31 17:06:19 -08007687 }
7688 }
7689 }
paulhuaa0743d2021-05-26 21:56:03 +08007690 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007691 }
7692
Varun Ananddf569952019-02-06 10:13:38 -08007693 @Nullable
7694 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7695 return nai != null ? nai.network : null;
7696 }
7697
7698 private void ensureRunningOnConnectivityServiceThread() {
7699 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7700 throw new IllegalStateException(
7701 "Not running on ConnectivityService thread: "
7702 + Thread.currentThread().getName());
7703 }
7704 }
7705
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007706 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007707 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7708 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007709 }
7710
Chalard Jean29d06db2018-05-02 21:14:54 +09007711 /**
7712 * Register a new agent with ConnectivityService to handle a network.
7713 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007714 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007715 * @param networkInfo the initial info associated with this network. It can be updated later :
7716 * see {@link #updateNetworkInfo}.
7717 * @param linkProperties the initial link properties of this network. They can be updated
7718 * later : see {@link #updateLinkProperties}.
7719 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007720 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007721 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007722 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007723 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007724 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007725 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007726 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007727 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007728 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7729 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007730 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7731 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7732 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007733 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007734 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007735 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08007736 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007737 } else {
7738 enforceNetworkFactoryPermission();
7739 }
7740
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007741 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007742 final long token = Binder.clearCallingIdentity();
7743 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007744 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007745 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007746 } finally {
7747 Binder.restoreCallingIdentity(token);
7748 }
7749 }
7750
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007751 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007752 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007753 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7754 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007755
Chalard Jeandbc46952022-02-02 00:14:18 +09007756 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
7757 // and mutate them at any time.
7758 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
7759 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
7760 final LinkProperties lpCopy = new LinkProperties(linkProperties);
7761
Chalard Jean366c5252022-01-25 18:27:53 +09007762 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09007763 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09007764 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7765 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007766 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09007767 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007768 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007769 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7770 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007771
Chalard Jeandbc46952022-02-02 00:14:18 +09007772 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09007773 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007774 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007775 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007776 mDeps.getNetworkStack().makeNetworkMonitor(
7777 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007778 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7779 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007780 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007781 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007782 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007783 }
7784
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007785 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007786 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007787 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09007788 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007789 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09007790 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
7791 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
7792 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09007793
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007794 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007795
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007796 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007797 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007798 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007799 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007800
7801 try {
7802 networkMonitor.start();
7803 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007804 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007805 }
Chalard Jean366c5252022-01-25 18:27:53 +09007806
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007807 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007808 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007809 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007810 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007811 }
7812
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007813 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7814 @NonNull public final NetworkOffer offer;
7815
7816 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7817 this.offer = offer;
7818 }
7819
7820 @Override
7821 public void binderDied() {
7822 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7823 }
7824 }
7825
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007826 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7827 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7828 if (npi.providerId == providerId) return true;
7829 }
7830 return false;
7831 }
7832
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007833 /**
7834 * Register or update a network offer.
7835 * @param newOffer The new offer. If the callback member is the same as an existing
7836 * offer, it is an update of that offer.
7837 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007838 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007839 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7840 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007841 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007842 // This may actually happen if a provider updates its score or registers and then
7843 // immediately unregisters. The offer would still be in the handler queue, but the
7844 // provider would have been removed.
7845 if (DBG) log("Received offer from an unregistered provider");
7846 return;
7847 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007848 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7849 if (null != existingOffer) {
7850 handleUnregisterNetworkOffer(existingOffer);
7851 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007852 if (DBG) {
7853 // handleUnregisterNetworkOffer has already logged the old offer
7854 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7855 }
7856 } else {
7857 if (DBG) {
7858 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7859 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007860 }
7861 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7862 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007863 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007864 } catch (RemoteException e) {
7865 noi.binderDied();
7866 return;
7867 }
7868 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007869 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007870 }
7871
7872 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7873 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007874 if (DBG) {
7875 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7876 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007877
7878 // If the provider removes the offer and dies immediately afterwards this
7879 // function may be called twice in a row, but the array will no longer contain
7880 // the offer.
7881 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007882 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007883 }
7884
7885 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7886 @NonNull final INetworkOfferCallback callback) {
7887 ensureRunningOnConnectivityServiceThread();
7888 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007889 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007890 }
7891 return null;
7892 }
7893
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007894 /**
7895 * Called when receiving LinkProperties directly from a NetworkAgent.
7896 * Stores into |nai| any data coming from the agent that might also be written to the network's
7897 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7898 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007899 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007900 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007901 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7902 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007903 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007904 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007905 }
7906
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007907 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08007908 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007909 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007910
Lorenzo Colittid523d142020-04-01 20:16:30 +09007911 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7912 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7913 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007914 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007915
Suprabh Shukla1e312032023-01-24 03:36:37 -08007916 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007917
7918 // update filtering rules, need to happen after the interface update so netd knows about the
7919 // new interface (the interface name -> index map becomes initialized)
7920 updateVpnFiltering(newLp, oldLp, networkAgent);
7921
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007922 updateMtu(newLp, oldLp);
7923 // TODO - figure out what to do for clat
7924// for (LinkProperties lp : newLp.getStackedLinks()) {
7925// updateMtu(lp, null);
7926// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007927 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007928 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7929 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007930
Erik Klineb9888902016-04-05 13:30:49 +09007931 updateRoutes(newLp, oldLp, netId);
7932 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007933 // Make sure LinkProperties represents the latest private DNS status.
7934 // This does not need to be done before updateDnses because the
7935 // LinkProperties are not the source of the private DNS configuration.
7936 // updateDnses will fetch the private DNS configuration from DnsManager.
7937 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007938
Chalard Jean5b409c72021-02-04 13:12:59 +09007939 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007940 handleApplyDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09007941 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007942 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007943 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007944
7945 updateWakeOnLan(newLp);
7946
Hai Shalome58bdc62021-01-11 18:45:34 -08007947 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7948 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7949 // does, it needs to be merged here.
7950 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7951 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007952
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007953 // TODO - move this check to cover the whole function
7954 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007955 synchronized (networkAgent) {
7956 networkAgent.linkProperties = newLp;
7957 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007958 // Start or stop DNS64 detection and 464xlat according to network state.
7959 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08007960 // Notify NSS when relevant events happened. Currently, NSS only cares about
7961 // interface changed to update clat interfaces accounting.
7962 final boolean interfacesChanged = oldLp == null
7963 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
7964 if (interfacesChanged) {
7965 notifyIfacesChangedForNetworkStats();
7966 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007967 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7968 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09007969 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007970 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007971
7972 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007973 }
7974
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09007975 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
7976 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
7977 }
7978
Hai Shalome58bdc62021-01-11 18:45:34 -08007979 /**
7980 * @param naData captive portal data from NetworkAgent
7981 * @param apiData captive portal data from capport API
7982 */
7983 @Nullable
7984 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7985 CaptivePortalData apiData) {
7986 if (naData == null || apiData == null) {
7987 return naData == null ? apiData : naData;
7988 }
7989 final CaptivePortalData.Builder captivePortalBuilder =
7990 new CaptivePortalData.Builder(naData);
7991
7992 if (apiData.isCaptive()) {
7993 captivePortalBuilder.setCaptive(true);
7994 }
7995 if (apiData.isSessionExtendable()) {
7996 captivePortalBuilder.setSessionExtendable(true);
7997 }
7998 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7999 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8000 // otherwise data would be inconsistent. Prefer the capport API info if present,
8001 // as it can generally be refreshed more often.
8002 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8003 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8004 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8005 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8006 // No source has time / bytes remaining information: surface the newest refresh time
8007 // for other fields
8008 captivePortalBuilder.setRefreshTime(
8009 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8010 }
8011
Hai Shalom7c6ab402021-02-04 19:34:06 -08008012 // Prioritize the user portal URL from the network agent if the source is authenticated.
8013 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8014 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8015 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8016 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008017 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008018 // Prioritize the venue information URL from the network agent if the source is
8019 // authenticated.
8020 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8021 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8022 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8023 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008024 }
8025 return captivePortalBuilder.build();
8026 }
8027
Suprabh Shukla53e16392023-04-26 18:47:36 -07008028 @VisibleForTesting
8029 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008030 // This needs to be kept in sync and backwards compatible with the decoding logic in
8031 // NetdEventListenerService, which is non-mainline code.
8032 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8033 }
8034
Suprabh Shukla75642282023-04-25 23:15:43 -07008035 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8036 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8037 return true;
8038 }
8039 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8040 return true;
8041 }
8042 return false;
8043 }
8044
Suprabh Shukla1e312032023-01-24 03:36:37 -08008045 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008046 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008047 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008048 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008049 return;
8050 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008051
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008052 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
8053 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
8054
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008055 // Mask/mark of zero will not detect anything interesting.
8056 // Don't install rules unless both values are nonzero.
8057 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008058 return;
8059 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008060
Suprabh Shukla1e312032023-01-24 03:36:37 -08008061 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008062 try {
8063 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08008064 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008065 } else {
Luke Huang46289a22018-09-27 19:33:11 +08008066 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008067 }
8068 } catch (Exception e) {
8069 loge("Exception modifying wakeup packet monitoring: " + e);
8070 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008071 }
8072
Junyu Lai970963e2022-10-25 15:46:47 +08008073 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008074 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008075 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008076 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008077 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008078 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008079 for (final String iface : interfaceDiff.added) {
8080 try {
8081 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008082 mNetd.networkAddInterface(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008083 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008084 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008085 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008086 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008087 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008088 }
Paul Jensenbff73492014-04-28 10:33:11 -04008089 }
8090 }
Chalard Jean9589e722019-11-19 19:03:53 +09008091 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008092 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008093 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008094 wakeupModifyInterface(iface, nai, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008095 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008096 } catch (Exception e) {
8097 loge("Exception removing interface: " + e);
8098 }
8099 }
8100 }
8101
Tyler Weare4314862019-12-05 14:55:30 -08008102 // TODO: move to frameworks/libs/net.
8103 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
8104 final String nextHop;
8105
8106 switch (route.getType()) {
8107 case RouteInfo.RTN_UNICAST:
8108 if (route.hasGateway()) {
8109 nextHop = route.getGateway().getHostAddress();
8110 } else {
8111 nextHop = INetd.NEXTHOP_NONE;
8112 }
8113 break;
8114 case RouteInfo.RTN_UNREACHABLE:
8115 nextHop = INetd.NEXTHOP_UNREACHABLE;
8116 break;
8117 case RouteInfo.RTN_THROW:
8118 nextHop = INetd.NEXTHOP_THROW;
8119 break;
8120 default:
8121 nextHop = INetd.NEXTHOP_NONE;
8122 break;
8123 }
8124
8125 final RouteInfoParcel rip = new RouteInfoParcel();
8126 rip.ifName = route.getInterface();
8127 rip.destination = route.getDestination().toString();
8128 rip.nextHop = nextHop;
8129 rip.mtu = route.getMtu();
8130
8131 return rip;
8132 }
8133
Paul Jensene0fd4a82014-08-06 15:51:33 -04008134 /**
8135 * Have netd update routes from oldLp to newLp.
8136 * @return true if routes changed between oldLp and newLp
8137 */
Junyu Lai970963e2022-10-25 15:46:47 +08008138 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8139 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008140 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008141 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8142 new CompareOrUpdateResult<>(
8143 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008144 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008145 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008146
8147 // add routes before removing old in case it helps with continuous connectivity
8148
Chalard Jean9dd11612018-06-04 16:52:49 +09008149 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008150 for (RouteInfo route : routeDiff.added) {
8151 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008152 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008153 try {
Tyler Weare4314862019-12-05 14:55:30 -08008154 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008155 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008156 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008157 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008158 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008159 }
8160 }
8161 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008162 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008163 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008164 try {
Tyler Weare4314862019-12-05 14:55:30 -08008165 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008166 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008167 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008168 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008169 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008170 }
8171 }
8172
8173 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008174 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008175 try {
Tyler Weare4314862019-12-05 14:55:30 -08008176 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008177 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08008178 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008179 }
8180 }
Tyler Weare4314862019-12-05 14:55:30 -08008181
8182 for (RouteInfo route : routeDiff.updated) {
8183 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8184 try {
8185 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
8186 } catch (Exception e) {
8187 loge("Exception in networkUpdateRouteParcel: " + e);
8188 }
8189 }
8190 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8191 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008192 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008193
Junyu Lai970963e2022-10-25 15:46:47 +08008194 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8195 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008196 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8197 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008198 }
Erik Klineb9888902016-04-05 13:30:49 +09008199
Erik Kline31b4a9e2018-01-11 21:07:29 +09008200 if (DBG) {
8201 final Collection<InetAddress> dnses = newLp.getDnsServers();
8202 log("Setting DNS servers for network " + netId + " to " + dnses);
8203 }
Erik Klineb9888902016-04-05 13:30:49 +09008204 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008205 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008206 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008207 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008208 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008209 }
Erik Kline54e35c02017-04-07 15:29:29 +09008210 }
8211
Junyu Lai970963e2022-10-25 15:46:47 +08008212 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8213 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008214 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8215 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008216 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8217 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008218
8219 if (!wasFiltering && !needsFiltering) {
8220 // Nothing to do.
8221 return;
8222 }
8223
8224 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8225 // Nothing changed.
8226 return;
8227 }
8228
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008229 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008230 if (ranges == null || ranges.isEmpty()) {
8231 return;
8232 }
8233
Qingxi Libb8da982020-01-17 17:54:27 -08008234 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008235 // TODO: this create a window of opportunity for apps to receive traffic between the time
8236 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008237 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008238 // old rules are being removed.
8239 if (wasFiltering) {
8240 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8241 }
8242 if (needsFiltering) {
8243 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8244 }
8245 }
8246
Valentin Iftime9fa35092019-09-24 13:32:13 +02008247 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008248 if (mWolSupportedInterfaces == null) {
8249 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008250 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008251 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008252 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8253 }
8254
Luke Huangb913c812018-08-24 20:33:16 +08008255 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008256 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008257 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008258 }
8259 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008260 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008261 }
Luke Huangb913c812018-08-24 20:33:16 +08008262 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008263 }
8264
Chalard Jean62edfd82019-12-02 18:39:29 +09008265 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8266 @NonNull final NetworkCapabilities newNc) {
8267 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8268 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008269 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008270 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008271 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008272 } catch (RemoteException | ServiceSpecificException e) {
8273 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008274 }
8275 }
8276 }
8277
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008278 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008279 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008280 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008281 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008282 underlyingNetworks = underlyingNetworksOrDefault(
8283 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008284 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008285 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8286 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008287 // metered if any underlying is metered, or originally declared metered by the agent.
8288 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008289 boolean roaming = false; // roaming if any underlying is roaming
8290 boolean congested = false; // congested if any underlying is congested
8291 boolean suspended = true; // suspended if all underlying are suspended
8292
8293 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008294 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008295 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008296 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008297 for (Network underlyingNetwork : underlyingNetworks) {
8298 final NetworkAgentInfo underlying =
8299 getNetworkAgentInfoForNetwork(underlyingNetwork);
8300 if (underlying == null) continue;
8301
8302 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8303 hadUnderlyingNetworks = true;
8304 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008305 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008306 }
8307
8308 // Merge capabilities of this underlying network. For bandwidth, assume the
8309 // worst case.
8310 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8311 underlyingCaps.getLinkDownstreamBandwidthKbps());
8312 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8313 underlyingCaps.getLinkUpstreamBandwidthKbps());
8314 // If this underlying network is metered, the VPN is metered (it may cost money
8315 // to send packets on this network).
8316 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8317 // If this underlying network is roaming, the VPN is roaming (the billing structure
8318 // is different than the usual, local one).
8319 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8320 // If this underlying network is congested, the VPN is congested (the current
8321 // condition of the network affects the performance of this network).
8322 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8323 // If this network is not suspended, the VPN is not suspended (the VPN
8324 // is able to transfer some data).
8325 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008326 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008327 }
8328 }
8329 if (!hadUnderlyingNetworks) {
8330 // No idea what the underlying networks are; assume reasonable defaults
8331 metered = true;
8332 roaming = false;
8333 congested = false;
8334 suspended = false;
8335 }
8336
Chalard Jean1d420b32022-10-12 16:39:37 +09008337 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008338 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8339 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8340 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8341 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8342 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8343 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008344 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008345 }
8346
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008347 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008348 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8349 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8350 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008351 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008352 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008353 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008354 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008355 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8356 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008357 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008358 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008359 if (nai.everConnected()
8360 && !nai.isVPN()
8361 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008362 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008363 // does not cause any request (that is not a listen) currently matching that agent to
8364 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008365 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008366 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008367 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008368 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008369 }
8370
Paul Jensen53f08952015-06-16 14:27:36 -04008371 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008372 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008373 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008374 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008375 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008376 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008377 }
Chalard Jean254bd162022-08-25 13:04:51 +09008378 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008379 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008380 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008381 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008382 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008383 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008384 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008385 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008386 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008387 }
Chalard Jean254bd162022-08-25 13:04:51 +09008388 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008389 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8390 } else {
8391 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8392 }
lucasline117e2e2019-10-22 18:27:33 +08008393 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008394
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008395 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008396 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8397 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008398 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008399 }
8400
Lorenzo Colittibd079452021-07-02 11:47:57 +09008401 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008402 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008403 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008404 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008405 }
8406
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008407 return newNc;
8408 }
8409
Lorenzo Colitti44840702021-01-11 22:27:57 +09008410 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8411 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8412 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8413 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8414 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8415 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8416 if (prevSuspended != suspended) {
8417 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8418 // onResumed have been removed.
8419 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8420 : ConnectivityManager.CALLBACK_RESUMED);
8421 }
8422 if (prevSuspended != suspended || prevRoaming != roaming) {
8423 // updateNetworkInfo will mix in the suspended info from the capabilities and
8424 // take appropriate action for the network having possibly changed state.
8425 updateNetworkInfo(nai, nai.networkInfo);
8426 }
8427 }
8428
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008429 /**
8430 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8431 *
8432 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8433 * capabilities we manage and store in {@code nai}, such as validated status and captive
8434 * portal status)
8435 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8436 * potentially triggers rematches.
8437 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8438 * change.)
8439 *
8440 * @param oldScore score of the network before any of the changes that prompted us
8441 * to call this function.
8442 * @param nai the network having its capabilities updated.
8443 * @param nc the new network capabilities.
8444 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008445 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008446 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008447 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008448 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008449 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8450 if (null != differences) {
8451 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8452 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008453 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008454 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008455
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008456 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008457 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008458 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008459
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008460 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008461 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8462 // the change we're processing can't affect any requests, it can only affect the listens
8463 // on this network. We might have been called by rematchNetworkAndRequests when a
8464 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008465 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008466 } else {
8467 // If the requestable capabilities have changed or the score changed, we can't have been
8468 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008469 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008470 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008471 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008472 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008473
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008474 final boolean oldMetered = prevNc.isMetered();
8475 final boolean newMetered = newNc.isMetered();
8476 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008477
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008478 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008479 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8480 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008481 }
junyulaif2c67e42018-08-07 19:50:45 +08008482
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008483 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8484 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008485
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008486 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008487 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008488 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008489 }
8490
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008491 // This network might have been underlying another network. Propagate its capabilities.
8492 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008493
8494 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008495 mDnsManager.updateTransportsForNetwork(
8496 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008497 }
lucaslin53e8a262021-06-08 01:43:59 +08008498
8499 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008500 }
8501
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008502 /** Convenience method to update the capabilities for a given network. */
8503 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008504 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008505 }
8506
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008507 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008508 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008509 *
8510 * Ingress interface filtering enforces that all apps under the given network can only receive
8511 * packets from the network's interface (and loopback). This is important for VPNs because
8512 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8513 * non-VPN interfaces.
8514 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008515 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008516 * 1. the network is an app VPN (not legacy VPN)
8517 * 2. the VPN does not allow bypass
8518 * 3. the VPN is fully-routed
8519 * 4. the VPN interface is non-null
8520 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008521 * @see INetd#firewallAddUidInterfaceRules
8522 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008523 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008524 @Nullable
8525 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008526 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008527 if (nc == null || lp == null) return null;
8528 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008529 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008530 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008531 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008532 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008533 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008534 && !lp.hasExcludeRoute()) {
8535 return lp.getInterfaceName();
8536 }
8537 return null;
8538 }
8539
8540 /**
8541 * Returns whether we need to set interface filtering rule or not
8542 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008543 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008544 String isolationIface) {
8545 // Allow rules are always needed if VPN isolation is enabled.
8546 if (isolationIface != null) return true;
8547
8548 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8549 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8550 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
8551 return SdkLevel.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008552 }
8553
Chiachang Wang28afaff2020-12-10 22:24:47 +08008554 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8555 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8556 int index = 0;
8557 for (UidRange range : ranges) {
8558 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8559 index++;
8560 }
8561 return stableRanges;
8562 }
8563
Chalard Jeane6c95272022-01-25 21:04:21 +09008564 private static UidRangeParcel[] intsToUidRangeStableParcels(
8565 final @NonNull ArraySet<Integer> uids) {
8566 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8567 int index = 0;
8568 for (int uid : uids) {
8569 stableRanges[index] = new UidRangeParcel(uid, uid);
8570 index++;
8571 }
8572 return stableRanges;
8573 }
8574
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008575 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8576 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8577 for (int i = 0; i < ranges.length; i++) {
8578 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8579 }
8580 return stableRanges;
8581 }
8582
Motomu Utsumi93a22182023-03-16 17:04:21 +09008583 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
8584 Set<Integer> exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08008585 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8586 try {
Motomu Utsumi93a22182023-03-16 17:04:21 +09008587 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008588 } catch (Exception e) {
8589 loge("Exception in socket destroy: ", e);
8590 }
8591 }
8592 }
8593
paulhuaa0743d2021-05-26 21:56:03 +08008594 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi93a22182023-03-16 17:04:21 +09008595 final Set<Integer> exemptUids = new ArraySet<>();
Ken Chen5e65a852020-12-24 12:59:10 +08008596 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8597 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8598 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi93a22182023-03-16 17:04:21 +09008599 exemptUids.add(VPN_UID);
8600 exemptUids.add(nai.networkCapabilities.getOwnerUid());
Ken Chen5e65a852020-12-24 12:59:10 +08008601 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8602
Motomu Utsumi6345e462023-03-13 13:24:50 +09008603 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi93a22182023-03-16 17:04:21 +09008604 maybeCloseSockets(nai, uidRanges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008605 try {
8606 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008607 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008608 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008609 } else {
paulhu0e79d952021-06-09 16:11:35 +08008610 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008611 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008612 }
8613 } catch (Exception e) {
8614 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8615 " on netId " + nai.network.netId + ". " + e);
8616 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09008617 // Close sockets that established connection while requesting netd.
Motomu Utsumi93a22182023-03-16 17:04:21 +09008618 maybeCloseSockets(nai, uidRanges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008619 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008620
lucaslin53e8a262021-06-08 01:43:59 +08008621 private boolean isProxySetOnAnyDefaultNetwork() {
8622 ensureRunningOnConnectivityServiceThread();
8623 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8624 final NetworkAgentInfo nai = nri.getSatisfier();
8625 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8626 return true;
8627 }
8628 }
8629 return false;
8630 }
8631
8632 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8633 NetworkCapabilities newNc) {
8634 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8635 // the proxy might be changed since the default network satisfied by the apps might also
8636 // changed.
8637 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8638 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008639 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8640 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008641 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008642 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8643 mProxyTracker.sendProxyBroadcast();
8644 }
8645 }
8646
Chalard Jeane6c95272022-01-25 21:04:21 +09008647 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8648 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008649 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8650 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008651 if (null == prevRanges) prevRanges = new ArraySet<>();
8652 if (null == newRanges) newRanges = new ArraySet<>();
8653 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8654
8655 prevRanges.removeAll(newRanges);
8656 newRanges.removeAll(prevRangesCopy);
8657
8658 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008659 // When updating the VPN uid routing rules, add the new range first then remove the old
8660 // range. If old range were removed first, there would be a window between the old
8661 // range being removed and the new range being added, during which UIDs contained
8662 // in both ranges are not subject to any VPN routing rules. Adding new range before
8663 // removing old range works because, unlike the filtering rules below, it's possible to
8664 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008665 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8666 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8667 // [1-5] & [1-2],[4-5] == [3]
8668 // Then we can do:
8669 // maybeCloseSockets([3])
8670 // mNetd.networkAddUidRanges([1-2],[4-5])
8671 // mNetd.networkRemoveUidRanges([1-5])
8672 // maybeCloseSockets([3])
8673 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8674 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008675 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008676 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008677 }
8678 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008679 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008680 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00008681 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
8682 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008683 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
8684 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008685 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008686 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008687 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8688 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8689 // were added first and then newRanges got removed later, there would be only one uid
8690 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8691 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8692 // Note that this is in contrast with the (more robust) update of VPN routing rules
8693 // above, where the addition of new ranges happens before the removal of old ranges.
8694 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8695 // to be removed will never overlap with the new range to be added.
8696 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008697 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
8698 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008699 }
8700 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008701 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008702 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008703 } catch (Exception e) {
8704 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008705 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008706 }
8707 }
8708
Chalard Jeande665262022-02-25 16:12:12 +09008709 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09008710 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8711 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09008712 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
8713 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09008714 if (prevEmpty && newEmpty) return;
8715
8716 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09008717 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008718 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09008719 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008720
8721 if (prevUids.equals(newUids)) return;
8722
8723 // This implementation is very simple and vastly faster for sets of Integers than
8724 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8725 // a key computed from the value and has storage for that.
8726 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8727 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8728 toRemove.removeAll(newUids);
8729 toAdd.removeAll(prevUids);
8730
8731 try {
8732 if (!toAdd.isEmpty()) {
8733 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8734 nai.network.netId,
8735 intsToUidRangeStableParcels(toAdd),
8736 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8737 }
8738 if (!toRemove.isEmpty()) {
8739 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8740 nai.network.netId,
8741 intsToUidRangeStableParcels(toRemove),
8742 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8743 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008744 } catch (ServiceSpecificException e) {
8745 // Has the interface disappeared since the network was built ?
8746 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008747 } catch (RemoteException e) {
8748 // Netd died. This usually causes a runtime restart anyway.
8749 }
8750 }
8751
Junyu Lai2ed7d412022-10-07 16:52:21 +08008752 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
8753 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008754 ensureRunningOnConnectivityServiceThread();
8755
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008756 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008757 // Ignore updates for disconnected networks
8758 return;
8759 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008760 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008761 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09008762 + "; created=" + nai.getCreatedTime()
8763 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00008764 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008765 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8766 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008767 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008768 }
8769
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008770 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8771 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008772 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008773 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008774 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008775 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8776 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8777 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008778 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8779 // need to be sent as a separate extra.
8780 final NetworkRequest req = nri.isMultilayerRequest()
8781 ? nri.getActiveRequest()
8782 // Non-multilayer listen requests do not have an active request
8783 : nri.mRequests.get(0);
8784 if (req == null) {
8785 Log.wtf(TAG, "No request in NRI " + nri);
8786 }
8787 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008788 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008789 sendIntent(nri.mPendingIntent, intent);
8790 }
8791 // else not handled
8792 }
8793
Michael Groover73f69482023-01-27 11:01:25 -06008794 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
8795 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008796 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8797 mPendingIntentWakeLock.acquire();
8798 try {
8799 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00008800 final BroadcastOptions options = BroadcastOptions.makeBasic();
8801 if (SdkLevel.isAtLeastT()) {
8802 // Explicitly disallow the receiver from starting activities, to prevent apps from
8803 // utilizing the PendingIntent as a backdoor to do this.
8804 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
8805 }
8806 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
8807 null /* requiredPermission */,
8808 SdkLevel.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008809 } catch (PendingIntent.CanceledException e) {
8810 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8811 mPendingIntentWakeLock.release();
8812 releasePendingNetworkRequest(pendingIntent);
8813 }
8814 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8815 }
8816
8817 @Override
8818 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8819 String resultData, Bundle resultExtras) {
8820 if (DBG) log("Finished sending " + pendingIntent);
8821 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008822 // Release with a delay so the receiving client has an opportunity to put in its
8823 // own request.
8824 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008825 }
8826
Chalard Jean46bfbf02022-02-02 00:56:25 +09008827 // networkAgent is only allowed to be null if notificationType is
8828 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
8829 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08008830 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09008831 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08008832 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008833 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008834 // Default request has no msgr. Also prevents callbacks from being invoked for
8835 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8836 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8837 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008838 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008839 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008840 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008841 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008842 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008843 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008844 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008845 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8846 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008847 }
Roshan Pius951c0032020-12-22 15:10:42 -08008848 final boolean includeLocationSensitiveInfo =
8849 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008850 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008851 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008852 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08008853 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09008854 networkCapabilitiesRestrictedForCallerPermissions(
8855 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
8856 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008857 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09008858 nri.mCallingAttributionTag);
8859 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008860 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8861 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008862 // For this notification, arg1 contains the blocked status.
8863 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008864 break;
8865 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008866 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008867 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008868 break;
8869 }
8870 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008871 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008872 final NetworkCapabilities netCap =
8873 networkCapabilitiesRestrictedForCallerPermissions(
8874 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8875 putParcelable(
8876 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008877 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008878 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008879 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008880 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008881 break;
8882 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008883 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008884 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8885 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008886 break;
8887 }
junyulaif2c67e42018-08-07 19:50:45 +08008888 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008889 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008890 msg.arg1 = arg1;
8891 break;
8892 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008893 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008894 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008895 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008896 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008897 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008898 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008899 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008900 }
James Mattis45d81842021-01-10 14:24:24 -08008901 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008902 } catch (RemoteException e) {
8903 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008904 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008905 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008906 }
8907
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008908 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8909 bundle.putParcelable(t.getClass().getSimpleName(), t);
8910 }
8911
Chalard Jean0702f982021-09-16 21:50:07 +09008912 /**
8913 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8914 *
8915 * When a request should be assigned to a new network, it is normally lingered to give
8916 * time for apps to gracefully migrate their connections. When both networks are on the same
8917 * radio, but that radio can't do time-sharing efficiently, this may end up being
8918 * counter-productive because any traffic on the old network may drastically reduce the
8919 * performance of the new network.
8920 * The stack supports a configuration to let modem vendors state that their radio can't
8921 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8922 * from one cell network to another can't be done gracefully.
8923 *
8924 * @param oldNai the old network serving the request
8925 * @param newNai the new network serving the request
8926 * @return whether the switch can be graceful
8927 */
8928 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8929 @NonNull final NetworkAgentInfo newSatisfier) {
8930 if (mCellularRadioTimesharingCapable) return true;
8931 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8932 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8933 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8934 }
8935
Paul Jensenaf94b982014-09-30 15:37:41 -04008936 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008937 if (nai.numRequestNetworkRequests() != 0) {
8938 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8939 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008940 // Ignore listening and track default requests.
8941 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008942 loge("Dead network still had at least " + nr);
8943 break;
8944 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008945 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008946 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008947 }
8948
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008949 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8950 if (oldNetwork == null) {
8951 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8952 return;
8953 }
Chalard Jean49707572019-12-10 21:07:02 +09008954 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008955
8956 // If we get here it means that the last linger timeout for this network expired. So there
8957 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008958 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008959
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008960 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008961 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008962 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008963 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008964 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008965 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008966 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008967 }
8968
James Mattise3ef1912020-12-20 11:09:58 -08008969 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8970 boolean isDefaultChanged = false;
8971 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8972 final NetworkReassignment.RequestReassignment reassignment =
8973 changes.getReassignment(defaultRequestInfo);
8974 if (null == reassignment) {
8975 continue;
8976 }
8977 // reassignment only contains those instances where the satisfying network changed.
8978 isDefaultChanged = true;
8979 // Notify system services of the new default.
8980 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8981 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008982
James Mattise3ef1912020-12-20 11:09:58 -08008983 if (isDefaultChanged) {
8984 // Hold a wakelock for a short time to help apps in migrating to a new default.
8985 scheduleReleaseNetworkTransitionWakelock();
8986 }
8987 }
8988
8989 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8990 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8991 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8992 if (DBG) {
8993 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8994 }
Chalard Jean8e382112019-12-03 20:45:30 +09008995
James Mattisd31bdfa2020-12-23 16:37:26 -08008996 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8997 if (newDefaultNetwork != null) {
8998 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008999 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009000
James Mattisd31bdfa2020-12-23 16:37:26 -08009001 // Set an app level managed default and return since further processing only applies to the
9002 // default network.
9003 if (mDefaultRequest != nri) {
9004 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9005 return;
9006 }
9007
9008 makeDefaultNetwork(newDefaultNetwork);
9009
James Mattise3ef1912020-12-20 11:09:58 -08009010 if (oldDefaultNetwork != null) {
9011 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9012 }
9013 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009014 handleApplyDefaultProxy(null != newDefaultNetwork
9015 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
9016 updateTcpBufferSizes(null != newDefaultNetwork
9017 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009018 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009019 }
9020
James Mattisd31bdfa2020-12-23 16:37:26 -08009021 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9022 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9023 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9024 try {
9025 if (VDBG) {
9026 log("Setting default network for " + nri
9027 + " using UIDs " + nri.getUids()
9028 + " with old network " + (oldDefaultNetwork != null
9029 ? oldDefaultNetwork.network().getNetId() : "null")
9030 + " and new network " + (newDefaultNetwork != null
9031 ? newDefaultNetwork.network().getNetId() : "null"));
9032 }
9033 if (nri.getUids().isEmpty()) {
9034 throw new IllegalStateException("makeDefaultForApps called without specifying"
9035 + " any applications to set as the default." + nri);
9036 }
9037 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009038 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009039 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009040 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009041 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009042 }
9043 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009044 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009045 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009046 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009047 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009048 }
9049 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009050 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009051 }
9052 }
9053
Junyu Lai35665cc2022-12-19 17:37:48 +08009054 /**
9055 * Collect restricted uid ranges for the given network and UserHandle, these uids
9056 * are not restricted for matched enterprise networks but being restricted for non-matched
9057 * enterprise networks and non-enterprise networks.
9058 */
9059 @NonNull
9060 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9061 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9062 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9063 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9064 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9065
9066 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9067 // The NC is built from a `ProfileNetworkPreference` which has only one
9068 // enterprise ID, so it's guaranteed to have exactly one.
9069 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9070 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9071 continue;
9072 }
9073 }
9074
9075 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9076 pref.capabilities.getUidRanges())) {
9077 throw new IllegalArgumentException(
9078 "Overlapping uid range in preference: " + pref);
9079 }
9080 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9081 }
9082 return restrictedUidRanges;
9083 }
9084
9085 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009086 // Netd command is not implemented before U.
9087 if (!SdkLevel.isAtLeastU()) return;
9088
Junyu Lai35665cc2022-12-19 17:37:48 +08009089 ensureRunningOnConnectivityServiceThread();
9090 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9091 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9092 .getUserHandles(true /* excludeDying */);
9093 if (users.isEmpty()) {
9094 throw new IllegalStateException("No user is available");
9095 }
9096
9097 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9098 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9099 for (final UserHandle user : users) {
9100 final ArraySet<UidRange> restrictedUidRanges =
9101 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9102 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9103 UidRange.createForUser(user), restrictedUidRanges));
9104 }
9105
9106 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9107 configs.add(new NativeUidRangeConfig(
9108 nai.network.netId, rangesParcel, 0 /* subPriority */));
9109 }
9110
9111 // The netd API replaces the previous configs with the current configs.
9112 // Thus, for network disconnection or preference removal, no need to
9113 // unset previous config. Instead, collecting all currently needed
9114 // configs and issue to netd.
9115 try {
9116 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9117 } catch (ServiceSpecificException e) {
9118 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009119 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009120 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009121 // Netd died. This will cause a runtime restart anyway.
9122 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009123 }
9124 }
9125
James Mattisd31bdfa2020-12-23 16:37:26 -08009126 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9127 try {
9128 if (null != newDefaultNetwork) {
9129 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9130 } else {
9131 mNetd.networkClearDefault();
9132 }
9133 } catch (RemoteException | ServiceSpecificException e) {
9134 loge("Exception setting default network :" + e);
9135 }
9136 }
9137
Chalard Jean05cbe972019-12-09 11:50:38 +09009138 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009139 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009140 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009141 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009142 processNewlySatisfiedListenRequests(nai);
9143 }
9144
9145 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009146 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9147 if (nri.isMultilayerRequest()) {
9148 continue;
9149 }
9150 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009151 if (!nr.isListen()) continue;
9152 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009153 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009154 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9155 }
9156 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009157 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009158
Chalard Jeancd397a22019-11-22 22:33:33 +09009159 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009160 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9161 if (nri.isMultilayerRequest()) {
9162 continue;
9163 }
9164 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009165 if (!nr.isListen()) continue;
9166 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9167 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009168 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009169 }
9170 }
9171 }
9172
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009173 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009174 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009175 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009176 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009177 @Nullable public final NetworkRequest mOldNetworkRequest;
9178 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009179 @Nullable public final NetworkAgentInfo mOldNetwork;
9180 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009181 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009182 @Nullable final NetworkRequest oldNetworkRequest,
9183 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009184 @Nullable final NetworkAgentInfo oldNetwork,
9185 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009186 mNetworkRequestInfo = networkRequestInfo;
9187 mOldNetworkRequest = oldNetworkRequest;
9188 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009189 mOldNetwork = oldNetwork;
9190 mNewNetwork = newNetwork;
9191 }
Chalard Jean49707572019-12-10 21:07:02 +09009192
9193 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009194 final NetworkRequest requestToShow = null != mNewNetworkRequest
9195 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9196 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009197 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9198 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009199 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009200 }
9201
Chalard Jean46a62372019-12-10 21:25:24 +09009202 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009203
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009204 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009205 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009206 }
9207
9208 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009209 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009210 // The code is never supposed to add two reassignments of the same request. Make
9211 // sure this stays true, but without imposing this expensive check on all
9212 // reassignments on all user devices.
9213 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009214 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009215 throw new IllegalStateException("Trying to reassign ["
9216 + reassignment + "] but already have ["
9217 + existing + "]");
9218 }
9219 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009220 }
Chalard Jean46a62372019-12-10 21:25:24 +09009221 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009222 }
9223
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009224 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009225 // the passed request.
9226 @Nullable
9227 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009228 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009229 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009230 }
9231 return null;
9232 }
Chalard Jean49707572019-12-10 21:07:02 +09009233
9234 public String toString() {
9235 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9236 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009237 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009238 for (final RequestReassignment rr : getRequestReassignments()) {
9239 sj.add(rr.toString());
9240 }
9241 return sj.toString();
9242 }
9243
9244 public String debugString() {
9245 final StringBuilder sb = new StringBuilder();
9246 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009247 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009248 for (final RequestReassignment rr : getRequestReassignments()) {
9249 sb.append("\n ").append(rr);
9250 }
9251 return sb.append("\n").toString();
9252 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009253 }
9254
Chalard Jean24344d72019-12-04 13:32:31 +09009255 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009256 @Nullable final NetworkRequest previousRequest,
9257 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009258 @Nullable final NetworkAgentInfo previousSatisfier,
9259 @Nullable final NetworkAgentInfo newSatisfier,
9260 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009261 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009262 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009263 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009264 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009265 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09009266 }
James Mattisa076c532020-12-02 14:12:41 -08009267 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009268 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009269 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009270 // If this network switch can't be supported gracefully, the request is not
9271 // lingered. This allows letting go of the network sooner to reclaim some
9272 // performance on the new network, since the radio can't do both at the same
9273 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009274 //
9275 // Also don't linger the request if the old network has been destroyed.
9276 // A destroyed network does not provide actual network connectivity, so
9277 // lingering it is not useful. In particular this ensures that a destroyed
9278 // network is outscored by its replacement,
9279 // then it is torn down immediately instead of being lingered, and any apps that
9280 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009281 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9282 }
Chalard Jean24344d72019-12-04 13:32:31 +09009283 } else {
9284 if (VDBG || DDBG) log(" accepting network in place of null");
9285 }
junyulai0ac374f2020-12-14 18:41:52 +08009286
9287 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9288 // and immediately satisfies a request then remove the timer. This will happen for
9289 // all networks except in the case of an underlying network for a VCN.
9290 if (newSatisfier.isNascent()) {
9291 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009292 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009293 }
9294
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009295 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009296 newSatisfier.unlingerRequest(newRequest.requestId);
9297 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009298 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009299 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009300 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009301 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009302 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009303 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009304 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009305 }
James Mattisa076c532020-12-02 14:12:41 -08009306 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009307 }
James Mattisa076c532020-12-02 14:12:41 -08009308 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009309 }
9310
James Mattisa076c532020-12-02 14:12:41 -08009311 /**
9312 * This function is triggered when something can affect what network should satisfy what
9313 * request, and it computes the network reassignment from the passed collection of requests to
9314 * network match to the one that the system should now have. That data is encoded in an
9315 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9316 * satisfier.
9317 *
9318 * After the reassignment is computed, it is applied to the state objects.
9319 *
9320 * @param networkRequests the nri objects to evaluate for possible network reassignment
9321 * @return NetworkReassignment listing of proposed network assignment changes
9322 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009323 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009324 private NetworkReassignment computeNetworkReassignment(
9325 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009326 final NetworkReassignment changes = new NetworkReassignment();
9327
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009328 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009329 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009330 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009331 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009332 }
Chalard Jean857a1712019-12-10 21:08:07 +09009333
James Mattisa076c532020-12-02 14:12:41 -08009334 for (final NetworkRequestInfo nri : networkRequests) {
9335 // Non-multilayer listen requests can be ignored.
9336 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9337 continue;
9338 }
9339 NetworkAgentInfo bestNetwork = null;
9340 NetworkRequest bestRequest = null;
9341 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009342 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009343 // Stop evaluating as the highest possible priority request is satisfied.
9344 if (null != bestNetwork) {
9345 bestRequest = req;
9346 break;
9347 }
9348 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009349 if (null == bestNetwork && isDefaultBlocked(nri)) {
9350 // Remove default networking if disallowed for managed default requests.
9351 bestNetwork = mNoServiceNetwork;
9352 }
9353 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009354 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009355 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009356 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009357 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009358 }
9359 return changes;
9360 }
9361
James Mattisa076c532020-12-02 14:12:41 -08009362 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9363 return new HashSet<>(mNetworkRequests.values());
9364 }
9365
Paul Jensenc88b39b2015-06-16 14:27:36 -04009366 /**
James Mattisa076c532020-12-02 14:12:41 -08009367 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009368 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009369 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009370 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009371 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9372 }
9373
9374 /**
9375 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9376 * being disconnected.
9377 */
9378 private void rematchNetworksAndRequests(
9379 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9380 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009381 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009382 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009383 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009384 final long computed = SystemClock.elapsedRealtime();
9385 applyNetworkReassignment(changes, start);
9386 final long applied = SystemClock.elapsedRealtime();
9387 issueNetworkNeeds();
9388 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009389 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009390 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9391 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009392 log(changes.debugString());
9393 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009394 // Shorter form, only one line of log
9395 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9396 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009397 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009398 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009399
Chalard Jeand7f762d2019-12-10 19:01:29 +09009400 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009401 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009402 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009403
9404 // Since most of the time there are only 0 or 1 background networks, it would probably
9405 // be more efficient to just use an ArrayList here. TODO : measure performance
9406 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9407 for (final NetworkAgentInfo nai : nais) {
9408 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9409 }
9410
Chalard Jeand7f762d2019-12-10 19:01:29 +09009411 // First, update the lists of satisfied requests in the network agents. This is necessary
9412 // because some code later depends on this state to be correct, most prominently computing
9413 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009414 for (final NetworkReassignment.RequestReassignment event :
9415 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009416 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9417 event.mOldNetworkRequest, event.mNewNetworkRequest,
9418 event.mOldNetwork, event.mNewNetwork,
9419 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009420 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009421
James Mattise3ef1912020-12-20 11:09:58 -08009422 // Process default network changes if applicable.
9423 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009424
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009425 // Notify requested networks are available after the default net is switched, but
9426 // before LegacyTypeTracker sends legacy broadcasts
9427 for (final NetworkReassignment.RequestReassignment event :
9428 changes.getRequestReassignments()) {
9429 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009430 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009431 } else {
James Mattisa076c532020-12-02 14:12:41 -08009432 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009433 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009434 }
9435 }
9436
junyulai0ac374f2020-12-14 18:41:52 +08009437 // Update the inactivity state before processing listen callbacks, because the background
9438 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009439 // just yet though, because they have to be sent after the listens are processed to keep
9440 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009441 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009442 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009443 // Rematching may have altered the inactivity state of some networks, so update all
9444 // inactivity timers. updateInactivityState reads the state from the network agent
9445 // and does nothing if the state has not changed : the source of truth is controlled
9446 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9447 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009448 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009449 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009450 }
9451 }
9452
Chalard Jeanb10ab412019-12-11 14:12:30 +09009453 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009454 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009455 // Process listen requests and update capabilities if the background state has
9456 // changed for this network. For consistency with previous behavior, send onLost
9457 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009458 processNewlyLostListenRequests(nai);
9459 if (oldBackground != nai.isBackgroundNetwork()) {
9460 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009461 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009462 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009463 }
9464
junyulai0ac374f2020-12-14 18:41:52 +08009465 for (final NetworkAgentInfo nai : inactiveNetworks) {
9466 // For nascent networks, if connecting with no foreground request, skip broadcasting
9467 // LOSING for backward compatibility. This is typical when mobile data connected while
9468 // wifi connected with mobile data always-on enabled.
9469 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009470 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009471 }
9472
James Mattise3ef1912020-12-20 11:09:58 -08009473 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009474
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009475 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009476 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009477 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009478 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009479 // This network has active linger timers and no requests, but is not
9480 // lingering. Linger it.
9481 //
9482 // One way (the only way?) this can happen if this network is unvalidated
9483 // and became unneeded due to another network improving its score to the
9484 // point where this network will no longer be able to satisfy any requests
9485 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009486 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009487 notifyNetworkLosing(nai, now);
9488 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009489 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009490 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009491 teardownUnneededNetwork(nai);
9492 }
9493 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009494 }
9495 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009496
Chalard Jean62edfd82019-12-02 18:39:29 +09009497 /**
9498 * Apply a change in background state resulting from rematching networks with requests.
9499 *
9500 * During rematch, a network may change background states by starting to satisfy or stopping
9501 * to satisfy a foreground request. Listens don't count for this. When a network changes
9502 * background states, its capabilities need to be updated and callbacks fired for the
9503 * capability change.
9504 *
9505 * @param nai The network that changed background states
9506 */
9507 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
9508 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
9509 if (Objects.equals(nai.networkCapabilities, newNc)) return;
9510 updateNetworkPermissions(nai, newNc);
9511 nai.getAndSetNetworkCapabilities(newNc);
9512 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
9513 }
9514
Chalard Jeanf0344532019-11-19 19:23:38 +09009515 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08009516 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009517 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09009518 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
9519 changes.getReassignment(mDefaultRequest);
9520 final NetworkAgentInfo oldDefaultNetwork =
9521 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
9522 final NetworkAgentInfo newDefaultNetwork =
9523 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08009524
Chalard Jean5b409c72021-02-04 13:12:59 +09009525 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009526 // Maintain the illusion : since the legacy API only understands one network at a time,
9527 // if the default network changed, apps should see a disconnected broadcast for the
9528 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009529 if (oldDefaultNetwork != null) {
9530 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9531 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009532 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009533 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009534 // The new default network can be newly null if and only if the old default
9535 // network doesn't satisfy the default request any more because it lost a
9536 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009537 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009538 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009539 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009540 }
9541 }
9542
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009543 // Now that all the callbacks have been sent, send the legacy network broadcasts
9544 // as needed. This is necessary so that legacy requests correctly bind dns
9545 // requests to this network. The legacy users are listening for this broadcast
9546 // and will generally do a dns request so they can ensureRouteToHost and if
9547 // they do that before the callbacks happen they'll use the default network.
9548 //
9549 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
9550 // callbacks, but if apps can receive the broadcast before the callback, they still might
9551 // have an inconsistent view of networking.
9552 //
9553 // This *does* introduce a race where if the user uses the new api
9554 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
9555 // they may get old info. Reverse this after the old startUsing api is removed.
9556 // This is on top of the multiple intent sequencing referenced in the todo above.
9557 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09009558 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009559 addNetworkToLegacyTypeTracker(nai);
9560 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08009561 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009562 }
9563
Chalard Jean0354d8c2021-01-12 10:58:56 +09009564 private void issueNetworkNeeds() {
9565 ensureRunningOnConnectivityServiceThread();
9566 for (final NetworkOfferInfo noi : mNetworkOffers) {
9567 issueNetworkNeeds(noi);
9568 }
9569 }
9570
9571 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
9572 ensureRunningOnConnectivityServiceThread();
9573 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9574 informOffer(nri, noi.offer, mNetworkRanker);
9575 }
9576 }
9577
9578 /**
9579 * Inform a NetworkOffer about any new situation of a request.
9580 *
9581 * This function handles updates to offers. A number of events may happen that require
9582 * updating the registrant for this offer about the situation :
9583 * • The offer itself was updated. This may lead the offer to no longer being able
9584 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
9585 * or conversely being strengthened enough to beat the satisfier (and therefore
9586 * start being needed)
9587 * • The network satisfying a request changed (including cases where the request
9588 * starts or stops being satisfied). The new network may be a stronger or weaker
9589 * match than the old one, possibly affecting whether the offer is needed.
9590 * • The network satisfying a request updated their score. This may lead the offer
9591 * to no longer be able to beat it if the current satisfier got better, or
9592 * conversely start being a good choice if the current satisfier got weaker.
9593 *
9594 * @param nri The request
9595 * @param offer The offer. This may be an updated offer.
9596 */
9597 private static void informOffer(@NonNull NetworkRequestInfo nri,
9598 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9599 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9600 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009601
9602 // Multi-layer requests have a currently active request, the one being satisfied.
9603 // Since the system will try to bring up a better network than is currently satisfying
9604 // the request, NetworkProviders need to be told the offers matching the requests *above*
9605 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9606 // not needed, and the offer is needed for the active request iff the offer can beat
9607 // the satisfier.
9608 // For non-multilayer requests, the logic above gracefully degenerates to only the
9609 // last case.
9610 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9611 // providers that the offer is needed for this request, until the active request is found.
9612 // In a second phase, deal with the currently active request. In a third phase, inform
9613 // the providers that offer is unneeded for the remaining requests.
9614
9615 // First phase : inform providers of all requests above the active request.
9616 int i;
9617 for (i = 0; nri.mRequests.size() > i; ++i) {
9618 final NetworkRequest request = nri.mRequests.get(i);
9619 if (activeRequest == request) break; // Found the active request : go to phase 2
9620 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9621 // Since this request is higher-priority than the one currently satisfied, if the
9622 // offer can satisfy it, the provider should try and bring up the network for sure ;
9623 // no need to even ask the ranker – an offer that can satisfy is always better than
9624 // no network. Hence tell the provider so unless it already knew.
9625 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9626 offer.onNetworkNeeded(request);
9627 }
9628 }
9629
9630 // Second phase : deal with the active request (if any)
9631 if (null != activeRequest && activeRequest.isRequest()) {
9632 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009633 // If an offer can satisfy the request, it is considered needed if it is currently
9634 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009635 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009636 && satisfier.factorySerialNumber == offer.providerId
9637 && activeRequest.canBeSatisfiedBy(offer.caps);
9638 final boolean newNeeded = currentlyServing
9639 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009640 if (newNeeded != oldNeeded) {
9641 if (newNeeded) {
9642 offer.onNetworkNeeded(activeRequest);
9643 } else {
9644 // The offer used to be able to beat the satisfier. Now it can't.
9645 offer.onNetworkUnneeded(activeRequest);
9646 }
9647 }
9648 }
9649
9650 // Third phase : inform the providers that the offer isn't needed for any request
9651 // below the active one.
9652 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
9653 final NetworkRequest request = nri.mRequests.get(i);
9654 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9655 // Since this request is lower-priority than the one currently satisfied, if the
9656 // offer can satisfy it, the provider should not try and bring up the network.
9657 // Hence tell the provider so unless it already knew.
9658 if (offer.neededFor(request)) {
9659 offer.onNetworkUnneeded(request);
9660 }
9661 }
9662 }
9663
Chalard Jean61c79252019-11-07 23:07:32 +09009664 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
9665 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9666 NetworkRequest nr = nai.requestAt(i);
9667 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
9668 // legacy type tracker filters out repeat adds
9669 mLegacyTypeTracker.add(nr.legacyType, nai);
9670 }
9671 }
9672
9673 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09009674 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09009675 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
9676 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
9677 if (nai.isVPN()) {
9678 mLegacyTypeTracker.add(TYPE_VPN, nai);
9679 }
9680 }
9681
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009682 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04009683 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +09009684 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09009685 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04009686 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09009687 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009688
Chalard Jean254bd162022-08-25 13:04:51 +09009689 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009690 // Don't repeat publish.
9691 if (newInetCondition == mDefaultInetConditionPublished) return;
9692
9693 mDefaultInetConditionPublished = newInetCondition;
9694 sendInetConditionBroadcast(nai.networkInfo);
9695 }
9696
Chalard Jeand61375d2020-01-14 22:46:36 +09009697 @NonNull
9698 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
9699 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009700 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09009701 final boolean suspended =
9702 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9703 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
9704 // Only override the state with SUSPENDED if the network is currently in CONNECTED
9705 // state. This is because the network could have been suspended before connecting,
9706 // or it could be disconnecting while being suspended, and in both these cases
9707 // the state should not be overridden. Note that the only detailed state that
9708 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
9709 // worry about multiple different substates of CONNECTED.
9710 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
9711 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009712 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
9713 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
9714 // network agent is created, then goes to suspended, then goes out of suspended without
9715 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +09009716 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009717 ? NetworkInfo.DetailedState.CONNECTED
9718 : NetworkInfo.DetailedState.CONNECTING,
9719 info.getReason(),
9720 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09009721 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009722 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09009723 return newInfo;
9724 }
9725
9726 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
9727 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
9728
Erik Kline99f301b2017-02-15 19:59:17 +09009729 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009730 NetworkInfo oldInfo = null;
9731 synchronized (networkAgent) {
9732 oldInfo = networkAgent.networkInfo;
9733 networkAgent.networkInfo = newInfo;
9734 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009735
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009736 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009737 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
9738 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009739 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009740
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09009741 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009742 // A network that has just connected has zero requests and is thus a foreground network.
9743 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
9744
Luke Huangfdd11f82019-04-09 18:41:49 +08009745 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09009746
9747 networkAgent.setCreated();
9748
9749 // If the network is created immediately on register, then apply the LinkProperties now.
9750 // Otherwise, this is done further down when the network goes into connected state.
9751 // Applying the LinkProperties means that the network is ready to carry traffic -
9752 // interfaces and routing rules have been added, DNS servers programmed, etc.
9753 // For VPNs, this must be done before the capabilities are updated, because as soon as
9754 // that happens, UIDs are routed to the network.
9755 if (shouldCreateNetworksImmediately()) {
9756 applyInitialLinkProperties(networkAgent);
9757 }
9758
9759 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
9760 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +09009761 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009762 // Initialize the network's capabilities to their starting values according to the
9763 // underlying networks. This ensures that the capabilities are correct before
9764 // anything happens to the network.
9765 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009766 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009767 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +09009768 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +08009769 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009770 }
9771
Chalard Jean254bd162022-08-25 13:04:51 +09009772 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
9773 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009774
lucaslin45e639b2019-04-03 17:09:28 +08009775 // NetworkCapabilities need to be set before sending the private DNS config to
9776 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009777 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9778
Erik Kline9a62f012018-03-21 07:18:33 -07009779 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09009780 if (!shouldCreateNetworksImmediately()) {
9781 applyInitialLinkProperties(networkAgent);
9782 } else {
9783 // The network was created when the agent registered, and the LinkProperties are
9784 // already up-to-date. However, updateLinkProperties also makes some changes only
9785 // when the network connects. Apply those changes here. On T and below these are
9786 // handled by the applyInitialLinkProperties call just above.
9787 // TODO: stop relying on updateLinkProperties(..., null) to do this.
9788 // If something depends on both LinkProperties and connected state, it should be in
9789 // this method as well.
9790 networkAgent.clatd.update();
9791 updateProxy(networkAgent.linkProperties, null);
9792 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009793
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +01009794 // If a rate limit has been configured and is applicable to this network (network
9795 // provides internet connectivity), apply it. The tc police filter cannot be attached
9796 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
9797 // updateInterfaces -> INetd#networkAddInterface.
9798 // Note: in case of a system server crash, the NetworkController constructor in netd
9799 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
9800 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9801 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9802 mIngressRateLimit);
9803 }
9804
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009805 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9806 // command must be sent after updating LinkProperties to maximize chances of
9807 // NetworkMonitor seeing the correct LinkProperties when starting.
9808 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009809 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009810 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009811 }
Chalard Jeand4900722022-02-06 12:25:38 +09009812 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9813 params.networkAgentConfig = networkAgent.networkAgentConfig;
9814 params.networkCapabilities = networkAgent.networkCapabilities;
9815 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9816 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +09009817 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
9818 // newer callback even before T. However getInterfaceVersion is a synchronized binder
9819 // call that would cause a Log.wtf to be emitted from the system_server process, and
9820 // in the absence of a satisfactory, scalable solution which follows an easy/standard
9821 // process to check the interface version, just use an SDK check. NetworkStack will
9822 // always be new enough when running on T+.
9823 if (SdkLevel.isAtLeastT()) {
9824 networkAgent.networkMonitor().notifyNetworkConnected(params);
9825 } else {
9826 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
9827 params.networkCapabilities);
9828 }
Chalard Jeane63c42f2022-09-16 19:31:45 +09009829 final long delay = activelyPreferBadWifi()
9830 ? ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS
9831 : DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
9832 scheduleEvaluationTimeout(networkAgent.network, delay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009833
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009834 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9835 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9836 // capabilities, so it only needs to be done once on initial connect, not every time the
9837 // network's capabilities change. Note that we do this before rematching the network,
9838 // so we could decide to tear it down immediately afterwards. That's fine though - on
9839 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9840 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009841 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009842
junyulai0ac374f2020-12-14 18:41:52 +08009843 // Before first rematching networks, put an inactivity timer without any request, this
9844 // allows {@code updateInactivityState} to update the state accordingly and prevent
9845 // tearing down for any {@code unneeded} evaluation in this period.
9846 // Note that the timer will not be rescheduled since the expiry time is
9847 // fixed after connection regardless of the network satisfying other requests or not.
9848 // But it will be removed as soon as the network satisfies a request for the first time.
9849 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9850 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009851 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009852
Paul Jensen05e85ee2014-09-11 11:00:39 -04009853 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009854 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009855
9856 // This has to happen after matching the requests, because callbacks are just requests.
9857 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009858 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009859 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009860 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009861 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009862 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009863 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009864 if (networkAgent.isVPN()) {
9865 // As the active or bound network changes for apps, broadcast the default proxy, as
9866 // apps may need to update their proxy data. This is called after disconnecting from
9867 // VPN to make sure we do not broadcast the old proxy data.
9868 // TODO(b/122649188): send the broadcast only to VPN users.
9869 mProxyTracker.sendProxyBroadcast();
9870 }
Chalard Jean254bd162022-08-25 13:04:51 +09009871 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
9872 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009873 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009874 }
9875 }
9876
Chalard Jean28018572020-12-21 18:36:52 +09009877 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009878 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9879 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009880 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009881 }
9882
Erik Kline99f301b2017-02-15 19:59:17 +09009883 // Notify only this one new request of the current state. Transfer all the
9884 // current state by calling NetworkCapabilities and LinkProperties callbacks
9885 // so that callers can be guaranteed to have as close to atomicity in state
9886 // transfer as can be supported by this current API.
9887 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009888 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009889 if (nri.mPendingIntent != null) {
9890 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9891 // Attempt no subsequent state pushes where intents are involved.
9892 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009893 }
Erik Kline99f301b2017-02-15 19:59:17 +09009894
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009895 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009896 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009897 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9898 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9899 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009900 }
9901
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009902 // Notify the requests on this NAI that the network is now lingered.
9903 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009904 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009905 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9906 }
9907
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009908 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9909 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9910 return vpnBlocked
9911 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9912 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9913 }
9914
9915 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9916 if (blockedReasons == BLOCKED_REASON_NONE) {
9917 mUidBlockedReasons.delete(uid);
9918 } else {
9919 mUidBlockedReasons.put(uid, blockedReasons);
9920 }
9921 }
9922
junyulaif2c67e42018-08-07 19:50:45 +08009923 /**
9924 * Notify of the blocked state apps with a registered callback matching a given NAI.
9925 *
9926 * Unlike other callbacks, blocked status is different between each individual uid. So for
9927 * any given nai, all requests need to be considered according to the uid who filed it.
9928 *
9929 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009930 * @param oldMetered True if the previous network capabilities were metered.
9931 * @param newMetered True if the current network capabilities are metered.
9932 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9933 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009934 */
9935 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009936 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9937 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009938
9939 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9940 NetworkRequest nr = nai.requestAt(i);
9941 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009942
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009943 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9944 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9945 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009946 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009947 : oldVpnBlocked;
9948
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009949 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9950 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9951 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009952 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009953 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009954 }
9955 }
9956 }
9957
9958 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009959 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009960 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009961 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009962 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009963 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009964 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009965 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009966 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009967
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009968 final int oldBlockedState = getBlockedState(
9969 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9970 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9971 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009972 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009973 }
junyulaif2c67e42018-08-07 19:50:45 +08009974 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9975 NetworkRequest nr = nai.requestAt(i);
9976 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009977 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009978 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9979 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009980 }
9981 }
9982 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009983 }
9984
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009985 @VisibleForTesting
9986 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009987 // The NetworkInfo we actually send out has no bearing on the real
9988 // state of affairs. For example, if the default connection is mobile,
9989 // and a request for HIPRI has just gone away, we need to pretend that
9990 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9991 // the state to DISCONNECTED, even though the network is of type MOBILE
9992 // and is still connected.
9993 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9994 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009995 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009996 if (state != DetailedState.DISCONNECTED) {
9997 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009998 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009999 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010000 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010001 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10002 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10003 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10004 if (info.isFailover()) {
10005 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10006 nai.networkInfo.setFailover(false);
10007 }
10008 if (info.getReason() != null) {
10009 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10010 }
10011 if (info.getExtraInfo() != null) {
10012 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10013 }
10014 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010015 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010016 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010017 if (newDefaultAgent != null) {
10018 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10019 newDefaultAgent.networkInfo);
10020 } else {
10021 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10022 }
10023 }
10024 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10025 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010026 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010027 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010028 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010029 }
10030 }
10031 }
10032
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010033 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010034 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010035 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010036 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010037 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010038 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10039 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010040 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10041 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010042 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010043 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010044 } else {
10045 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10046 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010047 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010048 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010049
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010050 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10051 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10052 }
10053
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010054 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010055 * Returns the list of all interfaces that could be used by network traffic that does not
10056 * explicitly specify a network. This includes the default network, but also all VPNs that are
10057 * currently connected.
10058 *
10059 * Must be called on the handler thread.
10060 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010061 @NonNull
10062 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010063 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010064 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010065 final Set<Integer> activeNetIds = new ArraySet<>();
10066 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10067 if (nri.isBeingSatisfied()) {
10068 activeNetIds.add(nri.getSatisfier().network().netId);
10069 }
10070 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010071 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010072 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010073 defaultNetworks.add(nai.network);
10074 }
10075 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010076 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010077 }
10078
10079 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010080 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10081 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010082 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010083 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010084 ensureRunningOnConnectivityServiceThread();
10085 String activeIface = null;
10086 LinkProperties activeLinkProperties = getActiveLinkProperties();
10087 if (activeLinkProperties != null) {
10088 activeIface = activeLinkProperties.getInterfaceName();
10089 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010090
junyulai2050bed2021-01-23 09:46:34 +080010091 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010092 try {
junyulaide41fc22021-01-22 22:46:01 +080010093 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010094 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010095 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10096 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010097 } catch (Exception ignored) {
10098 }
10099 }
10100
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010101 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010102 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010103 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010104 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010105 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010106
10107 if (!TextUtils.isEmpty(settingUrl)) {
10108 return settingUrl;
10109 }
10110
10111 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010112 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010113 if (!TextUtils.isEmpty(settingUrl)) {
10114 return settingUrl;
10115 }
10116
10117 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010118 }
10119
10120 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010121 public void startNattKeepalive(Network network, int intervalSeconds,
10122 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010123 enforceKeepalivePermission();
10124 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010125 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010126 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10127 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010128 // false and set the underpinned network to null because there is no way and no
10129 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10130 // deprecated method.
10131 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010132 }
10133
10134 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010135 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010136 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010137 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010138 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010139 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010140 mKeepaliveTracker.startNattKeepalive(
10141 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010142 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10143 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010144 } finally {
10145 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10146 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010147 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10148 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010149 }
10150 }
junyulaid05a1922019-01-15 11:32:44 +080010151 }
10152
10153 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010154 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010155 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010156 try {
10157 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010158 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010159 mKeepaliveTracker.startTcpKeepalive(
10160 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10161 } finally {
10162 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10163 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010164 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10165 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010166 }
10167 }
junyulai0835a1e2019-01-08 20:04:33 +080010168 }
10169
10170 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010171 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010172 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010173 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10174 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010175 }
10176
10177 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090010178 public int[] getSupportedKeepalives() {
10179 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10180 // Backwards compatibility with CTS 13
10181 android.Manifest.permission.QUERY_ALL_PACKAGES);
10182
10183 return BinderUtils.withCleanCallingIdentity(() ->
10184 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10185 }
10186
10187 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010188 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010189 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010190
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010191 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010192 final long token = Binder.clearCallingIdentity();
10193 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010194 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10195 UserHandle.getUserHandleForUid(uid))) {
10196 return;
10197 }
10198
Heemin Seogdb8489d2019-06-12 09:21:44 -070010199 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10200 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010201
10202 // Turn airplane mode off
10203 setAirplaneMode(false);
10204
10205 // restore private DNS settings to default mode (opportunistic)
10206 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10207 UserHandle.getUserHandleForUid(uid))) {
10208 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10209 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10210 }
10211
10212 Settings.Global.putString(mContext.getContentResolver(),
10213 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010214 } finally {
10215 Binder.restoreCallingIdentity(token);
10216 }
Stuart Scottd5463642015-04-02 18:00:02 -070010217 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010218
Ricky Wai7097cc92018-01-23 04:09:45 +000010219 @Override
10220 public byte[] getNetworkWatchlistConfigHash() {
10221 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10222 if (nwm == null) {
10223 loge("Unable to get NetworkWatchlistManager");
10224 return null;
10225 }
10226 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10227 return nwm.getWatchlistConfigHash();
10228 }
10229
Hugo Benichibe0c7652016-05-31 16:28:06 +090010230 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010231 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010232 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010233 }
Hugo Benichif4210292017-04-21 15:07:12 +090010234
10235 private static boolean toBool(int encodedBoolean) {
10236 return encodedBoolean != 0; // Only 0 means false.
10237 }
10238
10239 private static int encodeBool(boolean b) {
10240 return b ? 1 : 0;
10241 }
mswest4632928412018-03-12 10:34:34 -070010242
10243 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010244 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10245 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10246 @NonNull String[] args) {
10247 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10248 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010249 }
10250
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010251 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010252 @Override
10253 public int onCommand(String cmd) {
10254 if (cmd == null) {
10255 return handleDefaultCommands(cmd);
10256 }
10257 final PrintWriter pw = getOutPrintWriter();
10258 try {
10259 switch (cmd) {
10260 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010261 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
10262 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070010263 final String action = getNextArg();
10264 if ("enable".equals(action)) {
10265 setAirplaneMode(true);
10266 return 0;
10267 } else if ("disable".equals(action)) {
10268 setAirplaneMode(false);
10269 return 0;
10270 } else if (action == null) {
10271 final ContentResolver cr = mContext.getContentResolver();
10272 final int enabled = Settings.Global.getInt(cr,
10273 Settings.Global.AIRPLANE_MODE_ON);
10274 pw.println(enabled == 0 ? "disabled" : "enabled");
10275 return 0;
10276 } else {
10277 onHelp();
10278 return -1;
10279 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010280 case "reevaluate":
10281 // Usage : adb shell cmd connectivity reevaluate <netId>
10282 // If netId is omitted, then reevaluate the default network
10283 final String netId = getNextArg();
10284 final NetworkAgentInfo nai;
10285 if (null == netId) {
10286 // Note that the command is running on the wrong thread to call this,
10287 // so this could in principle return stale data. But it can't crash.
10288 nai = getDefaultNetwork();
10289 } else {
10290 // If netId can't be parsed, this throws NumberFormatException, which
10291 // is passed back to adb who prints it.
10292 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10293 }
10294 if (null == nai) {
10295 pw.println("Unknown network (net ID not found or no default network)");
10296 return 0;
10297 }
10298 Log.d(TAG, "Reevaluating network " + nai.network);
10299 reportNetworkConnectivity(nai.network, !nai.isValidated());
10300 return 0;
mswest4632928412018-03-12 10:34:34 -070010301 default:
10302 return handleDefaultCommands(cmd);
10303 }
10304 } catch (Exception e) {
10305 pw.println(e);
10306 }
10307 return -1;
10308 }
10309
10310 @Override
10311 public void onHelp() {
10312 PrintWriter pw = getOutPrintWriter();
10313 pw.println("Connectivity service commands:");
10314 pw.println(" help");
10315 pw.println(" Print this help text.");
10316 pw.println(" airplane-mode [enable|disable]");
10317 pw.println(" Turn airplane mode on or off.");
10318 pw.println(" airplane-mode");
10319 pw.println(" Get airplane mode.");
10320 }
10321 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010322
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010323 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010324 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10325 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10326 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010327 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010328 }
10329
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010330 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10331 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010332 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10333 final TransportInfo newInfo = nc.getTransportInfo();
10334 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10335 return;
10336 }
10337 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010338 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010339 }
10340 }
10341
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010342 /**
10343 * @param connectionInfo the connection to resolve.
10344 * @return {@code uid} if the connection is found and the app has permission to observe it
10345 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10346 * connection is not found.
10347 */
10348 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010349 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10350 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10351 }
10352
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010353 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010354 connectionInfo.local, connectionInfo.remote);
10355
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010356 if (uid == INVALID_UID) return uid; // Not found.
10357
10358 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10359 // VPN, if any, that applies to the UID that owns the connection.
10360 if (checkNetworkStackPermission()) return uid;
10361
10362 final NetworkAgentInfo vpn = getVpnForUid(uid);
10363 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010364 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010365 return INVALID_UID;
10366 }
10367
10368 return uid;
10369 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010370
Benedict Wong493e04b2018-11-09 14:45:34 -080010371 /**
10372 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10373 *
10374 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10375 */
10376 @Override
10377 public IBinder startOrGetTestNetworkService() {
10378 synchronized (mTNSLock) {
10379 TestNetworkService.enforceTestNetworkPermissions(mContext);
10380
10381 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010382 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010383 }
10384
10385 return mTNS;
10386 }
10387 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010388
Cody Kesting73708bf2019-12-18 10:57:50 -080010389 /**
10390 * Handler used for managing all Connectivity Diagnostics related functions.
10391 *
10392 * @see android.net.ConnectivityDiagnosticsManager
10393 *
10394 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10395 */
10396 @VisibleForTesting
10397 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010398 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10399
Cody Kesting73708bf2019-12-18 10:57:50 -080010400 /**
10401 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10402 * android.net.ConnectivityDiagnosticsManager}.
10403 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10404 * NetworkRequestInfo to be registered
10405 */
10406 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10407
10408 /**
10409 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10410 * android.net.ConnectivityDiagnosticsManager}.
10411 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10412 * arg1 = the uid of the caller
10413 */
10414 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10415
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010416 /**
10417 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010418 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010419 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10420 * NetworkMonitor.
10421 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010422 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010423 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010424
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010425 /**
10426 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10427 * been detected on the network.
10428 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10429 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10430 * arg2 = NetID.
10431 * data = PersistableBundle of extras passed from NetworkMonitor.
10432 */
10433 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10434
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010435 /**
10436 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10437 * the platform. This event will invoke {@link
10438 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10439 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070010440 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010441 */
10442 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
10443
Cody Kesting73708bf2019-12-18 10:57:50 -080010444 private ConnectivityDiagnosticsHandler(Looper looper) {
10445 super(looper);
10446 }
10447
10448 @Override
10449 public void handleMessage(Message msg) {
10450 switch (msg.what) {
10451 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10452 handleRegisterConnectivityDiagnosticsCallback(
10453 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
10454 break;
10455 }
10456 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10457 handleUnregisterConnectivityDiagnosticsCallback(
10458 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
10459 break;
10460 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010461 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010462 final ConnectivityReportEvent reportEvent =
10463 (ConnectivityReportEvent) msg.obj;
10464
Aaron Huang959d3642021-01-21 15:47:41 +080010465 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010466 break;
10467 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010468 case EVENT_DATA_STALL_SUSPECTED: {
10469 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080010470 final Pair<Long, PersistableBundle> arg =
10471 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010472 if (nai == null) break;
10473
Aaron Huang959d3642021-01-21 15:47:41 +080010474 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010475 break;
10476 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010477 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070010478 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010479 break;
10480 }
10481 default: {
10482 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
10483 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010484 }
10485 }
10486 }
10487
10488 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
10489 @VisibleForTesting
10490 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
10491 @NonNull private final IConnectivityDiagnosticsCallback mCb;
10492 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010493 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010494
10495 @VisibleForTesting
10496 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010497 @NonNull IConnectivityDiagnosticsCallback cb,
10498 @NonNull NetworkRequestInfo nri,
10499 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010500 mCb = cb;
10501 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010502 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010503 }
10504
10505 @Override
10506 public void binderDied() {
10507 log("ConnectivityDiagnosticsCallback IBinder died.");
10508 unregisterConnectivityDiagnosticsCallback(mCb);
10509 }
10510 }
10511
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010512 /**
10513 * Class used for sending information from {@link
10514 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
10515 */
10516 private static class NetworkTestedResults {
10517 private final int mNetId;
10518 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010519 @Nullable private final String mRedirectUrl;
10520
10521 private NetworkTestedResults(
10522 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
10523 mNetId = netId;
10524 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010525 mRedirectUrl = redirectUrl;
10526 }
10527 }
10528
10529 /**
10530 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
10531 * ConnectivityDiagnosticsHandler}.
10532 */
10533 private static class ConnectivityReportEvent {
10534 private final long mTimestampMillis;
10535 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080010536 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010537
Aaron Huang959d3642021-01-21 15:47:41 +080010538 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
10539 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010540 mTimestampMillis = timestampMillis;
10541 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080010542 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010543 }
10544 }
10545
Cody Kestingf1120be2020-08-03 18:01:40 -070010546 /**
10547 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
10548 * ConnectivityDiagnosticsHandler}.
10549 */
10550 private static class ReportedNetworkConnectivityInfo {
10551 public final boolean hasConnectivity;
10552 public final boolean isNetworkRevalidating;
10553 public final int reporterUid;
10554 @NonNull public final NetworkAgentInfo nai;
10555
10556 private ReportedNetworkConnectivityInfo(
10557 boolean hasConnectivity,
10558 boolean isNetworkRevalidating,
10559 int reporterUid,
10560 @NonNull NetworkAgentInfo nai) {
10561 this.hasConnectivity = hasConnectivity;
10562 this.isNetworkRevalidating = isNetworkRevalidating;
10563 this.reporterUid = reporterUid;
10564 this.nai = nai;
10565 }
10566 }
10567
Cody Kesting73708bf2019-12-18 10:57:50 -080010568 private void handleRegisterConnectivityDiagnosticsCallback(
10569 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
10570 ensureRunningOnConnectivityServiceThread();
10571
10572 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080010573 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010574 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
10575
James Mattis64b8b0f2020-11-24 17:40:49 -080010576 // Connectivity Diagnostics are meant to be used with a single network request. It would be
10577 // confusing for these networks to change when an NRI is satisfied in another layer.
10578 if (nri.isMultilayerRequest()) {
10579 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
10580 + "network requests.");
10581 }
10582
Cody Kesting73708bf2019-12-18 10:57:50 -080010583 // This means that the client registered the same callback multiple times. Do
10584 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080010585 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010586 if (VDBG) log("Diagnostics callback is already registered");
10587
10588 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10589 // incremented when the NetworkRequestInfo is created as part of
10590 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010591 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080010592 return;
10593 }
10594
Cody Kesting31f1ff62020-03-05 10:46:02 -080010595 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080010596
10597 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080010598 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010599 } catch (RemoteException e) {
10600 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080010601 return;
10602 }
10603
10604 // Once registered, provide ConnectivityReports for matching Networks
10605 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
10606 synchronized (mNetworkForNetId) {
10607 for (int i = 0; i < mNetworkForNetId.size(); i++) {
10608 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080010609 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
10610 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080010611 matchingNetworks.add(nai);
10612 }
10613 }
10614 }
10615 for (final NetworkAgentInfo nai : matchingNetworks) {
10616 final ConnectivityReport report = nai.getConnectivityReport();
10617 if (report == null) {
10618 continue;
10619 }
10620 if (!checkConnectivityDiagnosticsPermissions(
10621 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10622 continue;
10623 }
10624
10625 try {
10626 cb.onConnectivityReportAvailable(report);
10627 } catch (RemoteException e) {
10628 // Exception while sending the ConnectivityReport. Move on to the next network.
10629 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010630 }
10631 }
10632
10633 private void handleUnregisterConnectivityDiagnosticsCallback(
10634 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
10635 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010636 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010637
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010638 final ConnectivityDiagnosticsCallbackInfo cbInfo =
10639 mConnectivityDiagnosticsCallbacks.remove(iCb);
10640 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010641 if (VDBG) log("Removing diagnostics callback that is not currently registered");
10642 return;
10643 }
10644
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010645 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080010646
Cody Kesting70fa2b22020-12-02 12:16:56 -080010647 // Caller's UID must either be the registrants (if they are unregistering) or the System's
10648 // (if the Binder died)
10649 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
10650 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080010651 return;
10652 }
10653
Cody Kesting46cb1672020-03-04 13:35:20 -080010654 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10655 // incremented when the NetworkRequestInfo is created as part of
10656 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010657 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080010658
Cody Kesting31f1ff62020-03-05 10:46:02 -080010659 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010660 }
10661
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010662 private void handleNetworkTestedWithExtras(
10663 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
10664 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080010665 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010666 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010667 final ConnectivityReport report =
10668 new ConnectivityReport(
10669 reportEvent.mNai.network,
10670 reportEvent.mTimestampMillis,
10671 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010672 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010673 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080010674 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070010675
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010676 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010677 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010678 for (final IConnectivityDiagnosticsCallback cb : results) {
10679 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080010680 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010681 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070010682 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010683 }
10684 }
10685 }
10686
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010687 private void handleDataStallSuspected(
10688 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
10689 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080010690 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010691 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010692 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080010693 new DataStallReport(
10694 nai.network,
10695 timestampMillis,
10696 detectionMethod,
10697 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010698 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080010699 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010700 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010701 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010702 for (final IConnectivityDiagnosticsCallback cb : results) {
10703 try {
10704 cb.onDataStallSuspected(report);
10705 } catch (RemoteException ex) {
10706 loge("Error invoking onDataStallSuspected", ex);
10707 }
10708 }
10709 }
10710
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010711 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070010712 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
10713 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
10714 final ConnectivityReport cachedReport = nai.getConnectivityReport();
10715
10716 // If the Network is being re-validated as a result of this call to
10717 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
10718 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010719 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010720 getMatchingPermissionedCallbacks(
10721 nai,
10722 reportedNetworkConnectivityInfo.isNetworkRevalidating
10723 ? Process.INVALID_UID
10724 : reportedNetworkConnectivityInfo.reporterUid);
10725
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010726 for (final IConnectivityDiagnosticsCallback cb : results) {
10727 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070010728 cb.onNetworkConnectivityReported(
10729 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010730 } catch (RemoteException ex) {
10731 loge("Error invoking onNetworkConnectivityReported", ex);
10732 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010733
10734 // If the Network isn't re-validating, also provide the cached report. If there is no
10735 // cached report, the Network is still being validated and a report will be sent once
10736 // validation is complete. Note that networks which never undergo validation will still
10737 // have a cached ConnectivityReport with RESULT_SKIPPED.
10738 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
10739 try {
10740 cb.onConnectivityReportAvailable(cachedReport);
10741 } catch (RemoteException ex) {
10742 loge("Error invoking onConnectivityReportAvailable", ex);
10743 }
10744 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010745 }
10746 }
10747
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010748 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090010749 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
10750 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010751 sanitized.setUids(null);
10752 sanitized.setAdministratorUids(new int[0]);
10753 sanitized.setOwnerUid(Process.INVALID_UID);
10754 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080010755 }
10756
Cody Kestingf1120be2020-08-03 18:01:40 -070010757 /**
10758 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
10759 *
10760 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
10761 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010762 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070010763 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010764 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010765 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010766 mConnectivityDiagnosticsCallbacks.entrySet()) {
10767 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
10768 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070010769
James Mattis64b8b0f2020-11-24 17:40:49 -080010770 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070010771 if (!nai.satisfies(nri.mRequests.get(0))) {
10772 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010773 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010774
10775 // UID for this callback must either be:
10776 // - INVALID_UID (which sends callbacks to all UIDs), or
10777 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
10778 // notified as a result)
10779 if (uid != Process.INVALID_UID && uid != nri.mUid) {
10780 continue;
10781 }
10782
10783 if (!checkConnectivityDiagnosticsPermissions(
10784 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10785 continue;
10786 }
10787
10788 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010789 }
10790 return results;
10791 }
10792
Cody Kesting7474f672021-05-11 14:22:40 -070010793 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
10794 @NonNull NetworkAgentInfo nai) {
10795 // TODO(b/188483916): replace with a transport-agnostic location-aware check
10796 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
10797 }
10798
Cody Kesting160ef392021-05-05 13:17:22 -070010799 private boolean hasLocationPermission(String packageName, int uid) {
10800 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
10801 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
10802 // call in a try-catch.
10803 try {
10804 if (!mLocationPermissionChecker.checkLocationPermission(
10805 packageName, null /* featureId */, uid, null /* message */)) {
10806 return false;
10807 }
10808 } catch (SecurityException e) {
10809 return false;
10810 }
10811
10812 return true;
10813 }
10814
10815 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
10816 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090010817 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070010818 && virtual.networkCapabilities.getOwnerUid() == uid
10819 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
10820 return true;
10821 }
10822 }
10823
10824 return false;
10825 }
10826
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010827 @VisibleForTesting
10828 boolean checkConnectivityDiagnosticsPermissions(
10829 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
10830 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
10831 return true;
10832 }
10833
Cody Kesting160ef392021-05-05 13:17:22 -070010834 // Administrator UIDs also contains the Owner UID
10835 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10836 if (!CollectionUtils.contains(administratorUids, callbackUid)
10837 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010838 return false;
10839 }
10840
Cody Kesting7474f672021-05-11 14:22:40 -070010841 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10842 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010843 }
10844
Cody Kestingd199a9d2019-12-17 12:55:28 -080010845 @Override
10846 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010847 @NonNull IConnectivityDiagnosticsCallback callback,
10848 @NonNull NetworkRequest request,
10849 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010850 Objects.requireNonNull(callback, "callback must not be null");
10851 Objects.requireNonNull(request, "request must not be null");
10852 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10853
Cody Kesting73708bf2019-12-18 10:57:50 -080010854 if (request.legacyType != TYPE_NONE) {
10855 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10856 + " Please use NetworkCapabilities instead.");
10857 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010858 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010859 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010860
10861 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10862 // and administrator uids to be safe.
10863 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010864 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010865
10866 final NetworkRequest requestWithId =
10867 new NetworkRequest(
10868 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10869
10870 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10871 //
10872 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10873 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10874 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010875 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010876 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010877 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010878
10879 mConnectivityDiagnosticsHandler.sendMessage(
10880 mConnectivityDiagnosticsHandler.obtainMessage(
10881 ConnectivityDiagnosticsHandler
10882 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10883 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010884 }
10885
10886 @Override
10887 public void unregisterConnectivityDiagnosticsCallback(
10888 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010889 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010890 mConnectivityDiagnosticsHandler.sendMessage(
10891 mConnectivityDiagnosticsHandler.obtainMessage(
10892 ConnectivityDiagnosticsHandler
10893 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010894 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010895 0,
10896 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010897 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010898
Yan Yanfe96dde2022-12-05 23:00:01 +000010899 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
10900 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
10901 if (underlyingNetworks == null) return false;
10902
10903 for (Network network : underlyingNetworks) {
10904 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
10905 return true;
10906 }
10907 }
10908 return false;
10909 }
10910
Cody Kestingf53a0752020-04-15 12:33:28 -070010911 @Override
10912 public void simulateDataStall(int detectionMethod, long timestampMillis,
10913 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010914 Objects.requireNonNull(network, "network must not be null");
10915 Objects.requireNonNull(extras, "extras must not be null");
10916
paulhu3ffffe72021-09-16 10:15:22 +080010917 enforceAnyPermissionOf(mContext,
10918 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070010919 android.Manifest.permission.NETWORK_STACK);
10920 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000010921 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
10922 throw new SecurityException(
10923 "Data Stall simulation is only possible for test networks or networks built on"
10924 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010925 }
10926
10927 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000010928 if (nai == null
10929 || (nai.creatorUid != mDeps.getCallingUid()
10930 && nai.creatorUid != Process.SYSTEM_UID)) {
10931 throw new SecurityException(
10932 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070010933 }
10934
Cody Kesting652e3ec2020-05-21 12:08:21 -070010935 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10936 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10937 // Data Stall information as a DataStallReportParcelable and passing to
10938 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10939 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010940 final DataStallReportParcelable p = new DataStallReportParcelable();
10941 p.timestampMillis = timestampMillis;
10942 p.detectionMethod = detectionMethod;
10943
10944 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10945 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10946 }
10947 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10948 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10949 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10950 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10951 }
10952
Serik Beketayevec8ad212020-12-07 22:43:07 -080010953 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010954 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010955
lucaslin66f44212021-02-23 01:12:55 +080010956 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10957 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010958 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010959 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010960 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010961 }
lucaslin37a16d92021-01-21 19:48:09 +080010962
10963 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010964 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010965 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010966 nai.clatd.interfaceLinkStateChanged(iface, up);
10967 }
10968 }
10969
10970 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010971 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010972 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010973 nai.clatd.interfaceRemoved(iface);
10974 }
lucaslin66f44212021-02-23 01:12:55 +080010975 }
10976 }
10977
lucaslin1a8b4c62021-01-21 02:02:55 +080010978 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
10979
10980 /**
10981 * Class used for updating network activity tracking with netd and notify network activity
10982 * changes.
10983 */
10984 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080010985 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080010986 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080010987 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080010988 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
10989 new RemoteCallbackList<>();
10990 // Indicate the current system default network activity is active or not.
10991 @GuardedBy("mActiveIdleTimers")
10992 private boolean mNetworkActive;
10993 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090010994 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080010995 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010996
Chalard Jean46bfbf02022-02-02 00:56:25 +090010997 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080010998 public final int timeout;
10999 public final int transportType;
11000
11001 IdleTimerParams(int timeout, int transport) {
11002 this.timeout = timeout;
11003 this.transportType = transport;
11004 }
11005 }
11006
11007 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080011008 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011009 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011010 mNetd = netd;
11011 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080011012 }
11013
lucaslin66f44212021-02-23 01:12:55 +080011014 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
11015 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
11016 synchronized (mActiveIdleTimers) {
11017 mNetworkActive = active;
11018 // If there are no idle timers, it means that system is not monitoring
11019 // activity, so the system default network for those default network
11020 // unspecified apps is always considered active.
11021 //
11022 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
11023 // any network activity change event. Whenever this event is received,
11024 // the mActiveIdleTimers should be always not empty. The legacy behavior
11025 // is no-op. Remove to refer to mNetworkActive only.
11026 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
11027 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
11028 }
11029 }
11030 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011031
lucaslin1193a5d2021-01-21 02:04:15 +080011032 // The network activity should only be updated from ConnectivityService handler thread
11033 // when mActiveIdleTimers lock is held.
11034 @GuardedBy("mActiveIdleTimers")
11035 private void reportNetworkActive() {
11036 final int length = mNetworkActivityListeners.beginBroadcast();
11037 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
11038 try {
11039 for (int i = 0; i < length; i++) {
11040 try {
11041 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
11042 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011043 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080011044 }
11045 }
11046 } finally {
11047 mNetworkActivityListeners.finishBroadcast();
11048 }
11049 }
11050
11051 @GuardedBy("mActiveIdleTimers")
11052 public void handleReportNetworkActivity() {
11053 synchronized (mActiveIdleTimers) {
11054 reportNetworkActive();
11055 }
11056 }
11057
lucaslin1a8b4c62021-01-21 02:02:55 +080011058 // This is deprecated and only to support legacy use cases.
11059 private int transportTypeToLegacyType(int type) {
11060 switch (type) {
11061 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011062 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080011063 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011064 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080011065 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011066 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080011067 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011068 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080011069 default:
11070 loge("Unexpected transport in transportTypeToLegacyType: " + type);
11071 }
11072 return ConnectivityManager.TYPE_NONE;
11073 }
11074
11075 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
11076 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
11077 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
11078 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
11079 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
11080 final long ident = Binder.clearCallingIdentity();
11081 try {
11082 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
11083 RECEIVE_DATA_ACTIVITY_CHANGE,
11084 null /* resultReceiver */,
11085 null /* scheduler */,
11086 0 /* initialCode */,
11087 null /* initialData */,
11088 null /* initialExtra */);
11089 } finally {
11090 Binder.restoreCallingIdentity(ident);
11091 }
11092 }
11093
11094 /**
11095 * Setup data activity tracking for the given network.
11096 *
11097 * Every {@code setupDataActivityTracking} should be paired with a
11098 * {@link #removeDataActivityTracking} for cleanup.
11099 */
11100 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
11101 final String iface = networkAgent.linkProperties.getInterfaceName();
11102
11103 final int timeout;
11104 final int type;
11105
11106 if (networkAgent.networkCapabilities.hasTransport(
11107 NetworkCapabilities.TRANSPORT_CELLULAR)) {
11108 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011109 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080011110 10);
11111 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11112 } else if (networkAgent.networkCapabilities.hasTransport(
11113 NetworkCapabilities.TRANSPORT_WIFI)) {
11114 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011115 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080011116 15);
11117 type = NetworkCapabilities.TRANSPORT_WIFI;
11118 } else {
11119 return; // do not track any other networks
11120 }
11121
lucaslinb961efc2021-01-21 02:03:17 +080011122 updateRadioPowerState(true /* isActive */, type);
11123
lucaslin1a8b4c62021-01-21 02:02:55 +080011124 if (timeout > 0 && iface != null) {
11125 try {
lucaslin1193a5d2021-01-21 02:04:15 +080011126 synchronized (mActiveIdleTimers) {
11127 // Networks start up.
11128 mNetworkActive = true;
11129 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
11130 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
11131 reportNetworkActive();
11132 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011133 } catch (Exception e) {
11134 // You shall not crash!
11135 loge("Exception in setupDataActivityTracking " + e);
11136 }
11137 }
11138 }
11139
11140 /**
11141 * Remove data activity tracking when network disconnects.
11142 */
11143 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
11144 final String iface = networkAgent.linkProperties.getInterfaceName();
11145 final NetworkCapabilities caps = networkAgent.networkCapabilities;
11146
lucaslinb961efc2021-01-21 02:03:17 +080011147 if (iface == null) return;
11148
11149 final int type;
11150 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
11151 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11152 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
11153 type = NetworkCapabilities.TRANSPORT_WIFI;
11154 } else {
11155 return; // do not track any other networks
11156 }
11157
11158 try {
11159 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080011160 synchronized (mActiveIdleTimers) {
11161 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
11162 // The call fails silently if no idle timer setup for this interface
11163 mNetd.idletimerRemoveInterface(iface, params.timeout,
11164 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080011165 }
lucaslinb961efc2021-01-21 02:03:17 +080011166 } catch (Exception e) {
11167 // You shall not crash!
11168 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080011169 }
11170 }
11171
11172 /**
11173 * Update data activity tracking when network state is updated.
11174 */
11175 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
11176 NetworkAgentInfo oldNetwork) {
11177 if (newNetwork != null) {
11178 setupDataActivityTracking(newNetwork);
11179 }
11180 if (oldNetwork != null) {
11181 removeDataActivityTracking(oldNetwork);
11182 }
11183 }
lucaslinb961efc2021-01-21 02:03:17 +080011184
11185 private void updateRadioPowerState(boolean isActive, int transportType) {
11186 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
11187 switch (transportType) {
11188 case NetworkCapabilities.TRANSPORT_CELLULAR:
11189 bs.reportMobileRadioPowerState(isActive, NO_UID);
11190 break;
11191 case NetworkCapabilities.TRANSPORT_WIFI:
11192 bs.reportWifiRadioPowerState(isActive, NO_UID);
11193 break;
11194 default:
11195 logw("Untracked transport type:" + transportType);
11196 }
11197 }
lucaslin1193a5d2021-01-21 02:04:15 +080011198
11199 public boolean isDefaultNetworkActive() {
11200 synchronized (mActiveIdleTimers) {
11201 // If there are no idle timers, it means that system is not monitoring activity,
11202 // so the default network is always considered active.
11203 //
11204 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
11205 // tracking is disabled (negative idle timer value configured), or no active default
11206 // network. In the latter case, this reports active but it should report inactive.
11207 return mNetworkActive || mActiveIdleTimers.isEmpty();
11208 }
11209 }
11210
11211 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
11212 mNetworkActivityListeners.register(l);
11213 }
11214
11215 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
11216 mNetworkActivityListeners.unregister(l);
11217 }
lucaslin012f7a12021-01-21 02:04:35 +080011218
11219 public void dump(IndentingPrintWriter pw) {
11220 synchronized (mActiveIdleTimers) {
11221 pw.print("mNetworkActive="); pw.println(mNetworkActive);
11222 pw.println("Idle timers:");
11223 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
11224 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
11225 final IdleTimerParams params = ent.getValue();
11226 pw.print(" timeout="); pw.print(params.timeout);
11227 pw.print(" type="); pw.println(params.transportType);
11228 }
11229 }
11230 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011231 }
James Mattis47db0582021-01-01 14:13:35 -080011232
Daniel Brightf9e945b2020-06-15 16:10:01 -070011233 /**
11234 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
11235 *
11236 * @param socketInfo the socket information
11237 * @param callback the callback to register
11238 */
11239 @Override
11240 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
11241 @NonNull final IQosCallback callback) {
11242 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
11243 if (nai == null || nai.networkCapabilities == null) {
11244 try {
11245 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
11246 } catch (final RemoteException ex) {
11247 loge("registerQosCallbackInternal: RemoteException", ex);
11248 }
11249 return;
11250 }
11251 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
11252 }
11253
11254 /**
11255 * Register a {@link IQosCallback} with base {@link QosFilter}.
11256 *
11257 * @param filter the filter to register
11258 * @param callback the callback to register
11259 * @param nai the agent information related to the filter's network
11260 */
11261 @VisibleForTesting
11262 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
11263 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011264 Objects.requireNonNull(filter, "filter must be non-null");
11265 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011266
11267 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080011268 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
11269 // on this network is unregistered when the app loses permission or b) no QoS
11270 // callbacks are sent for restricted networks unless the app currently has permission
11271 // to access restricted networks.
11272 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070011273 }
11274 mQosCallbackTracker.registerCallback(callback, filter, nai);
11275 }
11276
11277 /**
11278 * Unregisters the given callback.
11279 *
11280 * @param callback the callback to unregister
11281 */
11282 @Override
11283 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011284 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011285 mQosCallbackTracker.unregisterCallback(callback);
11286 }
James Mattis47db0582021-01-01 14:13:35 -080011287
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011288 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
11289 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
11290 // Enterprise device can be fully managed like device owner and such use case
11291 // also should be supported. Calling app check for work profile and fully managed device
11292 // is already done in DevicePolicyManager.
11293 // This check is an extra caution to be sure device is fully managed or not.
11294 final UserManager um = mContext.getSystemService(UserManager.class);
11295 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
11296 if (um.isManagedProfile(profile.getIdentifier())) {
11297 return true;
11298 }
11299 if (SdkLevel.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
11300 return false;
11301 }
11302
James Mattis45d81842021-01-10 14:24:24 -080011303 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011304 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011305 *
11306 * See the documentation for the individual preferences for a description of the supported
11307 * behaviors.
11308 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011309 * @param profile If the device owner is set, any profile is allowed.
11310 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011311 * @param preferences the list of profile network preferences for the
11312 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011313 * @param listener an optional listener to listen for completion of the operation.
11314 */
11315 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011316 public void setProfileNetworkPreferences(
11317 @NonNull final UserHandle profile,
11318 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090011319 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011320 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011321 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011322
11323 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011324 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11325 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11326 .build();
11327 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011328 }
11329
paulhu3ffffe72021-09-16 10:15:22 +080011330 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011331 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011332 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011333 }
11334 if (profile.getIdentifier() < 0) {
11335 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11336 + "UserHandle.CURRENT not supported)");
11337 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011338 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11339 throw new IllegalArgumentException("Profile must be a managed profile "
11340 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011341 }
paulhuaa0743d2021-05-26 21:56:03 +080011342
Chalard Jean0606fc82022-12-14 20:34:43 +090011343 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011344 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011345 for (final ProfileNetworkPreference preference : preferences) {
11346 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011347 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011348 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011349 switch (preference.getPreference()) {
11350 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11351 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011352 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011353 if (preference.getPreferenceEnterpriseId() != 0) {
11354 throw new IllegalArgumentException(
11355 "Invalid enterprise identifier in setProfileNetworkPreferences");
11356 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011357 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011358 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11359 blockingNonEnterprise = true;
11360 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011361 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11362 allowFallback = false;
11363 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011364 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011365 // This code is needed even though there is a check later on,
11366 // because isRangeAlreadyInPreferenceList assumes that every preference
11367 // has a UID list.
11368 if (hasDefaultPreference) {
11369 throw new IllegalArgumentException(
11370 "Default profile preference should not be set along with other "
11371 + "preference");
11372 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011373 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11374 throw new IllegalArgumentException(
11375 "Invalid enterprise identifier in setProfileNetworkPreferences");
11376 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011377 final Set<UidRange> uidRangeSet =
11378 getUidListToBeAppliedForNetworkPreference(profile, preference);
11379 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11380 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11381 } else {
11382 throw new IllegalArgumentException(
11383 "Overlapping uid range in setProfileNetworkPreferences");
11384 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011385 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011386 nc.addEnterpriseId(
11387 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011388 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11389 break;
11390 default:
11391 throw new IllegalArgumentException(
11392 "Invalid preference in setProfileNetworkPreferences");
11393 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011394 preferenceList.add(new ProfileNetworkPreferenceInfo(
11395 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011396 if (hasDefaultPreference && preferenceList.size() > 1) {
11397 throw new IllegalArgumentException(
11398 "Default profile preference should not be set along with other preference");
11399 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011400 }
11401 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011402 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011403 }
11404
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011405 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
11406 @NonNull final UserHandle profile,
11407 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
11408 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080011409 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
11410 profileNetworkPreference.getIncludedUids());
11411
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011412 if (uidRangeSet.size() > 0) {
11413 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
11414 throw new IllegalArgumentException(
11415 "Allow uid range is outside the uid range of profile.");
11416 }
11417 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080011418 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011419 profileNetworkPreference.getExcludedUids());
11420 if (disallowUidRangeSet.size() > 0) {
11421 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
11422 throw new IllegalArgumentException(
11423 "disallow uid range is outside the uid range of profile.");
11424 }
11425 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
11426 disallowUidRangeSet);
11427 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011428 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011429 uidRangeSet.add(profileUids);
11430 }
11431 }
11432 return uidRangeSet;
11433 }
11434
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011435 private boolean isEnterpriseIdentifierValid(
11436 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011437 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011438 return true;
11439 }
11440 return false;
11441 }
11442
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011443 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090011444 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011445 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090011446 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011447 // The NRI for a user should contain the request for capabilities.
11448 // If fallback to default network is needed then NRI should include
11449 // the request for the default network. Create an image of it to
11450 // have the correct UIDs in it (also a request can only be part of one NRI, because
11451 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011452 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
11453 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011454 if (pref.allowFallback) {
11455 nrs.add(createDefaultInternetRequestForTransport(
11456 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11457 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011458 if (VDBG) {
11459 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
11460 pref.capabilities.getUids()));
11461 }
11462
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011463 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080011464 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080011465 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011466 result.add(nri);
11467 }
11468 return result;
11469 }
11470
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011471 /**
11472 * Compare if the given UID range sets have the same UIDs.
11473 *
11474 */
11475 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090011476 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011477 @NonNull Set<UidRange> uidRangeSet) {
11478 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
11479 return false;
11480 }
Chalard Jean0606fc82022-12-14 20:34:43 +090011481 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011482 if (UidRangeUtils.doesRangeSetOverlap(
11483 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
11484 return true;
11485 }
11486 }
11487 return false;
11488 }
11489
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011490 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090011491 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011492 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011493 /*
11494 * handleSetProfileNetworkPreference is always called for single user.
11495 * preferenceList only contains preferences for different uids within the same user
11496 * (enforced by getUidListToBeAppliedForNetworkPreference).
11497 * Clear all the existing preferences for the user before applying new preferences.
11498 *
11499 */
Chalard Jean0606fc82022-12-14 20:34:43 +090011500 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
11501 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011502 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
11503 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011504
paulhu74128522021-09-28 02:29:03 +000011505 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
11506 addPerAppDefaultNetworkRequests(
11507 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080011508 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080011509
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011510 // Finally, rematch.
11511 rematchAllNetworksAndRequests();
11512
11513 if (null != listener) {
11514 try {
11515 listener.onComplete();
11516 } catch (RemoteException e) {
11517 loge("Listener for setProfileNetworkPreference has died");
11518 }
11519 }
11520 }
11521
paulhu51f77dc2021-06-07 02:34:20 +000011522 @VisibleForTesting
11523 @NonNull
11524 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
11525 @NonNull final Set<Integer> uids) {
11526 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11527 if (uids.size() == 0) {
11528 // Should not create NetworkRequestInfo if no preferences. Without uid range in
11529 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
11530 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
11531 return nris;
11532 }
11533
11534 final List<NetworkRequest> requests = new ArrayList<>();
11535 // The NRI should be comprised of two layers:
11536 // - The request for the mobile network preferred.
11537 // - The request for the default network, for fallback.
11538 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090011539 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000011540 requests.add(createDefaultInternetRequestForTransport(
11541 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11542 final Set<UidRange> ranges = new ArraySet<>();
11543 for (final int uid : uids) {
11544 ranges.add(new UidRange(uid, uid));
11545 }
11546 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080011547 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080011548 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000011549 return nris;
11550 }
11551
11552 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000011553 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000011554 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
11555 addPerAppDefaultNetworkRequests(
11556 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000011557 // Finally, rematch.
11558 rematchAllNetworksAndRequests();
11559 }
11560
Patrick Rohr2857ac42022-01-21 14:58:16 +010011561 private void handleIngressRateLimitChanged() {
11562 final long oldIngressRateLimit = mIngressRateLimit;
11563 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
11564 mContext);
11565 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
11566 if (canNetworkBeRateLimited(networkAgent)) {
11567 // If rate limit has previously been enabled, remove the old limit first.
11568 if (oldIngressRateLimit >= 0) {
11569 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
11570 }
11571 if (mIngressRateLimit >= 0) {
11572 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
11573 mIngressRateLimit);
11574 }
11575 }
11576 }
11577 }
11578
11579 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090011580 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
11581 if (!SdkLevel.isAtLeastT()) return false;
11582
Patrick Rohrff3b3f82022-02-09 15:15:52 +010011583 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
11584 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
11585 // internet connectivity can be rate limited.
11586 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
11587 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010011588 return false;
11589 }
11590
11591 final String iface = networkAgent.linkProperties.getInterfaceName();
11592 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010011593 // This may happen in tests, but if there is no interface then there is nothing that
11594 // can be rate limited.
11595 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010011596 return false;
11597 }
11598 return true;
11599 }
11600
James Mattis45d81842021-01-10 14:24:24 -080011601 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080011602 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
11603 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080011604 }
11605
11606 /**
11607 * Used by automotive devices to set the network preferences used to direct traffic at an
11608 * application level as per the given OemNetworkPreferences. An example use-case would be an
11609 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
11610 * vehicle via a particular network.
11611 *
11612 * Calling this will overwrite the existing preference.
11613 *
James Mattisda32cfe2021-01-26 16:23:52 -080011614 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090011615 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080011616 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080011617 */
James Mattis47db0582021-01-01 14:13:35 -080011618 @Override
James Mattis45d81842021-01-10 14:24:24 -080011619 public void setOemNetworkPreference(
11620 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011621 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080011622
James Mattisfa270db2021-05-31 17:11:10 -070011623 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11624 // Only bypass the permission/device checks if this is a valid test request.
11625 if (isValidTestOemNetworkPreference(preference)) {
11626 enforceManageTestNetworksPermission();
11627 } else {
11628 enforceAutomotiveDevice();
11629 enforceOemNetworkPreferencesPermission();
11630 validateOemNetworkPreferences(preference);
11631 }
James Mattis45d81842021-01-10 14:24:24 -080011632
James Mattis45d81842021-01-10 14:24:24 -080011633 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
11634 new Pair<>(preference, listener)));
11635 }
11636
James Mattisfa270db2021-05-31 17:11:10 -070011637 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000011638 * Sets the specified UIDs to get/receive the VPN as the only default network.
11639 *
11640 * Calling this will overwrite the existing network preference for this session, and the
11641 * specified UIDs won't get any default network when no VPN is connected.
11642 *
11643 * @param session The VPN session which manages the passed UIDs.
11644 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
11645 * setting for this session if the array is empty. Null is not allowed, the
11646 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
11647 * @hide
11648 */
11649 @Override
11650 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
11651 Objects.requireNonNull(ranges);
11652 enforceNetworkStackOrSettingsPermission();
11653 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
11654 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
11655 throw new IllegalArgumentException(
11656 "setVpnNetworkPreference: Passed UID ranges overlap");
11657 }
11658
11659 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
11660 new VpnNetworkPreferenceInfo(session,
11661 new ArraySet<UidRange>(Arrays.asList(ranges)))));
11662 }
11663
11664 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
11665 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
11666
11667 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
11668 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
11669
11670 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
11671 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
11672 // Finally, rematch.
11673 rematchAllNetworksAndRequests();
11674 }
11675
11676 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
11677 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
11678 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11679 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
11680 final List<NetworkRequest> requests = new ArrayList<>();
11681 // Request VPN only, so other networks won't be the fallback options when VPN is not
11682 // connected temporarily.
11683 requests.add(createVpnRequest());
11684 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
11685 setNetworkRequestUids(requests, uidRanges);
11686 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
11687 }
11688 return nris;
11689 }
11690
11691 /**
James Mattisfa270db2021-05-31 17:11:10 -070011692 * Check the validity of an OEM network preference to be used for testing purposes.
11693 * @param preference the preference to validate
11694 * @return true if this is a valid OEM network preference test request.
11695 */
11696 private boolean isValidTestOemNetworkPreference(
11697 @NonNull final OemNetworkPreferences preference) {
11698 // Allow for clearing of an existing OemNetworkPreference used for testing.
11699 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
11700 // changes after this check is complete. This is an unlikely scenario as calling of this API
11701 // is controlled by the OEM therefore the added complexity is not worth adding given those
11702 // circumstances. That said, it is an edge case to be aware of hence this comment.
11703 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
11704 && isTestOemNetworkPreference(mOemNetworkPreferences);
11705 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
11706 }
11707
11708 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
11709 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
11710 return prefMap.size() == 1
11711 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
11712 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
11713 }
11714
James Mattis45d81842021-01-10 14:24:24 -080011715 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
11716 for (@OemNetworkPreferences.OemNetworkPreference final int pref
11717 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070011718 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
11719 throw new IllegalArgumentException(
11720 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
11721 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080011722 }
11723 }
11724 }
11725
11726 private void handleSetOemNetworkPreference(
11727 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011728 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080011729 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11730 if (DBG) {
11731 log("set OEM network preferences :" + preference.toString());
11732 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011733
James Mattiscb1e0362021-04-06 17:07:42 -070011734 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000011735 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
11736 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
11737 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080011738 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080011739
11740 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011741 try {
11742 listener.onComplete();
11743 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080011744 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011745 }
James Mattis45d81842021-01-10 14:24:24 -080011746 }
11747 }
11748
paulhu74128522021-09-28 02:29:03 +000011749 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080011750 // Skip the requests which are set by other network preference. Because the uid range rules
11751 // should stay in netd.
11752 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080011753 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080011754 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080011755 }
11756
James Mattis3ce3d3c2021-02-09 18:18:28 -080011757 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
11758 ensureRunningOnConnectivityServiceThread();
11759 mDefaultNetworkRequests.addAll(nris);
11760 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
11761 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080011762 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000011763 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
11764 nrisToRegister.addAll(
11765 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
11766 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011767 }
11768
11769 /**
11770 * All current requests that are tracking the default network need to be assessed as to whether
11771 * or not the current set of per-application default requests will be changing their default
11772 * network. If so, those requests will need to be updated so that they will send callbacks for
11773 * default network changes at the appropriate time. Additionally, those requests tracking the
11774 * default that were previously updated by this flow will need to be reassessed.
11775 * @return the nris which will need to be updated.
11776 */
11777 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
11778 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
11779 // Get the distinct nris to check since for multilayer requests, it is possible to have the
11780 // same nri in the map's values for each of its NetworkRequest objects.
11781 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080011782 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011783 // Include this nri if it is currently being tracked.
11784 if (isPerAppTrackedNri(nri)) {
11785 defaultCallbackRequests.add(nri);
11786 continue;
11787 }
11788 // We only track callbacks for requests tracking the default.
11789 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
11790 continue;
11791 }
11792 // Include this nri if it will be tracked by the new per-app default requests.
11793 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011794 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080011795 if (isNriGoingToBeTracked) {
11796 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080011797 }
11798 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080011799 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080011800 }
11801
James Mattis3ce3d3c2021-02-09 18:18:28 -080011802 /**
11803 * Create nris for those network requests that are currently tracking the default network that
11804 * are being controlled by a per-application default.
11805 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
11806 * foundation when creating the nri. Important items include the calling uid's original
11807 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
11808 * requests are assumed to have already been validated as needing to be updated.
11809 * @return the Set of nris to use when registering network requests.
11810 */
11811 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
11812 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
11813 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
11814 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
11815 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011816 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011817
Chalard Jean9473c982021-07-29 20:03:04 +090011818 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080011819 if (trackingNri == mDefaultRequest) {
11820 callbackRequestsToRegister.add(new NetworkRequestInfo(
11821 callbackRequest,
11822 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
11823 continue;
11824 }
11825
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011826 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011827 callbackRequestsToRegister.add(new NetworkRequestInfo(
11828 callbackRequest,
11829 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011830 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090011831 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080011832 }
11833 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080011834 }
11835
Chalard Jean17215832021-03-01 14:06:28 +090011836 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
11837 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090011838 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011839 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090011840 }
11841 }
11842
James Mattis45d81842021-01-10 14:24:24 -080011843 /**
11844 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
11845 */
11846 @VisibleForTesting
11847 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011848 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080011849 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011850 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080011851 final SparseArray<Set<Integer>> uids =
11852 createUidsFromOemNetworkPreferences(preference);
11853 for (int i = 0; i < uids.size(); i++) {
11854 final int key = uids.keyAt(i);
11855 final Set<Integer> value = uids.valueAt(i);
11856 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
11857 // No need to add an nri without any requests.
11858 if (0 == nri.mRequests.size()) {
11859 continue;
11860 }
11861 nris.add(nri);
11862 }
11863
11864 return nris;
11865 }
11866
11867 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
11868 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070011869 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080011870 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080011871 final List<UserHandle> users =
11872 mContext.getSystemService(UserManager.class).getUserHandles(true);
11873 if (null == users || users.size() == 0) {
11874 if (VDBG || DDBG) {
11875 log("No users currently available for setting the OEM network preference.");
11876 }
James Mattisb6b6a432021-06-01 22:30:36 -070011877 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080011878 }
James Mattis45d81842021-01-10 14:24:24 -080011879 for (final Map.Entry<String, Integer> entry :
11880 preference.getNetworkPreferences().entrySet()) {
11881 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070011882 // Add the rules for all users as this policy is device wide.
11883 for (final UserHandle user : users) {
11884 try {
11885 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
11886 if (!prefToUids.contains(pref)) {
11887 prefToUids.put(pref, new ArraySet<>());
11888 }
11889 prefToUids.get(pref).add(uid);
11890 } catch (PackageManager.NameNotFoundException e) {
11891 // Although this may seem like an error scenario, it is ok that uninstalled
11892 // packages are sent on a network preference as the system will watch for
11893 // package installations associated with this network preference and update
11894 // accordingly. This is done to minimize race conditions on app install.
11895 continue;
James Mattis45d81842021-01-10 14:24:24 -080011896 }
James Mattis45d81842021-01-10 14:24:24 -080011897 }
11898 }
James Mattisb6b6a432021-06-01 22:30:36 -070011899 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080011900 }
11901
11902 private NetworkRequestInfo createNriFromOemNetworkPreferences(
11903 @OemNetworkPreferences.OemNetworkPreference final int preference,
11904 @NonNull final Set<Integer> uids) {
11905 final List<NetworkRequest> requests = new ArrayList<>();
11906 // Requests will ultimately be evaluated by order of insertion therefore it matters.
11907 switch (preference) {
11908 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
11909 requests.add(createUnmeteredNetworkRequest());
11910 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070011911 requests.add(createDefaultInternetRequestForTransport(
11912 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080011913 break;
11914 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
11915 requests.add(createUnmeteredNetworkRequest());
11916 requests.add(createOemPaidNetworkRequest());
11917 break;
11918 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
11919 requests.add(createOemPaidNetworkRequest());
11920 break;
11921 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
11922 requests.add(createOemPrivateNetworkRequest());
11923 break;
James Mattisfa270db2021-05-31 17:11:10 -070011924 case OEM_NETWORK_PREFERENCE_TEST:
11925 requests.add(createUnmeteredNetworkRequest());
11926 requests.add(createTestNetworkRequest());
11927 requests.add(createDefaultRequest());
11928 break;
11929 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
11930 requests.add(createTestNetworkRequest());
11931 break;
James Mattis45d81842021-01-10 14:24:24 -080011932 default:
11933 // This should never happen.
11934 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
11935 + " called with invalid preference of " + preference);
11936 }
11937
James Mattisfa270db2021-05-31 17:11:10 -070011938 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090011939 for (final int uid : uids) {
11940 ranges.add(new UidRange(uid, uid));
11941 }
11942 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080011943 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080011944 }
11945
11946 private NetworkRequest createUnmeteredNetworkRequest() {
11947 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11948 .addCapability(NET_CAPABILITY_NOT_METERED)
11949 .addCapability(NET_CAPABILITY_VALIDATED);
11950 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
11951 }
11952
11953 private NetworkRequest createOemPaidNetworkRequest() {
11954 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11955 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11956 .addCapability(NET_CAPABILITY_OEM_PAID)
11957 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11958 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11959 }
11960
11961 private NetworkRequest createOemPrivateNetworkRequest() {
11962 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
11963 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11964 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
11965 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11966 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11967 }
11968
11969 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070011970 final NetworkCapabilities netcap = new NetworkCapabilities();
11971 netcap.addCapability(NET_CAPABILITY_INTERNET);
11972 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
11973 return netcap;
11974 }
11975
11976 private NetworkRequest createTestNetworkRequest() {
11977 final NetworkCapabilities netcap = new NetworkCapabilities();
11978 netcap.clearAll();
11979 netcap.addTransportType(TRANSPORT_TEST);
11980 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080011981 }
James Mattis47db0582021-01-01 14:13:35 -080011982 }
markchien738ad912021-12-09 18:15:45 +080011983
11984 @Override
11985 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
11986 enforceNetworkStackOrSettingsPermission();
11987
11988 try {
11989 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011990 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011991 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011992 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011993 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011994 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011995 throw new IllegalStateException(e);
11996 }
11997 }
11998
11999 @Override
12000 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
12001 enforceNetworkStackOrSettingsPermission();
12002
12003 try {
12004 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012005 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012006 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012007 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012008 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012009 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012010 throw new IllegalStateException(e);
12011 }
12012 }
markchiene1561fa2021-12-09 22:00:56 +080012013
12014 @Override
markchien3c04e662022-03-22 16:29:56 +080012015 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080012016 enforceNetworkStackOrSettingsPermission();
12017
markchien3c04e662022-03-22 16:29:56 +080012018 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
12019 int firewallRule = getFirewallRuleType(chain, rule);
12020
12021 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
12022 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
12023 }
12024
markchiene1561fa2021-12-09 22:00:56 +080012025 try {
markchien3c04e662022-03-22 16:29:56 +080012026 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012027 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080012028 throw new IllegalStateException(e);
12029 }
12030 }
markchien98a6f952022-01-13 23:43:53 +080012031
Motomu Utsumi900b8062023-01-19 16:16:49 +090012032 @Override
12033 public int getUidFirewallRule(final int chain, final int uid) {
12034 enforceNetworkStackOrSettingsPermission();
12035 return mBpfNetMaps.getUidRule(chain, uid);
12036 }
12037
markchien3c04e662022-03-22 16:29:56 +080012038 private int getFirewallRuleType(int chain, int rule) {
12039 final int defaultRule;
12040 switch (chain) {
12041 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000012042 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
12043 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000012044 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080012045 defaultRule = FIREWALL_RULE_ALLOW;
12046 break;
12047 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
12048 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
12049 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
12050 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
12051 defaultRule = FIREWALL_RULE_DENY;
12052 break;
12053 default:
12054 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
12055 }
12056 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
12057
12058 return rule;
12059 }
12060
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012061 private void closeSocketsForFirewallChainLocked(final int chain)
12062 throws ErrnoException, SocketException, InterruptedIOException {
12063 if (mBpfNetMaps.isFirewallAllowList(chain)) {
12064 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
12065 // So, close all non-system socket owned by uids that are not explicitly allowed
12066 Set<Range<Integer>> ranges = new ArraySet<>();
12067 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
12068 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
12069 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
12070 } else {
12071 // Denylist means the firewall allows all by default, uids must be explicitly denied
12072 // So, close socket owned by uids that are explicitly denied
12073 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
12074 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
12075 }
12076 }
12077
markchien98a6f952022-01-13 23:43:53 +080012078 @Override
12079 public void setFirewallChainEnabled(final int chain, final boolean enable) {
12080 enforceNetworkStackOrSettingsPermission();
12081
12082 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012083 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012084 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080012085 throw new IllegalStateException(e);
12086 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012087
12088 if (SdkLevel.isAtLeastU() && enable) {
12089 try {
12090 closeSocketsForFirewallChainLocked(chain);
12091 } catch (ErrnoException | SocketException | InterruptedIOException e) {
12092 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
12093 }
12094 }
markchien98a6f952022-01-13 23:43:53 +080012095 }
12096
markchien00a0bed2022-01-13 23:46:13 +080012097 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012098 public boolean getFirewallChainEnabled(final int chain) {
12099 enforceNetworkStackOrSettingsPermission();
12100
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000012101 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012102 }
12103
12104 @Override
markchien00a0bed2022-01-13 23:46:13 +080012105 public void replaceFirewallChain(final int chain, final int[] uids) {
12106 enforceNetworkStackOrSettingsPermission();
12107
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000012108 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080012109 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080012110
12111 @Override
12112 public IBinder getCompanionDeviceManagerProxyService() {
12113 enforceNetworkStackPermission(mContext);
12114 return mCdmps;
12115 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070012116}