blob: 6aee6f8b9ccbd7965ca1be9588e8d7b6624d4044 [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;
Chalard Jeane0aaca52023-10-17 13:23:07 +090022import static android.content.pm.PackageManager.FEATURE_LEANBACK;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090023import static android.content.pm.PackageManager.FEATURE_WATCH;
24import static android.content.pm.PackageManager.FEATURE_WIFI;
25import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
Chalard Jean9a396cc2018-02-21 18:43:54 +090026import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090027import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
28import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
29import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
33import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
34import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090035import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
36import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000037import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Aaron Huang9fe47be2021-06-08 13:11:45 +080038import static android.net.ConnectivityManager.CALLBACK_IP_CHANGED;
Jeff Sharkey971cd162011-08-29 16:02:57 -070039import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
markchien3c04e662022-03-22 16:29:56 +080040import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
41import static android.net.ConnectivityManager.FIREWALL_RULE_DEFAULT;
42import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090043import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090044import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090045import static android.net.ConnectivityManager.TYPE_MOBILE;
46import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
47import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
48import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
49import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
50import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
51import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
52import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
53import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
54import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070055import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090056import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070057import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090058import static android.net.ConnectivityManager.TYPE_WIFI;
59import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070060import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070061import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080062import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080063import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080064import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070065import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080066import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040067import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090068import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090070import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Chalard Jeane0aaca52023-10-17 13:23:07 +090071import static android.net.NetworkCapabilities.NET_CAPABILITY_LOCAL_NETWORK;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090072import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090073import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
74import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060075import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090076import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080077import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090078import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080079import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
80import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080081import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Chalard Jeanf95e2de2023-08-22 19:07:47 +090082import static android.net.NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090083import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080084import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
85import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080086import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
87import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
88import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090089import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090090import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060091import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070092import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080093import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090094import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070095import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
96import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070097import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080098import static android.os.Process.VPN_UID;
Patrick Rohr2857ac42022-01-21 14:58:16 +010099import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700100import static android.system.OsConstants.IPPROTO_TCP;
101import static android.system.OsConstants.IPPROTO_UDP;
Chalard Jeaneb663892023-10-07 15:17:07 +0900102
Xiao Ma60142372022-07-16 17:30:20 +0900103import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Junyu Lai4c6fe232023-04-11 11:33:46 +0800104import static com.android.net.module.util.PermissionUtils.checkAnyPermissionOf;
paulhu3ffffe72021-09-16 10:15:22 +0800105import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
106import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
107import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900108import static com.android.server.ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE;
Chalard Jeaneb663892023-10-07 15:17:07 +0900109
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800110import static java.util.Map.Entry;
111
Chalard Jean5b639762020-03-09 21:25:37 +0900112import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000113import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800114import android.annotation.Nullable;
Michael Groover73f69482023-01-27 11:01:25 -0600115import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800116import android.annotation.TargetApi;
Mark Fasheh7c999d82023-05-04 20:23:11 +0000117import android.app.ActivityManager;
118import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800119import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800120import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700121import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700122import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900123import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800124import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700125import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800126import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800127import android.content.ContentResolver;
128import android.content.Context;
129import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700130import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800131import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900132import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700133import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900134import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900135import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700136import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800137import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800138import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800139import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900140import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800141import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900142import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800143import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900144import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800145import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700146import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900147import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800148import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800149import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800150import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800151import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800152import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900153import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900154import android.net.INetworkMonitor;
155import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900156import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900157import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700158import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800159import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900160import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900161import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900162import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800163import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100164import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800165import android.net.NativeNetworkConfig;
166import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800167import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700168import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700169import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900170import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700171import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800172import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700173import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900174import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900175import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000176import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900177import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700178import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900179import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700180import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900181import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700182import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800183import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900184import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700185import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000186import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800187import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900188import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800189import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400190import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700191import android.net.QosCallbackException;
192import android.net.QosFilter;
193import android.net.QosSocketFilter;
194import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700195import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800196import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800197import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800198import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900199import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400200import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800201import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800202import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400203import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800204import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900205import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900206import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900207import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900208import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800209import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900210import android.net.networkstack.ModuleNetworkStackClient;
211import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900212import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800213import android.net.resolv.aidl.DnsHealthEventParcel;
214import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
215import android.net.resolv.aidl.Nat64PrefixEventParcel;
216import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900217import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900218import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800219import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800220import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800221import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700222import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000223import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800224import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700225import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700226import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800227import android.os.Looper;
228import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700229import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700230import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900231import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800232import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700233import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700234import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800235import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700236import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900237import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900238import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700239import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700240import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400241import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800242import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900243import android.stats.connectivity.MeteredState;
244import android.stats.connectivity.RequestType;
245import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900246import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700247import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700248import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700249import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800250import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900251import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000252import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600253import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900254import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900255import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700256import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700257import android.util.SparseIntArray;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900258import android.util.StatsEvent;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800259
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800260import androidx.annotation.RequiresApi;
261
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900262import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400263import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400264import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700265import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900266import com.android.internal.util.MessageUtils;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900267import com.android.metrics.ConnectionDurationForTransports;
268import com.android.metrics.ConnectionDurationPerTransports;
269import com.android.metrics.ConnectivitySampleMetricsHelper;
270import com.android.metrics.ConnectivityStateSample;
271import com.android.metrics.NetworkCountForTransports;
272import com.android.metrics.NetworkCountPerTransports;
273import com.android.metrics.NetworkDescription;
274import com.android.metrics.NetworkList;
275import com.android.metrics.NetworkRequestCount;
276import com.android.metrics.RequestCountForType;
Chiachang Wang62740142020-11-02 16:51:24 +0800277import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900278import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800279import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000280import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900281import com.android.net.module.util.BitUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900282import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900283import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100284import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900285import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
286import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900287import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800288import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800289import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100290import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000291import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800292import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
293import com.android.networkstack.apishim.ConstantsShim;
294import com.android.networkstack.apishim.common.BroadcastOptionsShim;
295import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900296import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900297import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000298import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900299import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800300import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800301import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900302import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900303import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900304import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500305import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700306import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900307import com.android.server.connectivity.FullScore;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900308import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900309import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000310import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100311import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700312import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900313import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700314import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600315import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900316import com.android.server.connectivity.NetworkNotificationManager;
317import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900318import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900319import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900320import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700321import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900322import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900323import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700324import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800325import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000326import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800327import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600328
Josh Gao461a1222020-06-16 15:58:11 -0700329import libcore.io.IoUtils;
330
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900331import org.xmlpull.v1.XmlPullParserException;
332
The Android Open Source Project28527d22009-03-03 19:31:44 -0800333import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100334import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900335import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800336import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900337import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700338import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700339import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900340import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900341import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700342import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700343import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700344import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700345import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800346import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900347import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800348import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700349import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700350import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700351import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700352import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900353import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700354import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900355import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600356import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900357import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600358import java.util.TreeSet;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900359import java.util.concurrent.TimeUnit;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900360import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800361
362/**
363 * @hide
364 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800365public class ConnectivityService extends IConnectivityManager.Stub
366 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900367 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800368
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900369 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900370 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900371 private static final String NETWORK_ARG = "networks";
372 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800373 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900374
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900375 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900376 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
377 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800378
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900379 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700380
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100381 /**
382 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
383 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800384 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100385 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
386 * (preferably via runtime resource overlays).
387 */
388 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
389 "http://connectivitycheck.gstatic.com/generate_204";
390
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700391 // TODO: create better separation between radio types and network types
392
Robert Greenwalt2034b912009-08-12 16:08:25 -0700393 // how long to wait before switching back to a radio's default network
394 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
395 // system property that can override the above value
396 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
397 "android.telephony.apn-restore";
398
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900399 // How long to wait before putting up a "This network doesn't have an Internet connection,
400 // connect anyway?" dialog after the user selects a network that doesn't validate.
401 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
402
Chalard Jean5fb43c72022-09-08 19:03:14 +0900403 // How long to wait before considering that a network is bad in the absence of any form
404 // of connectivity (valid, partial, captive portal). If none has been detected after this
405 // delay, the stack considers this network bad, which may affect how it's handled in ranking
406 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900407 // Timeout in case the "actively prefer bad wifi" feature is on
408 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
409 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900410 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900411
junyulai0ac374f2020-12-14 18:41:52 +0800412 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900413 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
414 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800415 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700416
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800417 // Delimiter used when creating the broadcast delivery group for sending
418 // CONNECTIVITY_ACTION broadcast.
419 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
420
he_won.hwang881307a2022-03-15 21:23:52 +0900421 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900422 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900423
Daniel Brightf9e945b2020-06-15 16:10:01 -0700424 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900425 @VisibleForTesting
426 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700427
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900428 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700429 @VisibleForTesting
430 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900431
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900432 @VisibleForTesting
433 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800434 @VisibleForTesting
435 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900436 // True if the cell radio of the device is capable of time-sharing.
437 @VisibleForTesting
438 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900439
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800440 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800441 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800442 private final int mReleasePendingIntentDelayMs;
443
Chalard Jean46bfbf02022-02-02 00:56:25 +0900444 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900445
Motomu Utsumif360aa62023-01-30 17:52:20 +0900446 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700447
Chalard Jean9473c982021-07-29 20:03:04 +0900448 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800449 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700450 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800451 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700452
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900453 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700454
junyulaif2c67e42018-08-07 19:50:45 +0800455 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000456 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
457 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800458 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900459 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800460
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900461 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900462 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000463 private final int mWakeUpMark;
464 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000465 // The Context is created for UserHandle.ALL.
466 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900467 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900468 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700469 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700470 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800471
Chenbo Feng15416292018-11-08 17:36:21 -0800472 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800473 protected IDnsResolver mDnsResolver;
474 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800475 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700476 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900477 private final NetworkStatsManager mStatsManager;
478 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800479 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700480
Benedict Wong493e04b2018-11-09 14:45:34 -0800481 /**
482 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
483 * instances.
484 */
485 @GuardedBy("mTNSLock")
486 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800487 private final CompanionDeviceManagerProxyService mCdmps;
Benedict Wong493e04b2018-11-09 14:45:34 -0800488
489 private final Object mTNSLock = new Object();
490
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700491 private String mCurrentTcpBufferSizes;
492
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900493 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000494 new Class[] {
495 ConnectivityService.class,
496 NetworkAgent.class,
497 NetworkAgentInfo.class,
498 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900499
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500500 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400501 // Tear down networks that have no chance (e.g. even if validated) of becoming
502 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500503 // all networks have been rematched against all NetworkRequests.
504 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400505 // Don't reap networks. This should be passed when some networks have not yet been
506 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500507 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900508 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500509
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900510 private enum UnneededFor {
511 LINGER, // Determine whether this network is unneeded and should be lingered.
512 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
513 }
514
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700515 /**
paulhuaa0743d2021-05-26 21:56:03 +0800516 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800517 * should have priority. The order is passed to netd which will use it together
518 * with UID ranges to generate the corresponding IP rule. This serves to
519 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800520 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800521 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000522 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800523 *
paulhu48291862021-07-14 14:53:57 +0800524 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
525 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800526 */
paulhu48291862021-07-14 14:53:57 +0800527 // Used when sending to netd to code for "no order".
528 static final int PREFERENCE_ORDER_NONE = 0;
529 // Order for requests that don't code for a per-app preference. As it is
530 // out of the valid range, the corresponding order should be
531 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800532 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800533 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800534 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800535 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
536 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800537 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800538 static final int PREFERENCE_ORDER_OEM = 10;
539 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800540 // See {@link #setProfileNetworkPreference}.
541 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800542 static final int PREFERENCE_ORDER_PROFILE = 20;
543 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800544 // better scores are connected.
545 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800546 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800547 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900548 // Preference order that signifies the network shouldn't be set as a default network for
549 // the UIDs, only give them access to it. TODO : replace this with a boolean
550 // in NativeUidRangeConfig
551 @VisibleForTesting
552 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
553 // Bound for the lowest valid preference order.
554 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800555
556 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700557 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700558 * from one net to another. Clear happens when we get a new
559 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
560 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700561 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700562 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700563
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700564 /**
565 * used internally to reload global proxy settings
566 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700567 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700568
Robert Greenwalt34848c02011-03-25 13:09:25 -0700569 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400570 * PAC manager has received new port.
571 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800572 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400573
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700574 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900575 * used internally when registering NetworkProviders
576 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700577 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900578 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700579
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700580 /**
581 * used internally when registering NetworkAgents
582 * obj = Messenger
583 */
584 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
585
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700586 /**
587 * used to add a network request
588 * includes a NetworkRequestInfo
589 */
590 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
591
592 /**
593 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900594 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700595 * cancel it.
596 * includes a NetworkRequestInfo
597 */
598 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
599
600 /**
601 * used to add a network listener - no request
602 * includes a NetworkRequestInfo
603 */
604 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
605
606 /**
607 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400608 * arg1 = UID of caller
609 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700610 */
611 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
612
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700613 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900614 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700615 * obj = Messenger
616 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900617 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700618
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700619 /**
620 * used internally to expire a wakelock when transitioning
621 * from one net to another. Expire happens when we fail to find
622 * a new network (typically after 1 minute) -
623 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
624 * a replacement network.
625 */
626 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
627
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700628 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800629 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400630 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800631 */
632 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
633
634 /**
635 * used to remove a pending intent and its associated network request.
636 * arg1 = UID of caller
637 * obj = PendingIntent
638 */
639 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
640
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900641 /**
642 * used to specify whether a network should be used even if unvalidated.
643 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
644 * arg2 = whether to remember this choice in the future (1 or 0)
645 * obj = network
646 */
647 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
648
649 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700650 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900651 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700652 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900653
Paul Jensenc8873fc2015-06-17 14:15:39 -0400654 /**
655 * used to add a network listener with a pending intent
656 * obj = NetworkRequestInfo
657 */
658 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
659
Hugo Benichid6b510a2017-04-06 17:22:18 +0900660 /**
661 * used to specify whether a network should not be penalized when it becomes unvalidated.
662 */
663 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
664
665 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700666 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900667 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700668 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900669
Erik Kline31b4a9e2018-01-11 21:07:29 +0900670 // Handle changes in Private DNS settings.
671 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
672
dalyk1720e542018-03-05 12:42:22 -0500673 // Handle private DNS validation status updates.
674 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
675
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900676 /**
677 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
678 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800679 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
680 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
681 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900682 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900683 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900684
685 /**
686 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
687 * config was resolved.
688 * obj = PrivateDnsConfig
689 * arg2 = netid
690 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900691 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900692
693 /**
694 * Request ConnectivityService display provisioning notification.
695 * arg1 = Whether to make the notification visible.
696 * arg2 = NetID.
697 * obj = Intent to be launched when notification selected by user, null if !arg1.
698 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900699 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900700
701 /**
lucaslin2240ef62019-03-12 13:08:03 +0800702 * Used to specify whether a network should be used even if connectivity is partial.
703 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
704 * false)
705 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
706 * obj = network
707 */
lucaslin444d43a2020-02-20 16:56:59 +0800708 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800709
710 /**
lucasline117e2e2019-10-22 18:27:33 +0800711 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
712 * Both of the arguments are bitmasks, and the value of bits come from
713 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900714 * arg1 = unused
715 * arg2 = netId
716 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800717 */
lucaslin444d43a2020-02-20 16:56:59 +0800718 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800719
720 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900721 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
722 * arg1 = unused
723 * arg2 = netId
724 * obj = captive portal data
725 */
lucaslin444d43a2020-02-20 16:56:59 +0800726 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900727
728 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900729 * Used by setRequireVpnForUids.
730 * arg1 = whether the specified UID ranges are required to use a VPN.
731 * obj = Array of UidRange objects.
732 */
733 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
734
735 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900736 * Used internally when setting the default networks for OemNetworkPreferences.
737 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800738 */
739 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
740
741 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800742 * Used to indicate the system default network becomes active.
743 */
744 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
745
746 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900747 * Used internally when setting a network preference for a user profile.
748 * obj = Pair<ProfileNetworkPreference, Listener>
749 */
750 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
751
752 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000753 * Event to specify that reasons for why an uid is blocked changed.
754 * arg1 = uid
755 * arg2 = blockedReasons
756 */
757 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
758
759 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900760 * Event to register a new network offer
761 * obj = NetworkOffer
762 */
763 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
764
765 /**
766 * Event to unregister an existing network offer
767 * obj = INetworkOfferCallback
768 */
769 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
770
771 /**
paulhu51f77dc2021-06-07 02:34:20 +0000772 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
773 */
774 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
775
776 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800777 * Event to set temporary allow bad wifi within a limited time to override
778 * {@code config_networkAvoidBadWifi}.
779 */
780 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
781
782 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100783 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
784 */
785 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
786
787 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900788 * The initial evaluation period is over for this network.
789 *
790 * If no form of connectivity has been found on this network (valid, partial, captive portal)
791 * then the stack will now consider it to have been determined bad.
792 */
793 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
794
795 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000796 * Used internally when the user does not want the network from captive portal app.
797 * obj = Network
798 */
799 private static final int EVENT_USER_DOES_NOT_WANT = 58;
800
801 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000802 * Event to set VPN as preferred network for specific apps.
803 * obj = VpnNetworkPreferenceInfo
804 */
805 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
806
807 /**
chiachangwange0192a72023-02-06 13:25:01 +0000808 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
809 */
810 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
811
812 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000813 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
814 */
815 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
816
817 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900818 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
819 * should be shown.
820 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900821 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900822
823 /**
824 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
825 * should be hidden.
826 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900827 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900828
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800829 /**
830 * The maximum alive time to allow bad wifi configuration for testing.
831 */
832 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
833
Patrick Rohr2857ac42022-01-21 14:58:16 +0100834 /**
chiachangwange0192a72023-02-06 13:25:01 +0000835 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
836 * testing.
837 */
838 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
839
840 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100841 * The priority of the tc police rate limiter -- smaller value is higher priority.
842 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
843 */
844 private static final short TC_PRIO_POLICE = 1;
845
846 /**
847 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
848 */
849 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700850 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100851
Hugo Benichi47011212017-03-30 10:46:05 +0900852 private static String eventName(int what) {
853 return sMagicDecoderRing.get(what, Integer.toString(what));
854 }
855
paulhua10d8212020-11-10 15:32:56 +0800856 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900857 final DnsResolverServiceManager dsm = context.getSystemService(
858 DnsResolverServiceManager.class);
859 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800860 }
861
Cody Kesting73708bf2019-12-18 10:57:50 -0800862 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900863 @VisibleForTesting
864 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700865 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700866 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700867 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700868 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800869 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
870 @VisibleForTesting
871 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
872
Erik Kline32120082017-12-13 19:40:49 +0900873 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900874 @VisibleForTesting
875 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700876
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400877 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800878 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400879
Chalard Jean46bfbf02022-02-02 00:56:25 +0900880 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800881 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700882
Chalard Jean5d70ba42018-06-07 16:44:04 +0900883 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
884 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800885 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400886
Erik Kline05f2b402015-04-30 12:58:40 +0900887 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700888
Chalard Jean46bfbf02022-02-02 00:56:25 +0900889 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400890
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700891 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900892 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700893
Valentin Iftime9fa35092019-09-24 13:32:13 +0200894 private Set<String> mWolSupportedInterfaces;
895
Roshan Pius08c94fb2020-01-16 12:17:17 -0800896 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800897 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800898 private final AppOpsManager mAppOpsManager;
899
900 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400901
chiachangwang3d60bac2023-01-17 14:38:08 +0000902 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900903 private final QosCallbackTracker mQosCallbackTracker;
904 private final NetworkNotificationManager mNotifier;
905 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900906
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700907 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800908 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700909
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900910 // Sequence number for NetworkProvider IDs.
911 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
912 NetworkProvider.FIRST_PROVIDER_ID);
913
Erik Klineedf878b2015-07-09 18:24:03 +0900914 // NetworkRequest activity String log entries.
915 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
916 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
917
Hugo Benichid159fdd2016-07-11 11:05:12 +0900918 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900919 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900920 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
921
Hugo Benichi47011212017-03-30 10:46:05 +0900922 private static final int MAX_WAKELOCK_LOGS = 20;
923 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900924 private int mTotalWakelockAcquisitions = 0;
925 private int mTotalWakelockReleases = 0;
926 private long mTotalWakelockDurationMs = 0;
927 private long mMaxWakelockDurationMs = 0;
928 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900929
Hugo Benichi208c0102016-07-28 17:53:06 +0900930 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900931
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700932 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900933 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700934
Erik Kline95ecfee2016-10-02 18:02:14 +0900935 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900936 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900937
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900938 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800939 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
940 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800941
Patrick Rohr2857ac42022-01-21 14:58:16 +0100942 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
943 // configured via {@link
944 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
945 // Only the handler thread is allowed to access this field.
946 private long mIngressRateLimit = -1;
947
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900948 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
949 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900950 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900951 @GuardedBy("mSelfCertifiedCapabilityCache")
952 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
953 mSelfCertifiedCapabilityCache = new HashMap<>();
954
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900955 // Flag to enable the feature of closing frozen app sockets.
956 private final boolean mDestroyFrozenSockets;
957
958 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
959 private final boolean mDelayDestroyFrozenSockets;
960
961 // Uids that ConnectivityService is pending to close sockets of.
962 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
963
Robert Greenwalt802c1102014-06-02 15:32:02 -0700964 /**
965 * Implements support for the legacy "one network per network type" model.
966 *
967 * We used to have a static array of NetworkStateTrackers, one for each
968 * network type, but that doesn't work any more now that we can have,
969 * for example, more that one wifi network. This class stores all the
970 * NetworkAgentInfo objects that support a given type, but the legacy
971 * API will only see the first one.
972 *
973 * It serves two main purposes:
974 *
975 * 1. Provide information about "the network for a given type" (since this
976 * API only supports one).
977 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
978 * the first network for a given type changes, or if the default network
979 * changes.
980 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900981 @VisibleForTesting
982 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900983
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900984 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900985 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900986
Robert Greenwalt802c1102014-06-02 15:32:02 -0700987 /**
988 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
989 * Each list holds references to all NetworkAgentInfos that are used to
990 * satisfy requests for that network type.
991 *
992 * This array is built out at startup such that an unsupported network
993 * doesn't get an ArrayList instance, making this a tristate:
994 * unsupported, supported but not active and active.
995 *
996 * The actual lists are populated when we scan the network types that
997 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900998 *
999 * Threading model:
1000 * - addSupportedType() is only called in the constructor
1001 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1002 * They are therefore not thread-safe with respect to each other.
1003 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1004 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001005 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001006 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001007 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001008 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001009 @NonNull
1010 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001011
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001012 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1013 // an entry have no timer (equivalent to -1). Lazily loaded.
1014 @NonNull
1015 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1016
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001017 LegacyTypeTracker(@NonNull ConnectivityService service) {
1018 mService = service;
1019 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001020 }
1021
Chiachang Wang3bc52762021-11-25 14:17:57 +08001022 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1023 // addressed.
1024 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001025 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1026 final PackageManager pm = ctx.getPackageManager();
1027 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1028 addSupportedType(TYPE_WIFI);
1029 }
1030 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1031 addSupportedType(TYPE_WIFI_P2P);
1032 }
1033 if (tm.isDataCapable()) {
1034 // Telephony does not have granular support for these types: they are either all
1035 // supported, or none is supported
1036 addSupportedType(TYPE_MOBILE);
1037 addSupportedType(TYPE_MOBILE_MMS);
1038 addSupportedType(TYPE_MOBILE_SUPL);
1039 addSupportedType(TYPE_MOBILE_DUN);
1040 addSupportedType(TYPE_MOBILE_HIPRI);
1041 addSupportedType(TYPE_MOBILE_FOTA);
1042 addSupportedType(TYPE_MOBILE_IMS);
1043 addSupportedType(TYPE_MOBILE_CBS);
1044 addSupportedType(TYPE_MOBILE_IA);
1045 addSupportedType(TYPE_MOBILE_EMERGENCY);
1046 }
1047 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1048 addSupportedType(TYPE_BLUETOOTH);
1049 }
1050 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1051 // TYPE_PROXY is only used on Wear
1052 addSupportedType(TYPE_PROXY);
1053 }
1054 // Ethernet is often not specified in the configs, although many devices can use it via
1055 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001056 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001057 addSupportedType(TYPE_ETHERNET);
1058 }
1059
1060 // Always add TYPE_VPN as a supported type
1061 addSupportedType(TYPE_VPN);
1062 }
1063
1064 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001065 if (mTypeLists[type] != null) {
1066 throw new IllegalStateException(
1067 "legacy list for type " + type + "already initialized");
1068 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001069 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001070 }
1071
Robert Greenwalt802c1102014-06-02 15:32:02 -07001072 public boolean isTypeSupported(int type) {
1073 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1074 }
1075
1076 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001077 synchronized (mTypeLists) {
1078 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1079 return mTypeLists[type].get(0);
1080 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001081 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001082 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001083 }
1084
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001085 public int getRestoreTimerForType(int type) {
1086 synchronized (mTypeLists) {
1087 if (mRestoreTimers == null) {
1088 mRestoreTimers = loadRestoreTimers();
1089 }
1090 return mRestoreTimers.getOrDefault(type, -1);
1091 }
1092 }
1093
1094 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1095 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001096 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001097 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1098 for (final String config : configs) {
1099 final String[] splits = TextUtils.split(config, ",");
1100 if (splits.length != 2) {
1101 logwtf("Invalid restore timer token count: " + config);
1102 continue;
1103 }
1104 try {
1105 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1106 } catch (NumberFormatException e) {
1107 logwtf("Invalid restore timer number format: " + config, e);
1108 }
1109 }
1110 return ret;
1111 }
1112
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001113 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001114 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001115 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001116 log("Sending " + state
1117 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001118 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001119 }
1120 }
1121
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001122 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1123 // network type, to preserve previous behaviour.
1124 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1125 if (vpnNai != mService.getLegacyLockdownNai()) return;
1126
1127 if (vpnNai.declaredUnderlyingNetworks == null
1128 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1129 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1130 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1131 return;
1132 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001133 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001134 vpnNai.declaredUnderlyingNetworks[0]);
1135 if (underlyingNai == null) return;
1136
1137 final int type = underlyingNai.networkInfo.getType();
1138 final DetailedState state = DetailedState.CONNECTED;
1139 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1140 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1141 }
1142
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001143 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001144 public void add(int type, NetworkAgentInfo nai) {
1145 if (!isTypeSupported(type)) {
1146 return; // Invalid network type.
1147 }
1148 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1149
1150 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1151 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001152 return;
1153 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001154 synchronized (mTypeLists) {
1155 list.add(nai);
1156 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001157
Chalard Jean5b409c72021-02-04 13:12:59 +09001158 // Send a broadcast if this is the first network of its type or if it's the default.
1159 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001160
1161 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1162 // to preserve previous behaviour.
1163 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001164 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001165 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1166 mService.sendLegacyNetworkBroadcast(nai, state, type);
1167 }
1168
1169 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1170 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001171 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001172 }
1173
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001174 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001175 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001176 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1177 if (list == null || list.isEmpty()) {
1178 return;
1179 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001180 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001181
Hugo Benichi389633f2016-06-21 09:48:07 +09001182 synchronized (mTypeLists) {
1183 if (!list.remove(nai)) {
1184 return;
1185 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001186 }
1187
Lorenzo Colitti49767722015-05-01 00:30:10 +09001188 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001189 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1190 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001191 }
1192
1193 if (!list.isEmpty() && wasFirstNetwork) {
1194 if (DBG) log("Other network available for type " + type +
1195 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001196 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001197 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001198 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001199 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001200 }
1201 }
1202
1203 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001204 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1205 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001206 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001207 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001208 }
1209 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001210
Chalard Jean46bfbf02022-02-02 00:56:25 +09001211 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001212 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001213 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001214 final DetailedState state = nai.networkInfo.getDetailedState();
1215 for (int type = 0; type < mTypeLists.length; type++) {
1216 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001217 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001218 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001219 if (isFirst || contains && isDefault) {
1220 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001221 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001222 }
1223 }
1224 }
1225
Robert Greenwalt94e22142014-07-30 16:31:24 -07001226 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001227 pw.println("mLegacyTypeTracker:");
1228 pw.increaseIndent();
1229 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001230 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001231 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001232 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001233 pw.println();
1234 pw.println("Current state:");
1235 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001236 synchronized (mTypeLists) {
1237 for (int type = 0; type < mTypeLists.length; type++) {
1238 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1239 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001240 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001241 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001242 }
1243 }
1244 pw.decreaseIndent();
1245 pw.decreaseIndent();
1246 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001247 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001248 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001249 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001250
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001251 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001252 /**
1253 * Helper class which parses out priority arguments and dumps sections according to their
1254 * priority. If priority arguments are omitted, function calls the legacy dump command.
1255 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001256 private class LocalPriorityDump {
1257 private static final String PRIORITY_ARG = "--dump-priority";
1258 private static final String PRIORITY_ARG_HIGH = "HIGH";
1259 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1260
1261 LocalPriorityDump() {}
1262
1263 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1264 doDump(fd, pw, new String[] {DIAG_ARG});
1265 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001266 }
1267
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001268 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1269 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001270 }
1271
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001272 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1273 if (args == null) {
1274 dumpNormal(fd, pw, args);
1275 return;
1276 }
1277
1278 String priority = null;
1279 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1280 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1281 argIndex++;
1282 priority = args[argIndex];
1283 }
1284 }
1285
1286 if (PRIORITY_ARG_HIGH.equals(priority)) {
1287 dumpHigh(fd, pw);
1288 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1289 dumpNormal(fd, pw, args);
1290 } else {
1291 // ConnectivityService publishes binder service using publishBinderService() with
1292 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001293 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1294 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001295 // TODO: Integrate into signal dump.
1296 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001297 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001298 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001299 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001300
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001301 /**
1302 * Dependencies of ConnectivityService, for injection in tests.
1303 */
1304 @VisibleForTesting
1305 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001306 public int getCallingUid() {
1307 return Binder.getCallingUid();
1308 }
1309
Chalard Jeandf29a852023-05-29 17:02:43 +09001310 public boolean isAtLeastS() {
1311 return SdkLevel.isAtLeastS();
1312 }
1313
1314 public boolean isAtLeastT() {
1315 return SdkLevel.isAtLeastT();
1316 }
1317
1318 public boolean isAtLeastU() {
1319 return SdkLevel.isAtLeastU();
1320 }
1321
Chalard Jeaneb663892023-10-07 15:17:07 +09001322 public boolean isAtLeastV() {
1323 return SdkLevel.isAtLeastV();
1324 }
1325
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001326 /**
1327 * Get system properties to use in ConnectivityService.
1328 */
1329 public MockableSystemProperties getSystemProperties() {
1330 return new MockableSystemProperties();
1331 }
1332
1333 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001334 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1335 */
1336 public ConnectivityResources getResources(@NonNull Context ctx) {
1337 return new ConnectivityResources(ctx);
1338 }
1339
1340 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001341 * Create a HandlerThread to use in ConnectivityService.
1342 */
1343 public HandlerThread makeHandlerThread() {
1344 return new HandlerThread("ConnectivityServiceThread");
1345 }
1346
1347 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001348 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001349 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001350 public NetworkStackClientBase getNetworkStack() {
1351 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001352 }
1353
1354 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001355 * @see ProxyTracker
1356 */
1357 public ProxyTracker makeProxyTracker(@NonNull Context context,
1358 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001359 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001360 }
1361
1362 /**
1363 * @see NetIdManager
1364 */
1365 public NetIdManager makeNetIdManager() {
1366 return new NetIdManager();
1367 }
1368
1369 /**
1370 * @see NetworkUtils#queryUserAccess(int, int)
1371 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001372 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1373 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001374 }
1375
1376 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001377 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1378 * requires CAP_NET_ADMIN, which the unit tests do not have.
1379 */
1380 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1381 InetSocketAddress remote) {
1382 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1383 }
1384
1385 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001386 * @see MultinetworkPolicyTracker
1387 */
1388 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1389 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1390 return new MultinetworkPolicyTracker(c, h, r);
1391 }
1392
Aaron Huang330a4c02020-10-27 03:36:19 +08001393 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001394 * @see AutomaticOnOffKeepaliveTracker
1395 */
1396 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1397 @NonNull Context c, @NonNull Handler h) {
1398 return new AutomaticOnOffKeepaliveTracker(c, h);
1399 }
1400
1401 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001402 * @see BatteryStatsManager
1403 */
1404 public void reportNetworkInterfaceForTransports(Context context, String iface,
1405 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001406 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001407 context.getSystemService(BatteryStatsManager.class);
1408 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1409 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001410
1411 public boolean getCellular464XlatEnabled() {
1412 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1413 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001414
1415 /**
1416 * @see PendingIntent#intentFilterEquals
1417 */
1418 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1419 return a.intentFilterEquals(b);
1420 }
1421
1422 /**
1423 * @see LocationPermissionChecker
1424 */
1425 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1426 return new LocationPermissionChecker(context);
1427 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001428
1429 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001430 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001431 *
1432 * This method returns null in versions before T, where carrier privilege
1433 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001434 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001435 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001436 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1437 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001438 if (isAtLeastT()) {
Chalard Jean84dfa9f2023-01-30 11:23:20 +09001439 return new CarrierPrivilegeAuthenticator(context, this, tm);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001440 } else {
1441 return null;
1442 }
1443 }
1444
1445 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001446 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001447 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001448 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001449 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001450 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001451
1452 /**
1453 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001454 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001455 * @return BpfNetMaps implementation.
1456 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001457 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1458 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001459 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001460
1461 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001462 * @see ClatCoordinator
1463 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001464 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001465 public ClatCoordinator getClatCoordinator(INetd netd) {
1466 return new ClatCoordinator(
1467 new ClatCoordinator.Dependencies() {
1468 @NonNull
1469 public INetd getNetd() {
1470 return netd;
1471 }
1472 });
1473 }
1474
1475 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001476 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1477 */
1478 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1479 final InterfaceParams params = InterfaceParams.getByName(iface);
1480 if (params == null) {
1481 // the interface might have disappeared.
1482 logw("Failed to get interface params for interface " + iface);
1483 return;
1484 }
1485 try {
1486 // converting rateInBytesPerSecond from long to int is safe here because the
1487 // setting's range is limited to INT_MAX.
1488 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001489 Log.i(TAG,
1490 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001491 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1492 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1493 } catch (IOException e) {
1494 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1495 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1496 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1497 + ") failure: ", e);
1498 }
1499 }
1500
1501 /**
1502 * Wraps {@link TcUtils#tcFilterDelDev}
1503 */
1504 public void disableIngressRateLimit(String iface) {
1505 final InterfaceParams params = InterfaceParams.getByName(iface);
1506 if (params == null) {
1507 // the interface might have disappeared.
1508 logw("Failed to get interface params for interface " + iface);
1509 return;
1510 }
1511 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001512 Log.i(TAG,
1513 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001514 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1515 } catch (IOException e) {
1516 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1517 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1518 }
1519 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001520
1521 /**
1522 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1523 */
1524 // TODO: when available in all active branches:
1525 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1526 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1527 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1528 return BroadcastOptionsShimImpl.newInstance(options);
1529 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001530
1531 /**
1532 * Wrapper method for
1533 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1534 *
1535 * @param changeId The ID of the compatibility change in question.
1536 * @param packageName The package name of the app in question.
1537 * @param user The user that the operation is done for.
1538 * @return {@code true} if the change is enabled for the specified package.
1539 */
1540 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1541 @NonNull final UserHandle user) {
1542 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1543 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001544
1545 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001546 * As above but with a UID.
1547 * @see CompatChanges#isChangeEnabled(long, int)
1548 */
1549 public boolean isChangeEnabled(final long changeId, final int uid) {
1550 return CompatChanges.isChangeEnabled(changeId, uid);
1551 }
1552
1553 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001554 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1555 *
1556 * @param ranges target uid ranges
1557 * @param exemptUids uids to skip close socket
1558 */
1559 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1560 @NonNull final Set<Integer> exemptUids)
1561 throws SocketException, InterruptedIOException, ErrnoException {
1562 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1563 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001564
1565 /**
1566 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1567 *
1568 * @param ownerUids target uids to close sockets
1569 */
1570 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1571 throws SocketException, InterruptedIOException, ErrnoException {
1572 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1573 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001574
1575 /**
1576 * Schedule the evaluation timeout.
1577 *
1578 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1579 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1580 * of these events happen, this time will run out, after which the network is considered
1581 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1582 * on this network and considers it won't provide connectivity. In particular, that means
1583 * it's when the system prefers it to cell if it's wifi and configuration says it should
1584 * prefer bad wifi to cell.
1585 */
1586 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1587 @NonNull final Network network, final long delayMs) {
1588 handler.sendMessageDelayed(
1589 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1590 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001591 }
1592
junyulaie7c7d2a2021-01-26 15:29:15 +08001593 public ConnectivityService(Context context) {
1594 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001595 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1596 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001597 }
1598
1599 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001600 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1601 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001602 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001603
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001604 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001605 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001606 mSystemProperties = mDeps.getSystemProperties();
1607 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001608 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001609 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001610 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1611 // Pass limit - 1 to maintain backward compatibility.
1612 // TODO: Remove the workaround.
1613 mNetworkRequestCounter =
1614 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1615 mSystemNetworkRequestCounter =
1616 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001617
Hugo Benichi208c0102016-07-28 17:53:06 +09001618 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001619 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1620 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001621 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001622 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001623 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001624 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1625 mDefaultNetworkRequests.add(mDefaultRequest);
1626 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001627
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001628 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001629 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001630
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001631 // The default WiFi request is a background request so that apps using WiFi are
1632 // migrated to a better network (typically ethernet) when one comes up, instead
1633 // of staying on WiFi forever.
1634 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1635 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1636
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001637 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1638 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1639 NetworkRequest.Type.BACKGROUND_REQUEST);
1640
Chalard Jean0702f982021-09-16 21:50:07 +09001641 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1642 // TODO: Consider making the timer customizable.
1643 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1644 mCellularRadioTimesharingCapable =
1645 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1646
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001647 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1648 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1649
1650 if (SdkLevel.isAtLeastU()) {
1651 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1652 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1653 final int defaultUMarkMask = 0x80000000; // u32
1654
1655 if ((mark == 0) || (mask == 0)) {
1656 // simply treat unset/disabled as the default U value
1657 mark = defaultUMarkMask;
1658 mask = defaultUMarkMask;
1659 }
1660 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1661 // invalid device overlay settings
1662 throw new IllegalArgumentException(
1663 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1664 }
1665 }
1666
1667 mWakeUpMark = mark;
1668 mWakeUpMask = mask;
1669
Paul Hu51f816b2022-08-11 14:43:47 +00001670 mNetd = netd;
1671 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001672 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001673 mPermissionMonitor =
1674 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001675 mHandlerThread.start();
1676 mHandler = new InternalHandler(mHandlerThread.getLooper());
1677 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001678 mConnectivityDiagnosticsHandler =
1679 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001680
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001681 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001682 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001683
junyulaie7c7d2a2021-01-26 15:29:15 +08001684 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001685 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001686 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001687 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001688
Wink Saville32506bc2013-06-29 21:10:57 -07001689 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001690 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001691 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001692 mCarrierPrivilegeAuthenticator =
1693 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001694
Sudheer Shanka9967d462021-03-18 19:09:25 +00001695 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001696 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1697 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001698 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001699
1700 final PowerManager powerManager = (PowerManager) context.getSystemService(
1701 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001702 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001703 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001704
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001705 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1706 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001707 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001708 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001709 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001710 mProtectedNetworks.add(p);
1711 } else {
1712 if (DBG) loge("Ignoring protectedNetwork " + p);
1713 }
1714 }
1715
soma, kawata29444ae2019-05-23 09:30:40 +09001716 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1717
James Mattis02220e22021-03-13 19:27:21 -08001718 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001719 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001720 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001721 final IntentFilter userIntentFilter = new IntentFilter();
1722 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1723 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1724 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1725 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001726
James Mattis02220e22021-03-13 19:27:21 -08001727 // Listen to package add/removes for netd
1728 final IntentFilter packageIntentFilter = new IntentFilter();
1729 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1730 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1731 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1732 packageIntentFilter.addDataScheme("package");
1733 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001734 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001735
Motomu Utsumi1e51a642023-07-18 15:11:41 +09001736 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001737
Chalard Jean46bfbf02022-02-02 00:56:25 +09001738 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001739 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001740 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001741 } catch (RemoteException | ServiceSpecificException e) {
1742 loge("Error registering event listener :" + e);
1743 }
1744
Erik Kline05f2b402015-04-30 12:58:40 +09001745 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1746 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001747
chiachangwang7c17c282023-02-02 05:58:59 +00001748 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001749 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001750 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001751
1752 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001753 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001754 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1755 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001756 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001757 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1758 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001759
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001760 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001761 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001762 mNetworkRanker =
1763 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1764
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001765 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001766
Chiachang Wangc1215d32020-10-20 15:38:58 +08001767 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001768 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001769
Chalard Jean28018572020-12-21 18:36:52 +09001770 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1771 // request that doesn't allow fallback to the default network. It should never be visible
1772 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1773 // arguments like the handler or the DnsResolver.
1774 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001775 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001776 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001777 new NetworkInfo(TYPE_NONE, 0, "", ""),
Anton Kulakov6eea22b2023-10-13 15:04:01 +00001778 new LinkProperties(), new NetworkCapabilities(),
Chalard Jean28018572020-12-21 18:36:52 +09001779 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001780 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1781 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001782
1783 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001784 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1785 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1786 // Even if it could, running on S would at least require mocking out the BPF map,
1787 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1788 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001789 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001790 mDscpPolicyTracker = new DscpPolicyTracker();
1791 }
Tyler Wear72388212021-09-09 14:49:02 -07001792 } catch (ErrnoException e) {
1793 loge("Unable to create DscpPolicyTracker");
1794 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001795
1796 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1797 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001798
Chalard Jeandf29a852023-05-29 17:02:43 +09001799 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001800 mCdmps = new CompanionDeviceManagerProxyService(context);
1801 } else {
1802 mCdmps = null;
1803 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001804
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001805 mDestroyFrozenSockets = mDeps.isAtLeastU()
1806 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
1807 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1808 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
1809 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001810 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1811 new UidFrozenStateChangedCallback() {
1812 @Override
1813 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1814 if (uids.length != frozenStates.length) {
1815 Log.wtf(TAG, "uids has length " + uids.length
1816 + " but frozenStates has length " + frozenStates.length);
1817 return;
1818 }
1819
1820 final UidFrozenStateChangedArgs args =
1821 new UidFrozenStateChangedArgs(uids, frozenStates);
1822
1823 mHandler.sendMessage(
1824 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1825 }
1826 };
1827
1828 final ActivityManager activityManager =
1829 mContext.getSystemService(ActivityManager.class);
1830 activityManager.registerUidFrozenStateChangedCallback(
1831 (Runnable r) -> r.run(), frozenStateChangedCallback);
1832 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001833 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001834
Xiao Ma0a171c02022-01-23 16:14:51 +00001835 /**
1836 * Check whether or not the device supports Ethernet transport.
1837 */
1838 public static boolean deviceSupportsEthernet(final Context context) {
1839 final PackageManager pm = context.getPackageManager();
1840 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1841 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1842 }
1843
Chalard Jean46adcf32018-04-18 20:18:38 +09001844 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001845 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1846 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001847 }
1848
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001849 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1850 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001851 final NetworkCapabilities netCap = new NetworkCapabilities();
1852 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001853 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001854 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001855 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001856 return netCap;
1857 }
1858
James Mattis45d81842021-01-10 14:24:24 -08001859 private NetworkRequest createDefaultRequest() {
1860 return createDefaultInternetRequestForTransport(
1861 TYPE_NONE, NetworkRequest.Type.REQUEST);
1862 }
1863
lucaslin3ba7cc22022-12-19 02:35:33 +00001864 private NetworkRequest createVpnRequest() {
1865 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1866 .withoutDefaultCapabilities()
1867 .addTransportType(TRANSPORT_VPN)
1868 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1869 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1870 .build();
1871 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1872 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1873 }
1874
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001875 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001876 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001877 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001878 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001879 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001880 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001881 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001882 netCap.addTransportType(transportType);
1883 }
James Mattis45d81842021-01-10 14:24:24 -08001884 return createNetworkRequest(type, netCap);
1885 }
1886
1887 private NetworkRequest createNetworkRequest(
1888 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001889 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001890 }
1891
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001892 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1893 NetworkRequest.Type type) {
1894 final NetworkCapabilities netCap = new NetworkCapabilities();
1895 netCap.clearAll();
1896 netCap.addCapability(capability);
1897 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1898 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1899 }
1900
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001901 // Used only for testing.
1902 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001903 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001904 // changing ContentResolver to make registerContentObserver non-final).
1905 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1906 // by subclassing SettingsObserver.
1907 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001908 void updateAlwaysOnNetworks() {
1909 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001910 }
1911
Erik Kline9a62f012018-03-21 07:18:33 -07001912 // See FakeSettingsProvider comment above.
1913 @VisibleForTesting
1914 void updatePrivateDnsSettings() {
1915 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1916 }
1917
paulhu51f77dc2021-06-07 02:34:20 +00001918 @VisibleForTesting
1919 void updateMobileDataPreferredUids() {
1920 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1921 }
1922
Patrick Rohr2857ac42022-01-21 14:58:16 +01001923 @VisibleForTesting
1924 void updateIngressRateLimit() {
1925 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1926 }
1927
Aaron Huang40b52442021-06-08 04:34:24 +08001928 @VisibleForTesting
1929 void simulateUpdateProxyInfo(@Nullable final Network network,
1930 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001931 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08001932 new Pair<>(network, proxyInfo)).sendToTarget();
1933 }
1934
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001935 private void handleAlwaysOnNetworkRequest(
1936 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001937 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001938 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001939 handleAlwaysOnNetworkRequest(networkRequest, enable);
1940 }
1941
1942 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001943 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001944 if (enable == isEnabled) {
1945 return; // Nothing to do.
1946 }
1947
1948 if (enable) {
1949 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001950 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001951 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001952 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001953 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001954 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1955 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001956 }
1957 }
1958
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001959 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001960 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1961 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1962 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1963 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001964 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1965 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001966 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001967 }
1968
paulhu51f77dc2021-06-07 02:34:20 +00001969 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001970 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001971 private void registerSettingsCallbacks() {
1972 // Watch for global HTTP proxy changes.
1973 mSettingsObserver.observe(
1974 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1975 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1976
Chalard Jean46bfbf02022-02-02 00:56:25 +09001977 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001978 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001979 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001980 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1981
Chalard Jean46bfbf02022-02-02 00:56:25 +09001982 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001983 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001984 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001985 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001986
1987 // Watch for mobile data preferred uids changes.
1988 mSettingsObserver.observe(
1989 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1990 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001991
1992 // Watch for ingress rate limit changes.
1993 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01001994 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01001995 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1996 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001997 }
1998
Erik Kline31b4a9e2018-01-11 21:07:29 +09001999 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002000 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2001 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002002 }
2003 }
2004
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002005 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002006 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2007 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002008 return mNextNetworkRequestId++;
2009 }
2010
junyulai74f9a8b2018-06-13 15:00:37 +08002011 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002012 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002013 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002014 if (network == null) {
2015 return null;
2016 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002017 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002018 }
2019
2020 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002021 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002022 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002023 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002024 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002025
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002026 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002027 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002028 private NetworkAgentInfo getVpnForUid(int uid) {
2029 synchronized (mNetworkForNetId) {
2030 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2031 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002032 if (nai.isVPN() && nai.everConnected()
2033 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002034 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002035 }
2036 }
2037 }
2038 return null;
2039 }
2040
Chalard Jean46bfbf02022-02-02 00:56:25 +09002041 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002042 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002043 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002044 final NetworkAgentInfo nai = getVpnForUid(uid);
2045 if (nai != null) return nai.declaredUnderlyingNetworks;
2046 return null;
2047 }
2048
Lorenzo Colittia7574052021-01-19 01:33:05 +09002049 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002050 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002051
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002052 final Network[] networks = getVpnUnderlyingNetworks(uid);
2053 if (networks != null) {
2054 // getUnderlyingNetworks() returns:
2055 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2056 // empty array => the VPN explicitly said "no default network".
2057 // non-empty array => the VPN specified one or more default networks; we use the
2058 // first one.
2059 if (networks.length > 0) {
2060 nai = getNetworkAgentInfoForNetwork(networks[0]);
2061 } else {
2062 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002063 }
2064 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002065 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002066 }
2067
2068 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002069 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002070 */
paulhu7aeba372020-12-30 00:42:19 +08002071 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2072 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002073 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002074 if (ignoreBlocked) {
2075 return false;
2076 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002077 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002078 final long ident = Binder.clearCallingIdentity();
2079 try {
2080 final boolean metered = nc == null ? true : nc.isMetered();
2081 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2082 } finally {
2083 Binder.restoreCallingIdentity(ident);
2084 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002085 }
2086
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002087 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002088 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2089 return;
2090 }
Hugo Benichi47011212017-03-30 10:46:05 +09002091 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002092 synchronized (mBlockedAppUids) {
2093 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002094 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002095 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002096 blocked = false;
2097 } else {
2098 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002099 }
2100 }
Hugo Benichi47011212017-03-30 10:46:05 +09002101 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2102 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2103 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002104 }
2105
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002106 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002107 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2108 return;
2109 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002110 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002111 final int requestId = nri.getActiveRequest() != null
2112 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002113 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002114 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002115 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002116 }
2117
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002118 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002119 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002120 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002121 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002122 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002123 @NonNull
2124 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2125 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002126 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2127 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2128 // but only exists if an app asks about them or requests them. Ensure the requesting app
2129 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002130 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002131 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2132 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2133 null /* extraInfo */);
2134 }
2135 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002136 return filtered;
2137 }
2138
2139 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2140 boolean ignoreBlocked) {
2141 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2142 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002143 }
2144
2145 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002146 * Return NetworkInfo for the active (i.e., connected) network interface.
2147 * It is assumed that at most one network is active at a time. If more
2148 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002149 * @return the info for the active network, or {@code null} if none is
2150 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002151 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002152 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002153 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002154 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002155 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002156 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002157 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2158 if (nai == null) return null;
2159 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2160 maybeLogBlockedNetworkInfo(networkInfo, uid);
2161 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002162 }
2163
Paul Jensen1f567382015-02-13 14:18:39 -05002164 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002165 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002166 public Network getActiveNetwork() {
2167 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002168 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002169 }
2170
2171 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002172 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002173 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002174 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002175 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002176 }
2177
Chalard Jean46bfbf02022-02-02 00:56:25 +09002178 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002179 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002180 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2181 if (vpnNai != null) {
2182 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2183 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2184 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002185 }
Paul Jensen1f567382015-02-13 14:18:39 -05002186 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002187
James Mattis2516da32021-01-31 17:06:19 -08002188 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002189 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2190 ignoreBlocked)) {
2191 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002192 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002193 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002194 }
2195
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002196 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002197 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002198 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002199 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002200 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2201 if (nai == null) return null;
2202 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002203 }
2204
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002205 /** Returns a NetworkInfo object for a network that doesn't exist. */
2206 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2207 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2208 getNetworkTypeName(networkType), "" /* subtypeName */);
2209 info.setIsAvailable(true);
2210 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2211 // background data is restricted.
2212 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2213 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2214 ? DetailedState.BLOCKED
2215 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002216 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2217 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002218 return info;
2219 }
2220
Lorenzo Colittia7574052021-01-19 01:33:05 +09002221 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002222 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2223 return null;
2224 }
2225 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002226 if (nai == null) {
2227 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002228 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002229 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2230 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002231 }
2232
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002233 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002234 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002235 public NetworkInfo getNetworkInfo(int networkType) {
2236 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002237 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002238 if (getVpnUnderlyingNetworks(uid) != null) {
2239 // A VPN is active, so we may need to return one of its underlying networks. This
2240 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002241 // getNetworkAgentInfoForUid.
2242 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2243 if (nai == null) return null;
2244 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2245 if (networkInfo.getType() == networkType) {
2246 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002247 }
2248 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002249 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002250 }
2251
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002252 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002253 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002254 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002255 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002256 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002257 if (nai == null) return null;
2258 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002259 }
2260
2261 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002262 public NetworkInfo[] getAllNetworkInfo() {
2263 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002264 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002265 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2266 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002267 NetworkInfo info = getNetworkInfo(networkType);
2268 if (info != null) {
2269 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002270 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002271 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002272 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002273 }
2274
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002275 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002276 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002277 public Network getNetworkForType(int networkType) {
2278 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002279 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2280 return null;
2281 }
2282 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2283 if (nai == null) {
2284 return null;
2285 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002286 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002287 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2288 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002289 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002290 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002291 }
2292
2293 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002294 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002295 public Network[] getAllNetworks() {
2296 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002297 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002298 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002299 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002300 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002301 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002302 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002303 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002304 }
2305
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002306 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002307 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002308 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002309 // The basic principle is: if an app's traffic could possibly go over a
2310 // network, without the app doing anything multinetwork-specific,
2311 // (hence, by "default"), then include that network's capabilities in
2312 // the array.
2313 //
2314 // In the normal case, app traffic only goes over the system's default
2315 // network connection, so that's the only network returned.
2316 //
2317 // With a VPN in force, some app traffic may go into the VPN, and thus
2318 // over whatever underlying networks the VPN specifies, while other app
2319 // traffic may go over the system default network (e.g.: a split-tunnel
2320 // VPN, or an app disallowed by the VPN), so the set of networks
2321 // returned includes the VPN's underlying networks and the system
2322 // default.
2323 enforceAccessPermission();
2324
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002325 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002326
James Mattis2516da32021-01-31 17:06:19 -08002327 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2328 if (!nri.isBeingSatisfied()) {
2329 continue;
2330 }
2331 final NetworkAgentInfo nai = nri.getSatisfier();
2332 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2333 if (null != nc
2334 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2335 && !result.containsKey(nai.network)) {
2336 result.put(
2337 nai.network,
2338 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002339 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002340 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2341 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002342 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002343 }
2344
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002345 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002346 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002347 if (null != networks) {
2348 for (final Network network : networks) {
2349 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2350 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002351 result.put(
2352 network,
2353 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002354 nc,
2355 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002356 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002357 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002358 }
2359 }
2360 }
2361
2362 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2363 out = result.values().toArray(out);
2364 return out;
2365 }
2366
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002367 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2368 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2369 // can call sampleConnectivityState and make the checks on it.
2370 @NonNull
2371 private StatsEvent sampleConnectivityStateToStatsEvent() {
2372 final ConnectivityStateSample sample = sampleConnectivityState();
2373 return ConnectivityStatsLog.buildStatsEvent(
2374 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2375 sample.getNetworkCountPerTransports().toByteArray(),
2376 sample.getConnectionDurationPerTransports().toByteArray(),
2377 sample.getNetworkRequestCount().toByteArray(),
2378 sample.getNetworks().toByteArray());
2379 }
2380
2381 /**
2382 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2383 *
2384 * This is used for metrics. These snapshots will be sampled and constitute a base for
2385 * statistics about connectivity state of devices.
2386 */
2387 @VisibleForTesting
2388 @NonNull
2389 public ConnectivityStateSample sampleConnectivityState() {
2390 ensureRunningOnConnectivityServiceThread();
2391 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2392 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2393 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2394 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2395 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2396 return builder.build();
2397 }
2398
2399 private static NetworkCountPerTransports sampleNetworkCount(
2400 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2401 final SparseIntArray countPerTransports = new SparseIntArray();
2402 for (final NetworkAgentInfo nai : nais) {
2403 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2404 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2405 }
2406 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2407 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2408 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2409 c.setTransportTypes(countPerTransports.keyAt(i));
2410 c.setNetworkCount(countPerTransports.valueAt(i));
2411 builder.addNetworkCountForTransports(c);
2412 }
2413 return builder.build();
2414 }
2415
2416 private static ConnectionDurationPerTransports sampleConnectionDuration(
2417 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2418 final ConnectionDurationPerTransports.Builder builder =
2419 ConnectionDurationPerTransports.newBuilder();
2420 for (final NetworkAgentInfo nai : nais) {
2421 final ConnectionDurationForTransports.Builder c =
2422 ConnectionDurationForTransports.newBuilder();
2423 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2424 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2425 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2426 // Add millisPerSecond/2 to round up or down to the nearest value
2427 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2428 builder.addConnectionDurationForTransports(c);
2429 }
2430 return builder.build();
2431 }
2432
2433 private static NetworkRequestCount sampleNetworkRequestCount(
2434 @NonNull final Collection<NetworkRequestInfo> nris) {
2435 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2436 final SparseIntArray countPerType = new SparseIntArray();
2437 for (final NetworkRequestInfo nri : nris) {
2438 final int type;
2439 if (Process.SYSTEM_UID == nri.mAsUid) {
2440 // The request is filed "as" the system, so it's the system on its own behalf.
2441 type = RequestType.RT_SYSTEM.getNumber();
2442 } else if (Process.SYSTEM_UID == nri.mUid) {
2443 // The request is filed by the system as some other app, so it's the system on
2444 // behalf of an app.
2445 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2446 } else {
2447 // Not the system, so it's an app requesting on its own behalf.
2448 type = RequestType.RT_APP.getNumber();
2449 }
2450 countPerType.put(type, countPerType.get(type, 0));
2451 }
2452 for (int i = countPerType.size() - 1; i >= 0; --i) {
2453 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2454 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2455 r.setRequestCount(countPerType.valueAt(i));
2456 builder.addRequestCountForType(r);
2457 }
2458 return builder.build();
2459 }
2460
2461 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2462 final NetworkList.Builder builder = NetworkList.newBuilder();
2463 for (final NetworkAgentInfo nai : nais) {
2464 final NetworkCapabilities nc = nai.networkCapabilities;
2465 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2466 d.setTransportTypes((int) nc.getTransportTypesInternal());
2467 final MeteredState meteredState;
2468 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2469 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2470 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2471 meteredState = MeteredState.METERED_NO;
2472 } else {
2473 meteredState = MeteredState.METERED_YES;
2474 }
2475 d.setMeteredState(meteredState);
2476 final ValidatedState validatedState;
2477 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2478 validatedState = ValidatedState.VS_PORTAL;
2479 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2480 validatedState = ValidatedState.VS_PARTIAL;
2481 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2482 validatedState = ValidatedState.VS_VALID;
2483 } else {
2484 validatedState = ValidatedState.VS_INVALID;
2485 }
2486 d.setValidatedState(validatedState);
2487 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2488 d.setCapabilities(nc.getCapabilitiesInternal());
2489 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2490 builder.addNetworkDescription(d);
2491 }
2492 return builder.build();
2493 }
2494
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002495 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002496 public boolean isNetworkSupported(int networkType) {
2497 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002498 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002499 }
2500
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002501 /**
2502 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002503 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002504 * @return the ip properties for the active network, or {@code null} if
2505 * none is active
2506 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002507 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002508 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002509 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002510 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002511 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2512 if (nai == null) return null;
2513 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002514 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002515 }
2516
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002517 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002518 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002519 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002520 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002521 final LinkProperties lp = getLinkProperties(nai);
2522 if (lp == null) return null;
2523 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002524 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002525 }
2526
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002527 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002528 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002529 public LinkProperties getLinkProperties(Network network) {
2530 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002531 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2532 if (lp == null) return null;
2533 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002534 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002535 }
2536
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002537 @Nullable
2538 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002539 if (nai == null) {
2540 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002541 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002542 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002543 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002544 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002545 }
2546
lucaslinc582d502022-01-27 09:07:00 +08002547 @Override
2548 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002549 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002550 @NonNull String packageName, @Nullable String callingAttributionTag) {
2551 Objects.requireNonNull(packageName);
2552 Objects.requireNonNull(lp);
2553 enforceNetworkStackOrSettingsPermission();
2554 if (!checkAccessPermission(-1 /* pid */, uid)) {
2555 return null;
2556 }
2557 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2558 }
2559
Qingxi Lib2748102020-01-08 12:51:49 -08002560 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2561 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2562 }
2563
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002564 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002565 if (nai == null) return null;
2566 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002567 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002568 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002569 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002570 }
2571
2572 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002573 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2574 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002575 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002576 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002577 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002578 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002579 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002580 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002581 }
2582
lucaslinc582d502022-01-27 09:07:00 +08002583 @Override
lucaslind2b06132022-03-02 10:56:57 +08002584 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2585 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2586 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002587 Objects.requireNonNull(nc);
2588 Objects.requireNonNull(packageName);
2589 enforceNetworkStackOrSettingsPermission();
2590 if (!checkAccessPermission(-1 /* pid */, uid)) {
2591 return null;
2592 }
2593 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2594 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2595 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2596 callingAttributionTag);
2597 }
2598
lucaslin69e1aa92022-03-22 18:15:09 +08002599 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2600 if (nc.getUnderlyingNetworks() != null
2601 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2602 nc.setUnderlyingNetworks(null);
2603 }
2604 }
2605
Qingxi Libb8da982020-01-17 17:54:27 -08002606 @VisibleForTesting
2607 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002608 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002609 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2610 // this would be expensive (one more permission check every time any NC callback is
2611 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2612 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2613 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002614 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002615 if (!checkSettingsPermission(callerPid, callerUid)) {
2616 newNc.setUids(null);
2617 newNc.setSSID(null);
2618 }
Etan Cohen107ae952018-12-30 17:59:59 -08002619 if (newNc.getNetworkSpecifier() != null) {
2620 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2621 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002622 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2623 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002624 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2625 newNc.setAdministratorUids(new int[0]);
2626 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002627 if (!checkAnyPermissionOf(mContext,
Benedict Wong53de25f2021-03-24 14:01:51 -07002628 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002629 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002630 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002631 }
lucaslin69e1aa92022-03-22 18:15:09 +08002632 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002633
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002634 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002635 }
2636
Roshan Pius98f59ec2021-02-23 08:47:39 -08002637 /**
2638 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002639 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002640 * NetworkCapabilities.
2641 * Note: This wrapper does not support any sort of invalidation and thus must not be
2642 * persistent or long-lived. It may only be used for the time necessary to
2643 * compute the redactions required by one particular NetworkCallback or
2644 * synchronous call.
2645 */
2646 private class RedactionPermissionChecker {
2647 private final int mCallingPid;
2648 private final int mCallingUid;
2649 @NonNull private final String mCallingPackageName;
2650 @Nullable private final String mCallingAttributionTag;
2651
2652 private Boolean mHasLocationPermission = null;
2653 private Boolean mHasLocalMacAddressPermission = null;
2654 private Boolean mHasSettingsPermission = null;
2655
2656 RedactionPermissionChecker(int callingPid, int callingUid,
2657 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2658 mCallingPid = callingPid;
2659 mCallingUid = callingUid;
2660 mCallingPackageName = callingPackageName;
2661 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002662 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002663
2664 private boolean hasLocationPermissionInternal() {
2665 final long token = Binder.clearCallingIdentity();
2666 try {
2667 return mLocationPermissionChecker.checkLocationPermission(
2668 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2669 null /* message */);
2670 } finally {
2671 Binder.restoreCallingIdentity(token);
2672 }
2673 }
2674
2675 /**
2676 * Returns whether the app holds location permission or not (might return cached result
2677 * if the permission was already checked before).
2678 */
2679 public boolean hasLocationPermission() {
2680 if (mHasLocationPermission == null) {
2681 // If there is no cached result, perform the check now.
2682 mHasLocationPermission = hasLocationPermissionInternal();
2683 }
2684 return mHasLocationPermission;
2685 }
2686
2687 /**
2688 * Returns whether the app holds local mac address permission or not (might return cached
2689 * result if the permission was already checked before).
2690 */
2691 public boolean hasLocalMacAddressPermission() {
2692 if (mHasLocalMacAddressPermission == null) {
2693 // If there is no cached result, perform the check now.
2694 mHasLocalMacAddressPermission =
2695 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2696 }
2697 return mHasLocalMacAddressPermission;
2698 }
2699
2700 /**
2701 * Returns whether the app holds settings permission or not (might return cached
2702 * result if the permission was already checked before).
2703 */
2704 public boolean hasSettingsPermission() {
2705 if (mHasSettingsPermission == null) {
2706 // If there is no cached result, perform the check now.
2707 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2708 }
2709 return mHasSettingsPermission;
2710 }
2711 }
2712
2713 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2714 @NetworkCapabilities.NetCapability long redaction) {
2715 return (redactions & redaction) != 0;
2716 }
2717
2718 /**
2719 * Use the provided |applicableRedactions| to check the receiving app's
2720 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2721 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2722 * before being sent to the corresponding app.
2723 */
2724 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2725 @NetworkCapabilities.RedactionType long applicableRedactions,
2726 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2727 boolean includeLocationSensitiveInfo) {
2728 long redactions = applicableRedactions;
2729 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2730 if (includeLocationSensitiveInfo
2731 && redactionPermissionChecker.hasLocationPermission()) {
2732 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2733 }
2734 }
2735 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2736 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2737 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2738 }
2739 }
2740 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2741 if (redactionPermissionChecker.hasSettingsPermission()) {
2742 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2743 }
2744 }
2745 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002746 }
2747
Qingxi Lib2748102020-01-08 12:51:49 -08002748 @VisibleForTesting
2749 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002750 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002751 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002752 int callingPid, int callingUid, @NonNull String callingPkgName,
2753 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002754 if (nc == null) {
2755 return null;
2756 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002757 // Avoid doing location permission check if the transport info has no location sensitive
2758 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002759 final RedactionPermissionChecker redactionPermissionChecker =
2760 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2761 callingAttributionTag);
2762 final long redactions = retrieveRequiredRedactions(
2763 nc.getApplicableRedactions(), redactionPermissionChecker,
2764 includeLocationSensitiveInfo);
2765 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002766 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002767 // TODO : calling UID is redacted because apps should generally not know what UID is
2768 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002769 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002770 newNc.setOwnerUid(INVALID_UID);
2771 return newNc;
2772 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002773 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2774 if (nc.hasTransport(TRANSPORT_VPN)) {
2775 // Owner UIDs already checked above. No need to re-check.
2776 return newNc;
2777 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002778 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2779 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002780 // compatibility for older apps.
2781 if (!includeLocationSensitiveInfo
2782 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002783 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002784 newNc.setOwnerUid(INVALID_UID);
2785 return newNc;
2786 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002787 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002788 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002789 newNc.setOwnerUid(INVALID_UID);
2790 }
Qingxi Lib2748102020-01-08 12:51:49 -08002791 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002792 }
2793
lucaslinc582d502022-01-27 09:07:00 +08002794 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002795 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2796 LinkProperties lp, int callerPid, int callerUid) {
2797 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002798 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2799 // this would be expensive (one more permission check every time any LP callback is
2800 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2801 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2802 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002803
2804 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2805 final boolean needsSanitization =
2806 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2807 if (!needsSanitization) {
2808 return new LinkProperties(lp);
2809 }
2810
2811 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002812 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002813 }
2814
2815 final LinkProperties newLp = new LinkProperties(lp);
2816 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2817 // object gets parceled.
2818 newLp.setCaptivePortalApiUrl(null);
2819 newLp.setCaptivePortalData(null);
2820 return newLp;
2821 }
2822
Roshan Pius08c94fb2020-01-16 12:17:17 -08002823 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2824 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002825 // There is no need to track the effective UID of the request here. If the caller
2826 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002827 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002828 // Unprivileged apps can only pass in null or their own UID.
2829 if (nc.getUids() == null) {
2830 // If the caller passes in null, the callback will also match networks that do not
2831 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2832 // In this case, redact everything in the request immediately. This ensures that the
2833 // app is not able to get any redacted information by filing an unredacted request
2834 // and observing whether the request matches something.
2835 if (nc.getNetworkSpecifier() != null) {
2836 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2837 }
2838 } else {
2839 nc.setSingleUid(callerUid);
2840 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002841 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002842 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002843 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002844
2845 // Clear owner UID; this can never come from an app.
2846 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002847 }
2848
Chalard Jean38354d12018-03-20 19:13:57 +09002849 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002850 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002851 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2852 }
2853 }
2854
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002855 @Override
2856 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2857 enforceAccessPermission();
2858 final int callerUid = Binder.getCallingUid();
2859 final long token = Binder.clearCallingIdentity();
2860 try {
2861 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2862 } finally {
2863 Binder.restoreCallingIdentity(token);
2864 }
2865 }
2866
junyulaiebd15162021-03-03 12:09:05 +08002867 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002868 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002869 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002870 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002871 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002872
Serik Beketayev05130302021-01-15 16:47:25 -08002873 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002874 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002875 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2876 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002877 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002878 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002879 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002880 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2881 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002882 }
2883 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002884 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002885 }
2886
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002887 @Override
junyulaiebd15162021-03-03 12:09:05 +08002888 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002889 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002890 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002891 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002892
2893 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2894 for (Network network : getAllNetworks()) {
2895 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09002896 final boolean includeNetwork = (nai != null) && nai.isCreated();
2897 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002898 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2899 // NetworkCapabilities, which may contain UIDs of apps to which the
2900 // network applies. Should the UIDs be cleared so as not to leak or
2901 // interfere ?
2902 result.add(nai.getNetworkStateSnapshot());
2903 }
2904 }
2905 return result;
2906 }
2907
2908 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002909 public boolean isActiveNetworkMetered() {
2910 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002911
Qingxi Lib2748102020-01-08 12:51:49 -08002912 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002913 if (caps != null) {
2914 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2915 } else {
2916 // Always return the most conservative value
2917 return true;
2918 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002919 }
2920
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002921 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002922 * Ensures that the system cannot call a particular method.
2923 */
2924 private boolean disallowedBecauseSystemCaller() {
2925 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002926 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2927 // for devices launched with Q and above. However, existing devices upgrading to Q and
2928 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002929 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002930 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002931 log("This method exists only for app backwards compatibility"
2932 + " and must not be called by system services.");
2933 return true;
2934 }
2935 return false;
2936 }
2937
paulhub2c28682021-08-18 18:35:54 +08002938 private int getAppUid(final String app, final UserHandle user) {
2939 final PackageManager pm =
2940 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2941 final long token = Binder.clearCallingIdentity();
2942 try {
2943 return pm.getPackageUid(app, 0 /* flags */);
2944 } catch (PackageManager.NameNotFoundException e) {
2945 return -1;
2946 } finally {
2947 Binder.restoreCallingIdentity(token);
2948 }
2949 }
2950
2951 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2952 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2953 if (getAppUid(packageName, user) != callingUid) {
2954 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2955 }
2956 }
2957
Lorenzo Colitti23862912018-09-28 11:31:55 +09002958 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002959 * Ensure that a network route exists to deliver traffic to the specified
2960 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002961 * @param networkType the type of the network over which traffic to the
2962 * specified host is to be routed
2963 * @param hostAddress the IP address of the host to which the route is
2964 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002965 * @return {@code true} on success, {@code false} on failure
2966 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002967 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002968 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2969 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002970 if (disallowedBecauseSystemCaller()) {
2971 return false;
2972 }
paulhub2c28682021-08-18 18:35:54 +08002973 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002974 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002975 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002976 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002977 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002978
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002979 InetAddress addr;
2980 try {
2981 addr = InetAddress.getByAddress(hostAddress);
2982 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002983 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002984 return false;
2985 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002986
The Android Open Source Project28527d22009-03-03 19:31:44 -08002987 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002988 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002989 return false;
2990 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002991
2992 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2993 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002994 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002995 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2996 } else {
2997 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2998 }
2999 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003000 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003001
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003002 DetailedState netState;
3003 synchronized (nai) {
3004 netState = nai.networkInfo.getDetailedState();
3005 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003006
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003007 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003008 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003009 log("requestRouteToHostAddress on down network "
3010 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003011 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003012 }
3013 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003014 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003015
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003016 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003017 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003018 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003019 LinkProperties lp;
3020 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003021 synchronized (nai) {
3022 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003023 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003024 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003025 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003026 if (DBG) {
3027 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3028 }
Wink Saville32506bc2013-06-29 21:10:57 -07003029 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003030 } finally {
3031 Binder.restoreCallingIdentity(token);
3032 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003033 }
3034
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003035 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003036 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003037 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003038 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003039 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003040 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003041 if (bestRoute.getGateway().equals(addr)) {
3042 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003043 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003044 } else {
3045 // if we will connect to this through another route, add a direct route
3046 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003047 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003048 }
3049 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003050 if (DBG) log("Adding legacy route " + bestRoute +
3051 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003052
3053 final String dst = bestRoute.getDestinationLinkAddress().toString();
3054 final String nextHop = bestRoute.hasGateway()
3055 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003056 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003057 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3058 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003059 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003060 return false;
3061 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003062 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003063 }
3064
paulhu7c0a2e62021-01-08 00:51:49 +08003065 class DnsResolverUnsolicitedEventCallback extends
3066 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003067 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003068 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003069 try {
3070 mHandler.sendMessage(mHandler.obtainMessage(
3071 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003072 new PrivateDnsValidationUpdate(event.netId,
3073 InetAddresses.parseNumericAddress(event.ipAddress),
3074 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003075 } catch (IllegalArgumentException e) {
3076 loge("Error parsing ip address in validation event");
3077 }
3078 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003079
3080 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003081 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3082 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003083 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3084 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3085 // event callback for certain nai. e.g. cellular. Register here to pass to
3086 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003087 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003088 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3089 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003090 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003091 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003092 }
3093 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003094
3095 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003096 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3097 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3098 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003099 }
dalyk1720e542018-03-05 12:42:22 -05003100
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003101 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003102 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003103 return this.VERSION;
3104 }
3105
3106 @Override
3107 public String getInterfaceHash() {
3108 return this.HASH;
3109 }
paulhu7c0a2e62021-01-08 00:51:49 +08003110 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003111
3112 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003113 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3114 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003115
paulhu7c0a2e62021-01-08 00:51:49 +08003116 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003117 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003118 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003119 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003120 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003121 }
3122 }
3123
Sudheer Shanka9967d462021-03-18 19:09:25 +00003124 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003125 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003126 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003127 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3128 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003129 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003130 };
3131
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003132 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003133 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003134 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003135 }
3136
Mark Fasheh7c999d82023-05-04 20:23:11 +00003137 static final class UidFrozenStateChangedArgs {
3138 final int[] mUids;
3139 final int[] mFrozenStates;
3140
3141 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3142 mUids = uids;
3143 mFrozenStates = frozenStates;
3144 }
3145 }
3146
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003147 /**
3148 * Check if the cell network is idle.
3149 * @return true if the cell network state is idle
3150 * false if the cell network state is active or unknown
3151 */
3152 private boolean isCellNetworkIdle() {
3153 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3154 if (defaultNai == null
3155 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3156 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3157 // cell network is not the default network, cell network state is unknown.
3158 // TODO(b/279380356): Track cell network state when the cell is not the default network
3159 return false;
3160 }
3161
3162 return !mNetworkActivityTracker.isDefaultNetworkActive();
3163 }
3164
Mark Fasheh7c999d82023-05-04 20:23:11 +00003165 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003166 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003167
3168 for (int i = 0; i < uids.length; i++) {
3169 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003170 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003171 } else {
3172 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003173 }
3174 }
3175
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003176 if (ownerUids.isEmpty()) {
3177 return;
3178 }
3179
3180 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3181 // Delay closing sockets to avoid waking the cell modem up.
3182 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3183 // than waking cell modem up.
3184 mPendingFrozenUids.addAll(ownerUids);
3185 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003186 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003187 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003188 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003189 loge("Exception in socket destroy: " + e);
3190 }
3191 }
3192 }
3193
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003194 private void closePendingFrozenSockets() {
3195 ensureRunningOnConnectivityServiceThread();
3196
3197 try {
3198 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3199 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3200 loge("Failed to close pending frozen app sockets: " + e);
3201 }
3202 mPendingFrozenUids.clear();
3203 }
3204
3205 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3206 mNetworkActivityTracker.handleReportNetworkActivity(params);
3207
3208 if (mDelayDestroyFrozenSockets
3209 && params.isActive
3210 && params.label == TRANSPORT_CELLULAR
3211 && !mPendingFrozenUids.isEmpty()) {
3212 closePendingFrozenSockets();
3213 }
3214 }
3215
3216 /**
3217 * If the cellular network is no longer the default network, close pending frozen sockets.
3218 *
3219 * @param newNetwork new default network
3220 * @param oldNetwork old default network
3221 */
3222 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3223 NetworkAgentInfo oldNetwork) {
3224 final boolean isOldNetworkCellular = oldNetwork != null
3225 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3226 final boolean isNewNetworkCellular = newNetwork != null
3227 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3228
3229 if (isOldNetworkCellular
3230 && !isNewNetworkCellular
3231 && !mPendingFrozenUids.isEmpty()) {
3232 closePendingFrozenSockets();
3233 }
3234 }
3235
3236 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3237 pw.println("CloseFrozenAppSockets:");
3238 pw.increaseIndent();
3239 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3240 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3241 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3242 pw.decreaseIndent();
3243 }
3244
Mark Fasheh7c999d82023-05-04 20:23:11 +00003245 @VisibleForTesting
3246 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003247 @VisibleForTesting
3248 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3249 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003250
Paul Jensen83f5d572014-08-29 09:54:01 -04003251 private void enforceInternetPermission() {
3252 mContext.enforceCallingOrSelfPermission(
3253 android.Manifest.permission.INTERNET,
3254 "ConnectivityService");
3255 }
3256
The Android Open Source Project28527d22009-03-03 19:31:44 -08003257 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003258 mContext.enforceCallingOrSelfPermission(
3259 android.Manifest.permission.ACCESS_NETWORK_STATE,
3260 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003261 }
3262
lucaslinc582d502022-01-27 09:07:00 +08003263 private boolean checkAccessPermission(int pid, int uid) {
3264 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3265 == PERMISSION_GRANTED;
3266 }
3267
paulhua6ee2122021-02-22 15:40:43 +08003268 /**
3269 * Performs a strict and comprehensive check of whether a calling package is allowed to
3270 * change the state of network, as the condition differs for pre-M, M+, and
3271 * privileged/preinstalled apps. The caller is expected to have either the
3272 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3273 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3274 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3275 * permission and cannot be revoked. See http://b/23597341
3276 *
3277 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3278 * of this app will be updated to the current time.
3279 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003280 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003281 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3282 == PackageManager.PERMISSION_GRANTED) {
3283 return;
3284 }
3285
3286 if (callingPkg == null) {
3287 throw new SecurityException("Calling package name is null.");
3288 }
3289
3290 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3291 final int uid = mDeps.getCallingUid();
3292 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3293 callingPkg, callingAttributionTag, null /* message */);
3294
3295 if (mode == AppOpsManager.MODE_ALLOWED) {
3296 return;
3297 }
3298
3299 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3300 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3301 return;
3302 }
3303
3304 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3305 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3306 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003307 }
3308
Charles He9369e612017-05-15 17:07:18 +01003309 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003310 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003311 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003312 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003313 }
3314
Quang Luong98858d62023-02-11 00:25:24 +00003315 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003316 enforceAnyPermissionOf(mContext,
3317 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003318 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003319 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3320 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3321 }
3322
paulhu8e96a752019-08-12 16:25:11 +08003323 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003324 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003325 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003326 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003327 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003328 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003329 }
3330
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003331 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003332 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003333 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003334 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003335 android.Manifest.permission.NETWORK_SETTINGS,
3336 android.Manifest.permission.NETWORK_FACTORY,
3337 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3338 }
3339
3340 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003341 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003342 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003343 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003344 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3345 android.Manifest.permission.NETWORK_FACTORY,
3346 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3347 }
3348
lucaslin69e1aa92022-03-22 18:15:09 +08003349 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3350 return PERMISSION_GRANTED == mContext.checkPermission(
3351 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3352 || PERMISSION_GRANTED == mContext.checkPermission(
3353 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3354 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003355 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003356 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003357 }
3358
Chalard Jean9a396cc2018-02-21 18:43:54 +09003359 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003360 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003361 android.Manifest.permission.NETWORK_SETTINGS,
3362 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003363 }
3364
3365 private boolean checkSettingsPermission(int pid, int uid) {
3366 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003367 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3368 || PERMISSION_GRANTED == mContext.checkPermission(
3369 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003370 }
3371
paulhu8e96a752019-08-12 16:25:11 +08003372 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003373 enforceNetworkStackPermissionOr(mContext,
3374 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003375 }
3376
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003377 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003378 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003379 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003380 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003381 }
3382
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003383 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003384 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003385 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3386 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003387 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003388 }
3389
James Mattis8378aec2021-01-26 14:05:36 -08003390 private void enforceOemNetworkPreferencesPermission() {
3391 mContext.enforceCallingOrSelfPermission(
3392 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3393 "ConnectivityService");
3394 }
3395
James Mattisfa270db2021-05-31 17:11:10 -07003396 private void enforceManageTestNetworksPermission() {
3397 mContext.enforceCallingOrSelfPermission(
3398 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3399 "ConnectivityService");
3400 }
3401
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003402 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003403 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003404 android.Manifest.permission.NETWORK_STACK,
3405 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003406 }
3407
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003408 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003409 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003410 android.Manifest.permission.NETWORK_STACK,
3411 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3412 }
3413
paulhu1a407652019-03-22 16:35:06 +08003414 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003415 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003416 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003417 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3418 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003419 }
3420
Paul Hu8fc2a552022-05-04 18:44:42 +08003421 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3422 boolean checkUidsAllowedList) {
3423 if (PermissionUtils.checkAnyPermissionOf(mContext,
3424 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3425 return true;
3426 }
3427
3428 // fallback to ConnectivityInternalPermission
3429 // TODO: Remove this fallback check after all apps have declared
3430 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3431 if (PermissionUtils.checkAnyPermissionOf(mContext,
3432 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3433 return true;
3434 }
3435
3436 // Check whether uid is in allowed on restricted networks list.
3437 if (checkUidsAllowedList
3438 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3439 return true;
3440 }
3441 return false;
3442 }
3443
3444 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3445 final int callingUid = mDeps.getCallingUid();
3446 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3447 throw new SecurityException("ConnectivityService: user " + callingUid
3448 + " has no permission to access restricted network.");
3449 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003450 }
3451
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003452 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003453 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003454 }
3455
Roshan Pius98f59ec2021-02-23 08:47:39 -08003456 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3457 return PERMISSION_GRANTED == mContext.checkPermission(
3458 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3459 }
3460
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003461 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003462 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003463 }
3464
3465 private void sendInetConditionBroadcast(NetworkInfo info) {
3466 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3467 }
3468
Wink Saville4f0de1e2011-08-04 15:01:58 -07003469 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003470 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003471 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003472 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003473 if (info.isFailover()) {
3474 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3475 info.setFailover(false);
3476 }
3477 if (info.getReason() != null) {
3478 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3479 }
3480 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003481 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3482 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003483 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003484 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003485 return intent;
3486 }
3487
3488 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3489 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3490 }
3491
Michael Groover73f69482023-01-27 11:01:25 -06003492 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3493 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003494 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3495 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003496 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003497 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003498 if (!mSystemReady
3499 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003500 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003501 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003502 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003503 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003504 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003505 }
3506
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003507 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003508 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003509 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003510 final NetworkInfo ni = intent.getParcelableExtra(
3511 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003512 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3513 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003514 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003515 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003516 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003517 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003518 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003519 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003520 } finally {
3521 Binder.restoreCallingIdentity(ident);
3522 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003523 }
3524 }
3525
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003526 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3527 NetworkInfo info) {
3528 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003529 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003530
3531 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3532 try {
3533 // This allows us to discard older broadcasts still waiting to be delivered
3534 // which have the same namespace and key.
3535 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3536 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3537 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003538 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003539 } catch (UnsupportedApiLevelException e) {
3540 Log.wtf(TAG, "Using unsupported API" + e);
3541 }
3542 }
3543
3544 @VisibleForTesting
3545 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3546 final StringBuilder sb = new StringBuilder();
3547 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3548 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3549 sb.append(info.getExtraInfo());
3550 return sb.toString();
3551 }
3552
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003553 /**
Aaron Huang96011892020-06-27 07:18:23 +08003554 * Called by SystemServer through ConnectivityManager when the system is ready.
3555 */
3556 @Override
3557 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003558 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003559 throw new SecurityException("Calling Uid is not system uid.");
3560 }
3561 systemReadyInternal();
3562 }
3563
3564 /**
3565 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003566 */
3567 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003568 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003569 // Load flags after PackageManager is ready to query module version
3570 mFlags.loadFlags(mDeps, mContext);
3571
Aaron Huang9a57acf2020-12-08 10:03:29 +08003572 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3573 // listening network request which is sent by MultipathPolicyTracker won't be added
3574 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3575 // be called after PermissionMonitor#startMonitoring().
3576 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3577 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3578 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003579 final ConditionVariable startMonitoringDone = new ConditionVariable();
3580 mHandler.post(() -> {
3581 mPermissionMonitor.startMonitoring();
3582 startMonitoringDone.open();
3583 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003584 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003585 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003586
Hugo Benichie5220992017-04-26 14:53:28 +09003587 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003588 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003589 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003590 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003591 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003592 }
3593 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003594
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003595 // Create network requests for always-on networks.
3596 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003597
3598 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003599 // Note that updating can be skipped here if the list is empty only because no uid
3600 // rules are applied before system ready. Normally, the empty uid list means to clear
3601 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003602 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3603 updateMobileDataPreferredUids();
3604 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003605
3606 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003607 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003608 mBpfNetMaps.setPullAtomCallback(mContext);
3609 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003610 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3611 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003612 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3613 // have permission problem. While CV#block() is unbounded in time and can in principle block
3614 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3615 // could have blocked forever too.
3616 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003617 }
3618
The Android Open Source Project28527d22009-03-03 19:31:44 -08003619 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003620 * Start listening for default data network activity state changes.
3621 */
3622 @Override
3623 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003624 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003625 }
3626
3627 /**
3628 * Stop listening for default data network activity state changes.
3629 */
3630 @Override
3631 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003632 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003633 }
3634
3635 /**
3636 * Check whether the default network radio is currently active.
3637 */
3638 @Override
3639 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003640 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003641 }
3642
3643 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003644 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003645 * and set it on it's iface.
3646 */
Junyu Lai970963e2022-10-25 15:46:47 +08003647 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003648 final String iface = newLp.getInterfaceName();
3649 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003650 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003651 // Silently ignore unset MTU value.
3652 return;
3653 }
Hansen Kurli04252032022-12-07 11:21:49 +00003654 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3655 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3656 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003657 return;
3658 }
Hansen Kurli04252032022-12-07 11:21:49 +00003659 // Cannot set MTU without interface name
3660 if (TextUtils.isEmpty(iface)) {
3661 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003662 return;
3663 }
sy.yun4aa73922013-09-02 05:24:09 +09003664
Hansen Kurli04252032022-12-07 11:21:49 +00003665 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3666 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003667 return;
3668 }
3669
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003670 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003671 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003672 mNetd.interfaceSetMtu(iface, mtu);
3673 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003674 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003675 }
3676 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003677
Chenbo Feng15416292018-11-08 17:36:21 -08003678 @VisibleForTesting
3679 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003680
Junyu Lai970963e2022-10-25 15:46:47 +08003681 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003682 String[] values = null;
3683 if (tcpBufferSizes != null) {
3684 values = tcpBufferSizes.split(",");
3685 }
3686
3687 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003688 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003689 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3690 values = tcpBufferSizes.split(",");
3691 }
3692
3693 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3694
3695 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003696 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003697
Chenbo Feng15416292018-11-08 17:36:21 -08003698 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3699 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3700 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003701 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003702 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003703 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003704 }
3705 }
3706
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003707 @Override
3708 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003709 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003710 NETWORK_RESTORE_DELAY_PROP_NAME);
3711 if(restoreDefaultNetworkDelayStr != null &&
3712 restoreDefaultNetworkDelayStr.length() != 0) {
3713 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003714 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003715 } catch (NumberFormatException e) {
3716 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003717 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003718 // if the system property isn't set, use the value for the apn type
3719 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3720
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003721 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3722 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003723 }
3724 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003725 }
3726
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003727 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003728 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003729 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003730 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003731 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003732 // Start gathering diagnostic information.
3733 netDiags.add(new NetworkDiagnostics(
3734 nai.network,
3735 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003736 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003737 DIAG_TIME_MS));
3738 }
3739
3740 for (NetworkDiagnostics netDiag : netDiags) {
3741 pw.println();
3742 netDiag.waitForMeasurements();
3743 netDiag.dump(pw);
3744 }
3745 }
3746
The Android Open Source Project28527d22009-03-03 19:31:44 -08003747 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003748 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3749 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003750 if (!checkDumpPermission(mContext, TAG, writer)) return;
3751
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003752 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003753 }
3754
lucaslin99473f62020-12-10 15:10:54 +08003755 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3756 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3757 != PackageManager.PERMISSION_GRANTED) {
3758 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003759 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003760 + " due to missing android.permission.DUMP permission");
3761 return false;
3762 } else {
3763 return true;
3764 }
3765 }
3766
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003767 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003768 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003769
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003770 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003771 dumpNetworkDiagnostics(pw);
3772 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003773 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003774 dumpNetworks(pw);
3775 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003776 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003777 dumpNetworkRequests(pw);
3778 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003779 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3780 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3781 dumpTrafficController(pw, fd, verbose);
3782 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003783 }
Erik Kline9647f382015-06-05 17:47:34 +09003784
Junyu Lai0da479b2022-04-20 15:06:29 +08003785 pw.println("NetworkProviders for:");
3786 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003787 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003788 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003789 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003790 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003791 pw.println();
3792
Chalard Jean5b409c72021-02-04 13:12:59 +09003793 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003794 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003795 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003796 pw.println("none");
3797 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003798 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003799 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003800 pw.println();
3801
James Mattis8b298a02021-06-01 22:34:04 -07003802 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003803 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003804 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003805 pw.decreaseIndent();
3806 pw.println();
3807
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003808 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003809 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003810 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003811 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003812 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003813
junyulaif2c67e42018-08-07 19:50:45 +08003814 pw.println("Status for known UIDs:");
3815 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003816 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003817 for (int i = 0; i < size; i++) {
3818 // Don't crash if the array is modified while dumping in bugreports.
3819 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003820 final int uid = mUidBlockedReasons.keyAt(i);
3821 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3822 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003823 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003824 } catch (ArrayIndexOutOfBoundsException e) {
3825 pw.println(" ArrayIndexOutOfBoundsException");
3826 } catch (ConcurrentModificationException e) {
3827 pw.println(" ConcurrentModificationException");
3828 }
3829 }
3830 pw.println();
3831 pw.decreaseIndent();
3832
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003833 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003834 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003835 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003836 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003837 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003838
Junyu Lai0da479b2022-04-20 15:06:29 +08003839 pw.println("Network Offers:");
3840 pw.increaseIndent();
3841 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3842 pw.println(offerInfo.offer);
3843 }
3844 pw.decreaseIndent();
3845 pw.println();
3846
Robert Greenwalt94e22142014-07-30 16:31:24 -07003847 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003848
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003849 pw.println();
markchien5e866652019-09-30 14:40:57 +08003850 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003851
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003852 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003853 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003854
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003855 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003856 dumpCloseFrozenAppSockets(pw);
3857
3858 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003859
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003860 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003861 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003862 pw.println("mNetworkRequestInfoLogs (most recent first):");
3863 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003864 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003865 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003866
3867 pw.println();
3868 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3869 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003870 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003871 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003872
3873 pw.println();
3874 pw.println("NetTransition WakeLock activity (most recent first):");
3875 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003876 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3877 pw.println("total releases: " + mTotalWakelockReleases);
3878 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3879 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3880 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3881 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3882 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3883 }
James Mattiscb1e0362021-04-06 17:07:42 -07003884 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003885
3886 pw.println();
3887 pw.println("bandwidth update requests (by uid):");
3888 pw.increaseIndent();
3889 synchronized (mBandwidthRequests) {
3890 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3891 pw.println("[" + mBandwidthRequests.keyAt(i)
3892 + "]: " + mBandwidthRequests.valueAt(i));
3893 }
3894 }
3895 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003896 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003897
James Mattiscb1e0362021-04-06 17:07:42 -07003898 pw.println();
3899 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3900 pw.increaseIndent();
3901 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003902 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003903 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003904
3905 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003906
3907 pw.println();
3908 pw.println("Permission Monitor:");
3909 pw.increaseIndent();
3910 mPermissionMonitor.dump(pw);
3911 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003912
3913 pw.println();
3914 pw.println("Legacy network activity:");
3915 pw.increaseIndent();
3916 mNetworkActivityTracker.dump(pw);
3917 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003918 }
3919
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003920 private void dumpNetworks(IndentingPrintWriter pw) {
3921 for (NetworkAgentInfo nai : networksSortedById()) {
3922 pw.println(nai.toString());
3923 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003924 pw.println("Nat464Xlat:");
3925 pw.increaseIndent();
3926 nai.dumpNat464Xlat(pw);
3927 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003928 pw.println(String.format(
3929 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3930 nai.numForegroundNetworkRequests(),
3931 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3932 nai.numBackgroundNetworkRequests(),
3933 nai.numNetworkRequests()));
3934 pw.increaseIndent();
3935 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3936 pw.println(nai.requestAt(i).toString());
3937 }
3938 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003939 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003940 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003941 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003942 pw.decreaseIndent();
3943 pw.decreaseIndent();
3944 }
3945 }
3946
James Mattis8b298a02021-06-01 22:34:04 -07003947 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3948 if (!mProfileNetworkPreferences.isEmpty()) {
3949 pw.println("Profile preferences:");
3950 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09003951 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07003952 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003953 }
James Mattis8b298a02021-06-01 22:34:04 -07003954 if (!mOemNetworkPreferences.isEmpty()) {
3955 pw.println("OEM preferences:");
3956 pw.increaseIndent();
3957 pw.println(mOemNetworkPreferences);
3958 pw.decreaseIndent();
3959 }
3960 if (!mMobileDataPreferredUids.isEmpty()) {
3961 pw.println("Mobile data preferred UIDs:");
3962 pw.increaseIndent();
3963 pw.println(mMobileDataPreferredUids);
3964 pw.decreaseIndent();
3965 }
James Mattis45d81842021-01-10 14:24:24 -08003966
James Mattis8b298a02021-06-01 22:34:04 -07003967 pw.println("Default requests:");
3968 pw.increaseIndent();
3969 dumpPerAppDefaultRequests(pw);
3970 pw.decreaseIndent();
3971 }
3972
3973 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003974 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3975 if (mDefaultRequest == defaultRequest) {
3976 continue;
3977 }
3978
James Mattis8b298a02021-06-01 22:34:04 -07003979 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3980 final String networkOutput;
3981 if (null == satisfier) {
3982 networkOutput = "null";
3983 } else if (mNoServiceNetwork.equals(satisfier)) {
3984 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003985 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003986 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003987 }
James Mattis8b298a02021-06-01 22:34:04 -07003988 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3989 ? "" : " asUid: " + defaultRequest.mAsUid;
3990 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3991 + defaultRequest.mPid + asUidString + "]";
3992 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3993 + " Preference order: " + defaultRequest.mPreferenceOrder
3994 + " Tracked UIDs: " + defaultRequest.getUids();
3995 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003996 }
3997 }
3998
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003999 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004000 NetworkRequestInfo[] infos = null;
4001 while (infos == null) {
4002 try {
4003 infos = requestsSortedById();
4004 } catch (ConcurrentModificationException e) {
4005 // mNetworkRequests should only be accessed from handler thread, except dump().
4006 // As dump() is never called in normal usage, it would be needlessly expensive
4007 // to lock the collection only for its benefit. Instead, retry getting the
4008 // requests if ConcurrentModificationException is thrown during dump().
4009 }
4010 }
4011 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004012 pw.println(nri.toString());
4013 }
4014 }
4015
Ken Chene6d511f2022-01-25 11:10:42 +08004016 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4017 boolean verbose) {
4018 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004019 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004020 } catch (ServiceSpecificException e) {
4021 pw.println(e.getMessage());
4022 } catch (IOException e) {
4023 loge("Dump BPF maps failed, " + e);
4024 }
4025 }
4026
Chalard Jean524f0b12021-10-25 21:11:56 +09004027 private void dumpAllRequestInfoLogsToLogcat() {
4028 try (PrintWriter logPw = new PrintWriter(new Writer() {
4029 @Override
4030 public void write(final char[] cbuf, final int off, final int len) {
4031 // This method is called with 0-length and 1-length arrays for empty strings
4032 // or strings containing only the DEL character.
4033 if (len <= 1) return;
4034 Log.e(TAG, new String(cbuf, off, len));
4035 }
4036 @Override public void flush() {}
4037 @Override public void close() {}
4038 })) {
4039 mNetworkRequestInfoLogs.dump(logPw);
4040 }
4041 }
4042
Hugo Benichia480ba52018-09-03 08:19:02 +09004043 /**
4044 * Return an array of all current NetworkAgentInfos sorted by network id.
4045 */
4046 private NetworkAgentInfo[] networksSortedById() {
4047 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004048 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004049 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004050 return networks;
4051 }
4052
4053 /**
4054 * Return an array of all current NetworkRequest sorted by request id.
4055 */
James Mattis258ea3c2020-11-15 15:04:40 -08004056 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004057 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004058 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004059 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004060 // Sort the array based off the NRI containing the min requestId in its requests.
4061 Arrays.sort(requests,
4062 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4063 Comparator.comparingInt(req -> req.requestId)).requestId
4064 )
4065 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004066 return requests;
4067 }
4068
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004069 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004070 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004071 if (officialNai != null && officialNai.equals(nai)) return true;
4072 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004073 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004074 " - " + nai);
4075 }
4076 return false;
4077 }
4078
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004079 private boolean isDisconnectRequest(Message msg) {
4080 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4081 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4082 return info.getState() == NetworkInfo.State.DISCONNECTED;
4083 }
4084
Robert Greenwalt2034b912009-08-12 16:08:25 -07004085 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004086 private class NetworkStateTrackerHandler extends Handler {
4087 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004088 super(looper);
4089 }
4090
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004091 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004092 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4093 final NetworkAgentInfo nai = arg.first;
4094 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004095 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004096 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004097 }
4098 return;
4099 }
4100
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004101 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004102 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004103 return;
4104 }
4105
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004106 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004107 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09004108 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
4109 final NetworkCapabilities sanitized =
4110 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004111 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004112 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004113 break;
4114 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004115 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004116 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004117 processLinkPropertiesFromAgent(nai, newLp);
4118 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004119 break;
4120 }
4121 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004122 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004123 updateNetworkInfo(nai, info);
4124 break;
4125 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004126 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004127 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004128 break;
4129 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004130 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004131 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004132 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004133 // Note that if the NAI had been connected, this would affect the
4134 // score, and therefore would require re-mixing the score and performing
4135 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004136 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004137 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4138 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004139 // Mark the network as temporarily accepting partial connectivity so that it
4140 // will be validated (and possibly become default) even if it only provides
4141 // partial internet access. Note that if user connects to partial connectivity
4142 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4143 // out of wifi coverage) and if the same wifi is available again, the device
4144 // will auto connect to this wifi even though the wifi has "no internet".
4145 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004146 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004147 break;
4148 }
junyulai011b1f12019-01-03 18:50:15 +08004149 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004150 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004151 break;
4152 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004153 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004154 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004155 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004156
4157 if (isLegacyLockdownNai(nai)
4158 && (underlying == null || underlying.size() != 1)) {
4159 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4160 + " must have exactly one underlying network: " + underlying);
4161 }
4162
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004163 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4164 nai.declaredUnderlyingNetworks = (underlying != null)
4165 ? underlying.toArray(new Network[0]) : null;
4166
4167 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4168 if (DBG) {
4169 log(nai.toShortString() + " changed underlying networks to "
4170 + Arrays.toString(nai.declaredUnderlyingNetworks));
4171 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004172 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004173 notifyIfacesChangedForNetworkStats();
4174 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004175 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004176 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004177 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4178 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4179 nai.teardownDelayMs = msg.arg1;
4180 } else {
4181 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4182 }
Chalard Jean550b5212021-03-05 23:07:53 +09004183 break;
4184 }
4185 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4186 nai.setLingerDuration((int) arg.second);
4187 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004188 }
Tyler Wear72388212021-09-09 14:49:02 -07004189 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4190 DscpPolicy policy = (DscpPolicy) arg.second;
4191 if (mDscpPolicyTracker != null) {
4192 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4193 }
4194 break;
4195 }
4196 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4197 if (mDscpPolicyTracker != null) {
4198 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4199 }
4200 break;
4201 }
4202 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4203 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004204 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004205 }
4206 break;
4207 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004208 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004209 if (!nai.everConnected()) {
4210 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4211 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004212 teardownUnneededNetwork(nai);
4213 break;
4214 }
4215
4216 if (nai.isDestroyed()) {
4217 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4218 + ", ignoring");
4219 break;
4220 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004221
4222 final int timeoutMs = (int) arg.second;
4223 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4224 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4225 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4226 }
4227
4228 // Marking a network awaiting replacement is used to ensure that any requests
4229 // satisfied by the network do not switch to another network until a
4230 // replacement is available or the wait for a replacement times out.
4231 // If the network is inactive (i.e., nascent or lingering), then there are no
4232 // such requests, and there is no point keeping it. Just tear it down.
4233 // Note that setLingerDuration(0) cannot be used to do this because the network
4234 // could be nascent.
4235 nai.clearInactivityState();
4236 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4237 Log.d(TAG, nai.toShortString()
4238 + " marked awaiting replacement is unneeded, tearing down instead");
4239 teardownUnneededNetwork(nai);
4240 break;
4241 }
4242
4243 Log.d(TAG, "Marking " + nai.toShortString()
4244 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4245 destroyNativeNetwork(nai);
4246
4247 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4248 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4249 // consider the fact that the network could already have disconnected or been
4250 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4251 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4252 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4253 mKeepaliveTracker.handleStopAllKeepalives(nai,
4254 SocketKeepalive.ERROR_INVALID_NETWORK);
4255
4256 nai.updateScoreForNetworkAgentUpdate();
4257 // This rematch is almost certainly not going to result in any changes, because
4258 // the destroyed flag is only just above the "current satisfier wins"
4259 // tie-breaker. But technically anything that affects scoring should rematch.
4260 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004261 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004262 break;
4263 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004264 }
4265 }
4266
4267 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004268 final int netId = msg.arg2;
4269 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004270 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004271 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004272 switch (msg.what) {
4273 default:
4274 return false;
lucasline117e2e2019-10-22 18:27:33 +08004275 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004276 if (nai == null) {
4277 break;
4278 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004279 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4280 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004281 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004282 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004283 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004284 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004285 if (probePrivateDnsCompleted) {
4286 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4287 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004288 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004289 }
4290 // Only show the notification when the private DNS is broken and the
4291 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004292 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004293 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4294 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004295 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004296 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4297 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4298 // private DNS is broken, it means this network is being reevaluated.
4299 // Either probing private DNS is not necessary any more or it hasn't been
4300 // done yet. In either case, the networkCapabilities should be updated to
4301 // reflect the new status.
4302 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004303 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004304 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004305 }
4306 break;
4307 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004308 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004309 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4310
Erik Kline31b4a9e2018-01-11 21:07:29 +09004311 if (nai == null) break;
4312
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004313 handleNetworkTested(nai, results.mTestResult,
4314 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004315 break;
4316 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004317 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004318 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004319 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004320 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004321 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004322 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004323 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4324 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004325 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004326 if (nai == null) {
4327 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4328 break;
4329 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004330 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004331 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004332 (PendingIntent) msg.obj,
4333 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004334 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004335 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004336 break;
4337 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004338 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004339 if (nai == null) break;
4340
Erik Kline9a62f012018-03-21 07:18:33 -07004341 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004342 break;
4343 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004344 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004345 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004346 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004347 break;
4348 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004349 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004350 return true;
4351 }
4352
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004353 private void handleNetworkTested(
4354 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004355 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4356 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004357 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004358
4359 // If there is any kind of working networking, then the NAI has been evaluated
4360 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4361 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004362 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004363 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004364 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4365 // any callback that receives onAvailable for that rematch receives an extra caps
4366 // callback. To prevent that, update the score in the agent so the updates below won't
4367 // see an update to both caps and score at the same time.
4368 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004369 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4370
he_won.hwang881307a2022-03-15 21:23:52 +09004371 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4372 // Assume the validation failure is due to a temporary failure after roaming
4373 // and ignore it. NetworkMonitor will continue to retry validation. If it
4374 // continues to fail after the block timeout expires, the network will be
4375 // marked unvalidated. If it succeeds, then validation state will not change.
4376 return;
4377 }
4378
Chalard Jean254bd162022-08-25 13:04:51 +09004379 final boolean wasValidated = nai.isValidated();
4380 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004381 final boolean wasPortal = nai.captivePortalDetected();
4382 nai.setPartialConnectivity(partial);
4383 nai.setCaptivePortalDetected(portal);
4384 nai.updateScoreForNetworkAgentUpdate();
4385 final boolean partialConnectivityChanged = (wasPartial != partial);
4386 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004387
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004388 if (DBG) {
4389 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4390 ? " with redirect to " + redirectUrl
4391 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004392 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004393 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004394 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004395 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004396 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004397 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004398 if (valid) {
4399 handleFreshlyValidatedNetwork(nai);
4400 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4401 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004402 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004403 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004404 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004405 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004406 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004407 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004408 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004409 NotificationType.PRIVATE_DNS_BROKEN);
4410 // If network becomes valid, the hasShownBroken should be reset for
4411 // that network so that the notification will be fired when the private
4412 // DNS is broken again.
4413 nai.networkAgentConfig.hasShownBroken = false;
4414 }
4415 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004416 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004417 } else if (portalChanged) {
4418 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004419 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004420 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4421 nai.onPreventAutomaticReconnect();
4422 teardownUnneededNetwork(nai);
4423 return;
4424 } else {
4425 updateCapabilitiesForNetwork(nai);
4426 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004427 } else if (becameEvaluated) {
4428 // If valid or partial connectivity changed, updateCapabilities* has
4429 // done the rematch.
4430 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004431 }
4432 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004433
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004434 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004435 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004436 nai.onValidationStatusChanged(
4437 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4438 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004439
4440 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004441 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004442 // immediately. Re-notify partial connectivity silently if no internet
4443 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004444 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004445 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004446 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4447 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004448 }
4449
Chalard Jean254bd162022-08-25 13:04:51 +09004450 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004451 handleNetworkUnvalidated(nai);
4452 }
4453 }
4454
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004455 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4456 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4457 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4458 // Do not avoid captive portal when network is wear proxy.
4459 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4460 }
4461
Calvin Ondada1452016-10-11 15:10:46 -07004462 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004463 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4464 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004465 }
4466
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004467 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4468 switch (msg.what) {
4469 default:
4470 return false;
4471 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4472 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4473 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4474 handleLingerComplete(nai);
4475 }
4476 break;
4477 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004478 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4479 handleNetworkAgentRegistered(msg);
4480 break;
4481 }
4482 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4483 handleNetworkAgentDisconnected(msg);
4484 break;
4485 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004486 }
4487 return true;
4488 }
4489
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004490 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004491 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004492 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004493 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004494 maybeHandleNetworkAgentMessage(msg);
4495 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004496 }
4497 }
4498
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004499 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004500 private final int mNetId;
4501 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004502
4503 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004504 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004505 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004506 }
4507
4508 @Override
4509 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4510 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004511 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004512 }
4513
4514 @Override
4515 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004516 // Legacy version of notifyNetworkTestedWithExtras.
4517 // Would only be called if the system has a NetworkStack module older than the
4518 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004519 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004520 }
4521
4522 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004523 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004524 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4525 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004526 final Message msg = mTrackerHandler.obtainMessage(
4527 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004528 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004529 new NetworkTestedResults(
4530 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004531 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004532
4533 // Invoke ConnectivityReport generation for this Network test event.
4534 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4535 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004536
Cody Kestingf1120be2020-08-03 18:01:40 -07004537 // NetworkMonitor reports the network validation result as a bitmask while
4538 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4539 // logical value for ConnectivityDiagnostics.
4540 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4541 p.result);
4542
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004543 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004544 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004545 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4546 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4547
Aaron Huang959d3642021-01-21 15:47:41 +08004548 ConnectivityReportEvent reportEvent =
4549 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4550 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004551 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004552 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004553 }
4554
4555 @Override
4556 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4557 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4558 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004559 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004560 }
4561
4562 @Override
lucasline117e2e2019-10-22 18:27:33 +08004563 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4564 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4565 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004566 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004567 }
4568
4569 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004570 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4571 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4572 EVENT_CAPPORT_DATA_CHANGED,
4573 0, mNetId, data));
4574 }
4575
4576 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004577 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004578 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004579 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004580
4581 final PendingIntent pendingIntent;
4582 // Only the system server can register notifications with package "android"
4583 final long token = Binder.clearCallingIdentity();
4584 try {
paulhu7746e4e2020-06-09 19:07:03 +08004585 pendingIntent = PendingIntent.getBroadcast(
4586 mContext,
4587 0 /* requestCode */,
4588 intent,
4589 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004590 } finally {
4591 Binder.restoreCallingIdentity(token);
4592 }
4593 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4594 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004595 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004596 }
4597
4598 @Override
4599 public void hideProvisioningNotification() {
4600 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004601 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004602 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004603
4604 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004605 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004606 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004607 }
4608
4609 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004610 public int getInterfaceVersion() {
4611 return this.VERSION;
4612 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004613
4614 @Override
4615 public String getInterfaceHash() {
4616 return this.HASH;
4617 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004618 }
4619
Cody Kestingf1120be2020-08-03 18:01:40 -07004620 /**
4621 * Converts the given NetworkMonitor-specific validation result bitmask to a
4622 * ConnectivityDiagnostics-specific validation result int.
4623 */
4624 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4625 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4626 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4627 }
4628 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4629 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4630 }
4631 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4632 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4633 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4634 }
4635
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004636 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004637 log("Data stall detected with methods: " + p.detectionMethod);
4638
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004639 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004640 int detectionMethod = 0;
4641 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4642 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4643 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4644 }
4645 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4646 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4647 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4648 p.tcpMetricsCollectionPeriodMillis);
4649 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004650 }
4651
Cody Kestingf53a0752020-04-15 12:33:28 -07004652 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004653 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004654 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004655
4656 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4657 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4658 // the cost of going through two handlers.
4659 mConnectivityDiagnosticsHandler.sendMessage(msg);
4660 }
4661
Cody Kestingb37958e2020-05-15 10:36:01 -07004662 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4663 return (p.detectionMethod & detectionMethod) != 0;
4664 }
4665
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004666 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4667 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004668 }
4669
Erik Klinea73af002018-06-26 18:53:43 +09004670 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4671 if (nai == null) return;
4672 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4673 // in order to restart a validation pass from within netd.
4674 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4675 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004676 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004677 }
4678 }
4679
Erik Kline31b4a9e2018-01-11 21:07:29 +09004680 private void handlePrivateDnsSettingsChanged() {
4681 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4682
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004683 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004684 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004685 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004686 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4687 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004688 }
4689 }
4690
Erik Kline9a62f012018-03-21 07:18:33 -07004691 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4692 // Private DNS only ever applies to networks that might provide
4693 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004694 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004695
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004696 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004697 // schedule DNS resolutions. If a DNS resolution is required the
4698 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004699 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004700
4701 // With Private DNS bypass support, we can proceed to update the
4702 // Private DNS config immediately, even if we're in strict mode
4703 // and have not yet resolved the provider name into a set of IPs.
4704 updatePrivateDns(nai, cfg);
4705 }
4706
4707 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4708 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004709 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004710 }
4711
dalyk1720e542018-03-05 12:42:22 -05004712 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4713 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4714 if (nai == null) {
4715 return;
4716 }
4717 mDnsManager.updatePrivateDnsValidation(update);
4718 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4719 }
4720
paulhu7c0a2e62021-01-08 00:51:49 +08004721 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004722 int prefixLength) {
4723 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4724 if (nai == null) return;
4725
paulhu7c0a2e62021-01-08 00:51:49 +08004726 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4727 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004728
4729 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004730 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004731 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004732 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004733 prefixLength);
4734 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004735 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004736 return;
4737 }
4738 }
4739
Lorenzo Colittid523d142020-04-01 20:16:30 +09004740 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004741 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4742 }
4743
Hai Shalome58bdc62021-01-11 18:45:34 -08004744 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004745 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004746 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004747 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4748 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4749 }
4750
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004751 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004752 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004753 * @param nai the agent info to update
4754 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004755 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004756 */
junyulai2b6f0c22021-02-03 20:15:30 +08004757 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4758 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4759 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004760 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004761 // one lingered request, set inactive.
4762 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004763 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004764 if (DBG) log("Unsetting inactive " + nai.toShortString());
4765 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004766 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004767 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004768 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004769 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4770 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004771 }
junyulai2b6f0c22021-02-03 20:15:30 +08004772 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004773 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004774 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004775 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004776 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004777 }
4778
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004779 private void handleNetworkAgentRegistered(Message msg) {
4780 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4781 if (!mNetworkAgentInfos.contains(nai)) {
4782 return;
4783 }
4784
4785 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4786 if (VDBG) log("NetworkAgent registered");
4787 } else {
4788 loge("Error connecting NetworkAgent");
4789 mNetworkAgentInfos.remove(nai);
4790 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004791 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004792 synchronized (mNetworkForNetId) {
4793 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004794 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004795 mNetIdManager.releaseNetId(nai.network.getNetId());
4796 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004797 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004798 }
4799 }
4800 }
Paul Jensend5f53392014-11-25 15:26:53 -05004801
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004802 @VisibleForTesting
4803 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09004804 // The feature of creating the networks immediately was slated for U, but race conditions
4805 // detected late required this was flagged off.
4806 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
4807 // in NetworkAgentTest.
4808 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004809 }
4810
4811 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4812 @NonNull NetworkInfo.State state) {
4813 if (nai.isCreated()) return false;
4814 if (state == NetworkInfo.State.CONNECTED) return true;
4815 if (state != NetworkInfo.State.CONNECTING) {
4816 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09004817 if (shouldCreateNetworksImmediately()) {
4818 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4819 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004820 return false;
4821 }
4822 return nai.isVPN() || shouldCreateNetworksImmediately();
4823 }
4824
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004825 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004826 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004827 }
4828
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004829 @VisibleForTesting
4830 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004831 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09004832 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004833
4834 // If the network never roamed, return false. The check below is not sufficient if time
4835 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4836 if (nai.lastRoamTime == 0) return false;
4837
he_won.hwang881307a2022-03-15 21:23:52 +09004838 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4839 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004840 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004841 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004842 final long currentTimeMs = SystemClock.elapsedRealtime();
4843 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004844 if (timeSinceLastRoam <= blockTimeOut) {
4845 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4846 return true;
4847 }
4848 }
4849 return false;
4850 }
4851
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004852 private void handleNetworkAgentDisconnected(Message msg) {
4853 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004854 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004855 }
4856
Chalard Jeand9fffc32018-05-11 20:19:20 +09004857 // Destroys a network, remove references to it from the internal state managed by
4858 // ConnectivityService, free its interfaces and clean up.
4859 // Must be called on the Handler thread.
4860 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004861 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004862
4863 if (!mNetworkAgentInfos.contains(nai)) return;
4864
Chalard Jeand9fffc32018-05-11 20:19:20 +09004865 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004866 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004867 }
lucaslinb25c9a62019-02-12 15:30:13 +08004868 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004869 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004870 // A network agent has disconnected.
4871 // TODO - if we move the logic to the network agent (have them disconnect
4872 // because they lost all their requests or because their score isn't good)
4873 // then they would disconnect organically, report their new state and then
4874 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08004875 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004876 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4877 null, null);
4878 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004879 final boolean wasDefault = isDefaultNetwork(nai);
4880 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004881 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004882 }
4883 notifyIfacesChangedForNetworkStats();
4884 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4885 // by other networks that are already connected. Perhaps that can be done by
4886 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4887 // of rematchAllNetworksAndRequests
4888 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004889 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004890
4891 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004892 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4893 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08004894 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004895 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004896 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004897 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004898 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004899 synchronized (mNetworkForNetId) {
4900 // Remove the NetworkAgent, but don't mark the netId as
4901 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004902 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004903 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004904 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08004905 // Update allowed network lists in netd. This should be called after removing nai
4906 // from mNetworkAgentInfos.
4907 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004908 // Remove all previously satisfied requests.
4909 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004910 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004911 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004912 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004913 if (currentNetwork != null
4914 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004915 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004916 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4917 // rematch not to keep disconnected agents instead of setting it here ; this
4918 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004919 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004920 for (final NetworkOfferInfo noi : mNetworkOffers) {
4921 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004922 }
James Mattise3ef1912020-12-20 11:09:58 -08004923
Chalard Jean5b409c72021-02-04 13:12:59 +09004924 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004925 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004926 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004927 // network, because while incorrect this is the closest to the old (also
4928 // incorrect) behavior.
4929 mNetworkActivityTracker.updateDataActivityTracking(
4930 null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004931 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004932 ensureNetworkTransitionWakelock(nai.toShortString());
4933 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004934 }
4935 }
junyulai2b6f0c22021-02-03 20:15:30 +08004936 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004937 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004938 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004939 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004940 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004941 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004942 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004943
Aaron Huang9fe47be2021-06-08 13:11:45 +08004944 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
4945 // The obvious place to do this would be in makeDefault(), however makeDefault() is
4946 // not called by the rematch in this case. This is because the code above unset
4947 // this network from the default request's satisfier, and that is what the rematch
4948 // is using as its source data to know what the old satisfier was. So as far as the
4949 // rematch above is concerned, the old default network was null.
4950 // Therefore if there is no new default, the default network was null and is still
4951 // null, thus there was no change so makeDefault() is not called. So if the old
4952 // network had a proxy and there is no new default, the proxy tracker should be told
4953 // that there is no longer a default proxy.
4954 // Strictly speaking this is not essential because having a proxy setting when
4955 // there is no network is harmless, but it's still counter-intuitive so reset to null.
4956 mProxyTracker.setDefaultProxy(null);
4957 }
4958
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004959 // Immediate teardown.
4960 if (nai.teardownDelayMs == 0) {
4961 destroyNetwork(nai);
4962 return;
4963 }
4964
4965 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004966 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304967 try {
4968 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4969 } catch (RemoteException e) {
4970 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4971 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004972 }
4973 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4974 }
4975
4976 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004977 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004978 // Tell netd to clean up the configuration for this network
4979 // (routing rules, DNS, etc).
4980 // This may be slow as it requires a lot of netd shelling out to ip and
4981 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004982 // after we've rematched networks with requests (which might change the default
4983 // network or service a new request from an app), so network traffic isn't interrupted
4984 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004985 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004986 }
Chalard Jeandf29a852023-05-29 17:02:43 +09004987 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004988 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4989 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4990 // false if the network was never created.
4991 // TODO: delete when S is no longer supported.
4992 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004993 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004994 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004995 }
4996
Ken Chen6df7a902021-04-09 15:08:42 +08004997 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004998 try {
4999 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005000 final NativeNetworkConfig config;
5001 if (nai.isVPN()) {
5002 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005003 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005004 return false;
5005 }
5006 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5007 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005008 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005009 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005010 } else {
Chalard Jeane0aaca52023-10-17 13:23:07 +09005011 final boolean hasLocalCap =
5012 nai.networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
5013 config = new NativeNetworkConfig(nai.network.getNetId(),
5014 hasLocalCap ? NativeNetworkType.PHYSICAL_LOCAL : NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005015 getNetworkPermission(nai.networkCapabilities),
5016 false /* secure */,
5017 VpnManager.TYPE_VPN_NONE,
5018 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005019 }
Ken Chen6df7a902021-04-09 15:08:42 +08005020 mNetd.networkCreate(config);
5021 mDnsResolver.createNetworkCache(nai.network.getNetId());
5022 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
5023 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08005024 return true;
5025 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005026 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005027 return false;
5028 }
5029 }
5030
Ken Chen6df7a902021-04-09 15:08:42 +08005031 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005032 if (mDscpPolicyTracker != null) {
5033 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5034 }
Luke Huangfdd11f82019-04-09 18:41:49 +08005035 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005036 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005037 } catch (RemoteException | ServiceSpecificException e) {
5038 loge("Exception destroying network(networkDestroy): " + e);
5039 }
5040 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005041 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005042 } catch (RemoteException | ServiceSpecificException e) {
5043 loge("Exception destroying network: " + e);
5044 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005045 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5046 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5047 // gets created, could add data to DnsManager data structures that will never get deleted.
5048 mDnsManager.removeNetwork(nai.network);
5049
5050 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005051 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005052 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5053 }
5054
Chalard Jean254bd162022-08-25 13:04:51 +09005055 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005056 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005057 }
5058
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005059 // If this method proves to be too slow then we can maintain a separate
5060 // pendingIntent => NetworkRequestInfo map.
5061 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5062 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005063 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5064 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5065 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005066 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005067 return entry.getValue();
5068 }
5069 }
5070 return null;
5071 }
5072
Chalard Jean524f0b12021-10-25 21:11:56 +09005073 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005074 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005075 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5076 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5077 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5078 // bug is fixed.
5079 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005080 throw new IllegalStateException("This NRI is already registered. New : " + nri
5081 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005082 }
5083 }
5084 }
5085 }
5086
Chalard Jeanac9ace02022-01-26 16:54:05 +09005087 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5088 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005089 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09005090 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
5091 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005092 }
5093 return false;
5094 }
5095
James Mattisf7027322020-12-13 16:28:14 -08005096 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005097 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005098 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5099 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5100 final NetworkRequestInfo existingRequest =
5101 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005102 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005103 if (DBG) {
5104 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5105 + nri.mRequests.get(0) + " because their intents matched.");
5106 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005107 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005108 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005109 }
Erik Kline05f2b402015-04-30 12:58:40 +09005110 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005111 }
5112
James Mattisf7027322020-12-13 16:28:14 -08005113 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005114 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005115 }
5116
James Mattis3ce3d3c2021-02-09 18:18:28 -08005117 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005118 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005119 for (final NetworkRequestInfo nri : nris) {
5120 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005121 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005122 for (final NetworkRequest req : nri.mRequests) {
5123 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005124 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005125 if (req.isListen()) {
5126 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5127 if (req.networkCapabilities.hasSignalStrength()
5128 && network.satisfiesImmutableCapabilitiesOf(req)) {
5129 updateSignalStrengthThresholds(network, "REGISTER", req);
5130 }
James Mattisf7027322020-12-13 16:28:14 -08005131 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005132 }
5133 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005134
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005135 // If this NRI has a satisfier already, it is replacing an older request that
5136 // has been removed. Track it.
5137 final NetworkRequest activeRequest = nri.getActiveRequest();
5138 if (null != activeRequest) {
5139 // If there is an active request, then for sure there is a satisfier.
5140 nri.getSatisfier().addRequest(activeRequest);
5141 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005142 }
James Mattisf7027322020-12-13 16:28:14 -08005143
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005144 if (mFlags.noRematchAllRequestsOnRegister()) {
5145 rematchNetworksAndRequests(nris);
5146 } else {
5147 rematchAllNetworksAndRequests();
5148 }
James Mattis45d81842021-01-10 14:24:24 -08005149
Chalard Jean0354d8c2021-01-12 10:58:56 +09005150 // Requests that have not been matched to a network will not have been sent to the
5151 // providers, because the old satisfier and the new satisfier are the same (null in this
5152 // case). Send these requests to the providers.
5153 for (final NetworkRequestInfo nri : nris) {
5154 for (final NetworkOfferInfo noi : mNetworkOffers) {
5155 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005156 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005157 }
5158 }
5159
James Mattisf7027322020-12-13 16:28:14 -08005160 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5161 final int callingUid) {
5162 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005163 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005164 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5165 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5166 handleReleaseNetworkRequest(
5167 nri.mRequests.get(0),
5168 callingUid,
5169 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005170 }
5171 }
5172
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005173 // Determines whether the network is the best (or could become the best, if it validated), for
5174 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5175 // on the value of reason:
5176 //
5177 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5178 // then it should be torn down.
5179 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5180 // then it should be lingered.
5181 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005182 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005183
Chalard Jean254bd162022-08-25 13:04:51 +09005184 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005185 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5186 return false;
5187 }
5188
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005189 final int numRequests;
5190 switch (reason) {
5191 case TEARDOWN:
5192 numRequests = nai.numRequestNetworkRequests();
5193 break;
5194 case LINGER:
5195 numRequests = nai.numForegroundNetworkRequests();
5196 break;
5197 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005198 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005199 return true;
5200 }
5201
Chalard Jean947acd42021-03-08 22:29:27 +09005202 if (numRequests > 0) return false;
5203
Paul Jensende49eb12015-06-25 15:30:08 -04005204 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005205 if (reason == UnneededFor.LINGER
5206 && !nri.isMultilayerRequest()
5207 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005208 // Background requests don't affect lingering.
5209 continue;
5210 }
5211
James Mattis3d229892020-11-16 16:46:28 -08005212 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005213 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005214 }
5215 }
Paul Jensende49eb12015-06-25 15:30:08 -04005216 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005217 }
5218
James Mattis3d229892020-11-16 16:46:28 -08005219 private boolean isNetworkPotentialSatisfier(
5220 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
5221 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005222 // request, return immediately. For multilayer requests, check to see if any of the
5223 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005224 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5225 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005226 return false;
5227 }
5228 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005229 // This multilayer listen request is satisfied therefore no further requests need to be
5230 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005231 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005232 return false;
5233 }
James Mattis3d229892020-11-16 16:46:28 -08005234 // As non-multilayer listen requests have already returned, the below would only happen
5235 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005236 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005237 continue;
5238 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09005239 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08005240 // there is hope for it to become one if it validated, then it is needed.
5241 if (candidate.satisfies(req)) {
5242 // As soon as a network is found that satisfies a request, return. Specifically for
5243 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5244 // is important so as to not evaluate lower priority requests further in
5245 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005246 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5247 ? nri.getSatisfier() : null;
5248 // Note that this catches two important cases:
5249 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5250 // is currently satisfying the request. This is desirable when
5251 // cellular ends up validating but WiFi does not.
5252 // 2. Unvalidated WiFi will not be reaped when validated cellular
5253 // is currently satisfying the request. This is desirable when
5254 // WiFi ends up validating and out scoring cellular.
5255 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005256 }
5257 }
5258
5259 return false;
5260 }
5261
Erik Kline0c04b742016-07-07 16:50:58 +09005262 private NetworkRequestInfo getNriForAppRequest(
5263 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005264 // Looking up the app passed param request in mRequests isn't possible since it may return
5265 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5266 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005267 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5268 // to avoid potential race conditions when validating a package->uid mapping when sending
5269 // the callback on the very low-chance that an application shuts down prior to the callback
5270 // being sent.
5271 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5272 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005273
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005274 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005275 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005276 log(String.format("UID %d attempted to %s for unowned request %s",
5277 callingUid, requestedOperation, nri));
5278 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005279 }
Erik Kline0c04b742016-07-07 16:50:58 +09005280 }
5281
5282 return nri;
5283 }
5284
James Mattisf7027322020-12-13 16:28:14 -08005285 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5286 final String callingMethod) {
5287 if (nri.isMultilayerRequest()) {
5288 throw new IllegalStateException(
5289 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005290 }
5291 }
5292
James Mattisf7027322020-12-13 16:28:14 -08005293 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005294 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005295 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5296 // single NetworkRequest and thus does not apply to multilayer requests.
5297 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5298 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005299 return;
5300 }
James Mattis2516da32021-01-31 17:06:19 -08005301 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005302 return;
5303 }
James Mattisf7027322020-12-13 16:28:14 -08005304 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5305 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005306 }
5307 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005308 callCallbackForRequest(
5309 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005310 }
5311
James Mattisf7027322020-12-13 16:28:14 -08005312 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5313 final int callingUid,
5314 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005315 final NetworkRequestInfo nri =
5316 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5317 if (nri == null) {
5318 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005319 }
James Mattisf7027322020-12-13 16:28:14 -08005320 if (VDBG || (DBG && request.isRequest())) {
5321 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005322 }
5323 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005324 if (callOnUnavailable) {
5325 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5326 }
Erik Kline155a59a2015-11-25 12:49:38 +09005327 }
Erik Kline0c04b742016-07-07 16:50:58 +09005328
James Mattisa076c532020-12-02 14:12:41 -08005329 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005330 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005331 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005332 if (null == mNetworkRequests.remove(req)) {
5333 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5334 continue;
5335 }
James Mattisa076c532020-12-02 14:12:41 -08005336 if (req.isListen()) {
5337 removeListenRequestFromNetworks(req);
5338 }
5339 }
James Mattis8f036802021-06-20 16:26:01 -07005340 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005341 if (mDefaultNetworkRequests.remove(nri)) {
5342 // If this request was one of the defaults, then the UID rules need to be updated
5343 // WARNING : if the app(s) for which this network request is the default are doing
5344 // traffic, this will kill their connected sockets, even if an equivalent request
5345 // is going to be reinstated right away ; unconnected traffic will go on the default
5346 // until the new default is set, which will happen very soon.
5347 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5348 // remove ranges for those requests that won't have a replacement
5349 final NetworkAgentInfo satisfier = nri.getSatisfier();
5350 if (null != satisfier) {
5351 try {
paulhu0e79d952021-06-09 16:11:35 +08005352 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5353 satisfier.network.getNetId(),
5354 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005355 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005356 } catch (RemoteException e) {
5357 loge("Exception setting network preference default network", e);
5358 }
5359 }
5360 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005361
Junyu Lai00d92df2022-07-05 11:01:52 +08005362 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005363 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005364 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005365
5366 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005367 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005368 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005369 }
5370 }
5371
Chalard Jean0354d8c2021-01-12 10:58:56 +09005372 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5373 // needed for this offer.
5374 for (final NetworkOfferInfo noi : mNetworkOffers) {
5375 for (final NetworkRequest req : nri.mRequests) {
5376 if (req.isRequest() && noi.offer.neededFor(req)) {
5377 noi.offer.onNetworkUnneeded(req);
5378 }
5379 }
5380 }
James Mattisa076c532020-12-02 14:12:41 -08005381 }
5382
James Mattis3ce3d3c2021-02-09 18:18:28 -08005383 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5384 for (final NetworkRequestInfo nri : nris) {
5385 if (mDefaultRequest == nri) {
5386 // Make sure we never remove the default request.
5387 continue;
5388 }
5389 handleRemoveNetworkRequest(nri);
5390 }
5391 }
5392
James Mattisa076c532020-12-02 14:12:41 -08005393 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5394 // listens don't have a singular affected Network. Check all networks to see
5395 // if this listen request applies and remove it.
5396 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5397 nai.removeRequest(req.requestId);
5398 if (req.networkCapabilities.hasSignalStrength()
5399 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5400 updateSignalStrengthThresholds(nai, "RELEASE", req);
5401 }
5402 }
5403 }
5404
5405 /**
5406 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5407 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5408 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5409 */
5410 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5411 boolean wasKept = false;
5412 final NetworkAgentInfo nai = nri.getSatisfier();
5413 if (nai != null) {
5414 final int requestLegacyType = nri.getActiveRequest().legacyType;
5415 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5416 nai.removeRequest(nri.getActiveRequest().requestId);
5417 if (VDBG || DDBG) {
5418 log(" Removing from current network " + nai.toShortString()
5419 + ", leaving " + nai.numNetworkRequests() + " requests.");
5420 }
5421 // If there are still lingered requests on this network, don't tear it down,
5422 // but resume lingering instead.
5423 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005424 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005425 notifyNetworkLosing(nai, now);
5426 }
5427 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5428 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5429 teardownUnneededNetwork(nai);
5430 } else {
5431 wasKept = true;
5432 }
James Mattisa076c532020-12-02 14:12:41 -08005433 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5434 // Went from foreground to background.
5435 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005436 }
5437
Erik Kline0c04b742016-07-07 16:50:58 +09005438 // Maintain the illusion. When this request arrived, we might have pretended
5439 // that a network connected to serve it, even though the network was already
5440 // connected. Now that this request has gone away, we might have to pretend
5441 // that the network disconnected. LegacyTypeTracker will generate that
5442 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005443 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005444 boolean doRemove = true;
5445 if (wasKept) {
5446 // check if any of the remaining requests for this network are for the
5447 // same legacy type - if so, don't remove the nai
5448 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5449 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005450 if (otherRequest.legacyType == requestLegacyType
5451 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005452 if (DBG) log(" still have other legacy request - leaving");
5453 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005454 }
5455 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005456 }
5457
Erik Kline0c04b742016-07-07 16:50:58 +09005458 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005459 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005460 }
5461 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005462 }
5463 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005464
Junyu Lai00d92df2022-07-05 11:01:52 +08005465 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005466 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005467 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5468 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5469 }
5470
Lorenzo Colittid6459092016-07-04 12:55:44 +09005471 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005472 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005473 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005474 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005475 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005476 }
5477
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005478 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005479 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5480 enforceNetworkStackSettingsOrSetup();
5481 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5482 encodeBool(accept), encodeBool(always), network));
5483 }
5484
5485 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005486 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005487 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005488 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5489 }
5490
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005491 @Override
5492 public void setTestAllowBadWifiUntil(long timeMs) {
5493 enforceSettingsPermission();
5494 if (!Build.isDebuggable()) {
5495 throw new IllegalStateException("Does not support in non-debuggable build");
5496 }
5497
5498 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5499 throw new IllegalArgumentException("It should not exceed "
5500 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5501 }
5502
5503 mHandler.sendMessage(
5504 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5505 }
5506
chiachangwange0192a72023-02-06 13:25:01 +00005507 @Override
5508 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5509 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005510
5511 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5512 throw new IllegalArgumentException("Argument should not exceed "
5513 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5514 }
5515
5516 mHandler.sendMessage(
5517 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5518 }
5519
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005520 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5521 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5522 " accept=" + accept + " always=" + always);
5523
5524 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5525 if (nai == null) {
5526 // Nothing to do.
5527 return;
5528 }
5529
Chalard Jean254bd162022-08-25 13:04:51 +09005530 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005531 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005532 return;
5533 }
5534
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005535 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005536 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005537 }
5538
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005539 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5540 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005541 // If network becomes partial connectivity and user already accepted to use this
5542 // network, we should respect the user's option and don't need to popup the
5543 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005544 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005545 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005546 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005547 }
5548
5549 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005550 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005551 }
5552
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005553 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005554 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005555 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005556 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005557 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005558 }
5559
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005560 }
5561
lucaslin2240ef62019-03-12 13:08:03 +08005562 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5563 boolean always) {
5564 if (DBG) {
5565 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5566 + " always=" + always);
5567 }
5568
5569 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5570 if (nai == null) {
5571 // Nothing to do.
5572 return;
5573 }
5574
Chalard Jean254bd162022-08-25 13:04:51 +09005575 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005576 // The network validated while the dialog box was up. Take no action.
5577 return;
5578 }
5579
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005580 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5581 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005582 }
5583
5584 // TODO: Use the current design or save the user choice into IpMemoryStore.
5585 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005586 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005587 }
5588
5589 if (!accept) {
5590 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005591 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005592 // Tear down the network.
5593 teardownUnneededNetwork(nai);
5594 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005595 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5596 // result in a partial connectivity result which will be processed by
5597 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005598 //
5599 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5600 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005601 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005602 }
5603 }
5604
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005605 private void handleSetAvoidUnvalidated(Network network) {
5606 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005607 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005608 // Nothing to do. The network either disconnected or revalidated.
5609 return;
5610 }
Chalard Jean254bd162022-08-25 13:04:51 +09005611 if (0L == nai.getAvoidUnvalidated()) {
5612 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005613 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005614 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005615 }
5616 }
5617
Chalard Jean5fb43c72022-09-08 19:03:14 +09005618 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005619 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005620 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005621 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005622 }
5623
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005624 @Override
5625 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005626 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005627 mHandler.post(() -> {
5628 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5629 if (nai == null) return;
5630 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005631 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005632 });
5633 }
5634
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005635 /**
5636 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5637 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005638 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005639 * @param appExtras Bundle to use as intent extras for the captive portal application.
5640 * Must be treated as opaque to avoid preventing the captive portal app to
5641 * update its arguments.
5642 */
5643 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005644 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005645 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5646 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005647
5648 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5649 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005650 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5651 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005652 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5653
lucaslin75ff7022020-12-17 04:14:35 +08005654 final long token = Binder.clearCallingIdentity();
5655 try {
5656 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5657 } finally {
5658 Binder.restoreCallingIdentity(token);
5659 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005660 }
5661
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005662 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5663 private final Network mNetwork;
5664
5665 private CaptivePortalImpl(Network network) {
5666 mNetwork = network;
5667 }
5668
5669 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005670 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005671 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5672 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005673 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5674 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5675 // Since the network will be disconnected, skip notifying NetworkMonitor
5676 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005677 }
5678
Chiachang Wang938bfba2020-01-09 13:50:55 +08005679 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005680 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005681 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005682 }
5683
5684 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005685 public void appRequest(final int request) {
5686 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5687 if (nm == null) return;
5688
5689 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005690 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005691 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005692 }
5693 }
5694
5695 @Nullable
5696 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5697 // getNetworkAgentInfoForNetwork is thread-safe
5698 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5699 if (nai == null) return null;
5700
5701 // nai.networkMonitor() is thread-safe
5702 return nai.networkMonitor();
5703 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005704 }
5705
Hugo Benichic9048bc2016-09-14 23:23:08 +00005706 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005707 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005708 }
5709
Chalard Jean020b93a2022-09-01 13:20:14 +09005710 private boolean activelyPreferBadWifi() {
5711 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5712 }
5713
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005714 /**
5715 * Return whether the device should maintain continuous, working connectivity by switching away
5716 * from WiFi networks having no connectivity.
5717 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5718 */
5719 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005720 if (!checkNetworkStackPermission()) {
5721 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5722 }
5723 return avoidBadWifi();
5724 }
5725
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005726 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005727 ensureRunningOnConnectivityServiceThread();
5728 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005729 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005730 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005731 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005732 if (avoidBadWifi) {
5733 // If the device is now avoiding bad wifi, remove notifications that might have
5734 // been put up when the device didn't.
5735 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5736 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005737 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005738 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5739 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5740 for (final NetworkOfferInfo noi : offersToUpdate) {
5741 updateOfferScore(noi.offer);
5742 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005743 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005744 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005745 }
5746
Erik Kline95ecfee2016-10-02 18:02:14 +09005747 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005748 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005749 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005750 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005751 if (!configRestrict) {
5752 pw.println("Bad Wi-Fi avoidance: unrestricted");
5753 return;
5754 }
5755
5756 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5757 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005758 pw.println("Config restrict: " + configRestrict);
5759 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005760
Chalard Jeane0fdea32022-09-14 21:44:22 +09005761 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005762 String description;
5763 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005764 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005765 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005766 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005767 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005768 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005769 description = "avoid";
5770 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005771 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005772 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005773 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005774
5775 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5776 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005777 if (null == configValue) {
5778 description = "unset";
5779 } else if (configValue) {
5780 description = "force true";
5781 } else {
5782 description = "force false";
5783 }
5784 pw.println("Actively prefer bad wifi conf: " + description);
5785 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005786 pw.println("Network overrides:");
5787 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005788 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005789 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005790 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005791 }
5792 }
5793 pw.decreaseIndent();
5794 pw.decreaseIndent();
5795 }
5796
paulhu7746e4e2020-06-09 19:07:03 +08005797 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5798 // unify the method.
5799 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5800 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5801 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5802 return settingsComponent != null
5803 ? settingsComponent.getPackageName() : "com.android.settings";
5804 }
5805
lucaslinb1e8e382019-01-24 15:55:30 +08005806 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005807 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005808 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005809 switch (type) {
5810 case NO_INTERNET:
5811 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005812 // High priority because it is only displayed for explicitly selected networks.
5813 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005814 break;
lucasline117e2e2019-10-22 18:27:33 +08005815 case PRIVATE_DNS_BROKEN:
5816 action = Settings.ACTION_WIRELESS_SETTINGS;
5817 // High priority because we should let user know why there is no internet.
5818 highPriority = true;
5819 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005820 case LOST_INTERNET:
5821 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005822 // High priority because it could help the user avoid unexpected data usage.
5823 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005824 break;
lucaslin2240ef62019-03-12 13:08:03 +08005825 case PARTIAL_CONNECTIVITY:
5826 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005827 // Don't bother the user with a high-priority notification if the network was not
5828 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005829 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005830 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005831 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005832 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005833 return;
5834 }
5835
5836 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005837 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005838 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005839 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005840 // Some OEMs have their own Settings package. Thus, need to get the current using
5841 // Settings package name instead of just use default name "com.android.settings".
5842 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5843 intent.setClassName(settingsPkgName,
5844 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005845 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005846
paulhu2af50222020-10-11 22:52:27 +08005847 PendingIntent pendingIntent = PendingIntent.getActivity(
5848 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005849 0 /* requestCode */,
5850 intent,
paulhu2af50222020-10-11 22:52:27 +08005851 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005852
Serik Beketayevec8ad212020-12-07 22:43:07 -08005853 mNotifier.showNotification(
5854 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005855 }
5856
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005857 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5858 // Don't prompt if the network is validated, and don't prompt on captive portals
5859 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005860 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005861 return false;
5862 }
5863
5864 // If a network has partial connectivity, always prompt unless the user has already accepted
5865 // partial connectivity and selected don't ask again. This ensures that if the device
5866 // automatically connects to a network that has partial Internet access, the user will
5867 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005868 // because we have prompted them.
5869 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005870 return true;
5871 }
5872
5873 // If a network has no Internet access, only prompt if the network was explicitly selected
5874 // and if the user has not already told us to use the network regardless of whether it
5875 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005876 if (nai.networkAgentConfig.explicitlySelected
5877 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005878 return true;
5879 }
5880
5881 return false;
5882 }
5883
Chalard Jean5fb43c72022-09-08 19:03:14 +09005884 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5885 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005886
Chalard Jean5fb43c72022-09-08 19:03:14 +09005887 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5888 if (null == nai) return;
5889
5890 if (nai.setEvaluated()) {
5891 // If setEvaluated() returned true, the network never had any form of connectivity.
5892 // This may have an impact on request matching if bad WiFi avoidance is off and the
5893 // network was found not to have Internet access.
5894 nai.updateScoreForNetworkAgentUpdate();
5895 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005896
5897 // Also, if this is WiFi and it should be preferred actively, now is the time to
5898 // prompt the user that they walked past and connected to a bad WiFi.
5899 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5900 && !avoidBadWifi()
5901 && activelyPreferBadWifi()) {
5902 // The notification will be removed if the network validates or disconnects.
5903 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5904 return;
5905 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005906 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005907
Chalard Jean5fb43c72022-09-08 19:03:14 +09005908 if (!shouldPromptUnvalidated(nai)) return;
5909
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005910 // Stop automatically reconnecting to this network in the future. Automatically connecting
5911 // to a network that provides no or limited connectivity is not useful, because the user
5912 // cannot use that network except through the notification shown by this method, and the
5913 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005914 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005915
Chalard Jean254bd162022-08-25 13:04:51 +09005916 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005917 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005918 } else {
5919 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5920 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005921 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005922
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005923 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5924 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005925 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005926
lucaslin2240ef62019-03-12 13:08:03 +08005927 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5928 return;
5929 }
5930
5931 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005932 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005933 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005934 }
5935
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005936 @Override
5937 public int getMultipathPreference(Network network) {
5938 enforceAccessPermission();
5939
5940 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005941 if (nai != null && nai.networkCapabilities
5942 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005943 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5944 }
5945
Aaron Huang9a57acf2020-12-08 10:03:29 +08005946 final NetworkPolicyManager netPolicyManager =
5947 mContext.getSystemService(NetworkPolicyManager.class);
5948
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005949 final long token = Binder.clearCallingIdentity();
5950 final int networkPreference;
5951 try {
5952 networkPreference = netPolicyManager.getMultipathPreference(network);
5953 } finally {
5954 Binder.restoreCallingIdentity(token);
5955 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005956 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005957 return networkPreference;
5958 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005959 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5960 }
5961
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005962 @Override
5963 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005964 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005965 }
5966
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005967 private class InternalHandler extends Handler {
5968 public InternalHandler(Looper looper) {
5969 super(looper);
5970 }
5971
5972 @Override
5973 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005974 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005975 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005976 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005977 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005978 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005979 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005980 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005981 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005982 break;
5983 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08005984 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005985 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08005986 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005987 break;
5988 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005989 case EVENT_REGISTER_NETWORK_PROVIDER: {
5990 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005991 break;
5992 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005993 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5994 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005995 break;
5996 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005997 case EVENT_REGISTER_NETWORK_OFFER: {
5998 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5999 break;
6000 }
6001 case EVENT_UNREGISTER_NETWORK_OFFER: {
6002 final NetworkOfferInfo offer =
6003 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6004 if (null != offer) {
6005 handleUnregisterNetworkOffer(offer);
6006 }
6007 break;
6008 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006009 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006010 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6011 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6012 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006013 break;
6014 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006015 case EVENT_REGISTER_NETWORK_REQUEST:
6016 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006017 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006018 break;
6019 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006020 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6021 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006022 handleRegisterNetworkRequestWithIntent(msg);
6023 break;
6024 }
Erik Kline155a59a2015-11-25 12:49:38 +09006025 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6026 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6027 handleTimedOutNetworkRequest(nri);
6028 break;
6029 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006030 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6031 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6032 break;
6033 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006034 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006035 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6036 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006037 break;
6038 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006039 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006040 Network network = (Network) msg.obj;
6041 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006042 break;
6043 }
lucaslin2240ef62019-03-12 13:08:03 +08006044 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6045 Network network = (Network) msg.obj;
6046 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6047 toBool(msg.arg2));
6048 break;
6049 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006050 case EVENT_SET_AVOID_UNVALIDATED: {
6051 handleSetAvoidUnvalidated((Network) msg.obj);
6052 break;
6053 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006054 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6055 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006056 break;
6057 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006058 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6059 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006060 break;
6061 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006062 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6063 // handler thread.
6064 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006065 mKeepaliveTracker.handleStartKeepalive(msg);
6066 break;
6067 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006068 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006069 final AutomaticOnOffKeepalive ki =
6070 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6071 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006072
chiachangwang676c84e2023-02-14 09:22:05 +00006073 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006074 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006075 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006076 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006077 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6078 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006079 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6080 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006081 }
6082 }
6083
6084 // If the network no longer exists, then the keepalive should have been
6085 // cleaned up already. There is no point trying to resume keepalives.
6086 if (!networkFound) return;
6087
chiachangwang676c84e2023-02-14 09:22:05 +00006088 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006089 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang676c84e2023-02-14 09:22:05 +00006090 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006091 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006092 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006093 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006094 }
6095 break;
6096 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006097 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006098 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006099 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6100 (IBinder) msg.obj);
6101 if (ki == null) {
6102 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006103 return;
6104 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006105 final int reason = msg.arg2;
6106 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006107 break;
6108 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006109 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6110 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6111 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006112 break;
6113 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006114 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6115 handlePrivateDnsSettingsChanged();
6116 break;
dalyk1720e542018-03-05 12:42:22 -05006117 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6118 handlePrivateDnsValidationUpdate(
6119 (PrivateDnsValidationUpdate) msg.obj);
6120 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006121 case EVENT_UID_BLOCKED_REASON_CHANGED:
6122 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006123 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006124 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6125 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6126 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006127 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006128 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6129 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006130 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006131 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006132 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006133 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006134 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6135 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006136 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006137 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006138 }
lucaslin1193a5d2021-01-21 02:04:15 +08006139 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006140 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006141 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006142 break;
paulhu51f77dc2021-06-07 02:34:20 +00006143 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6144 handleMobileDataPreferredUidsChanged();
6145 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006146 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6147 final long timeMs = ((Long) msg.obj).longValue();
6148 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6149 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006150 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6151 handleIngressRateLimitChanged();
6152 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006153 case EVENT_USER_DOES_NOT_WANT:
6154 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6155 if (nai == null) break;
6156 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006157 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006158 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006159 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6160 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6161 break;
chiachangwange0192a72023-02-06 13:25:01 +00006162 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6163 final long time = ((Long) msg.obj).longValue();
6164 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6165 break;
6166 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006167 case EVENT_UID_FROZEN_STATE_CHANGED:
6168 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6169 handleFrozenUids(args.mUids, args.mFrozenStates);
6170 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006171 }
6172 }
6173 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006174
Lorenzo Colittid6459092016-07-04 12:55:44 +09006175 @Override
markchien5776f962019-12-16 20:15:20 +08006176 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006177 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006178 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006179 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6180 Context.TETHERING_SERVICE);
6181 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006182 }
6183
Lorenzo Colittid6459092016-07-04 12:55:44 +09006184 @Override
markchien5776f962019-12-16 20:15:20 +08006185 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006186 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006187 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006188 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6189 Context.TETHERING_SERVICE);
6190 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006191 }
6192
Lorenzo Colittid6459092016-07-04 12:55:44 +09006193 @Override
markchien5776f962019-12-16 20:15:20 +08006194 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006195 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006196 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006197 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6198 Context.TETHERING_SERVICE);
6199 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006200 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006201
markchien5776f962019-12-16 20:15:20 +08006202
Lorenzo Colittid6459092016-07-04 12:55:44 +09006203 @Override
markchien5776f962019-12-16 20:15:20 +08006204 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006205 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006206 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006207 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6208 Context.TETHERING_SERVICE);
6209
6210 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006211 }
6212
Lorenzo Colittid6459092016-07-04 12:55:44 +09006213 @Override
markchien5776f962019-12-16 20:15:20 +08006214 @Deprecated
6215 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006216 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006217 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6218 Context.TETHERING_SERVICE);
6219
6220 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006221 }
6222
Udam Saini8f7d6a72017-06-07 12:06:28 -07006223 @Override
markchien5776f962019-12-16 20:15:20 +08006224 @Deprecated
6225 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006226 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006227 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6228 Context.TETHERING_SERVICE);
6229 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006230 }
6231
Robert Greenwalte0b00512014-07-02 09:59:16 -07006232 // Called when we lose the default network and have no replacement yet.
6233 // This will automatically be cleared after X seconds or a new default network
6234 // becomes CONNECTED, whichever happens first. The timer is started by the
6235 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006236 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006237 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006238 if (mNetTransitionWakeLock.isHeld()) {
6239 return;
6240 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006241 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006242 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6243 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006244 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006245 mWakelockLogs.log("ACQUIRE for " + forWhom);
6246 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006247 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006248 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006249 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006250 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006251
Hugo Benichi471b62a2017-03-30 23:18:10 +09006252 // Called when we gain a new default network to release the network transition wakelock in a
6253 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6254 // message is cancelled.
6255 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006256 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006257 if (!mNetTransitionWakeLock.isHeld()) {
6258 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006259 }
6260 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006261 // Cancel self timeout on wakelock hold.
6262 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6263 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6264 mHandler.sendMessageDelayed(msg, 1000);
6265 }
6266
6267 // Called when either message of ensureNetworkTransitionWakelock or
6268 // scheduleReleaseNetworkTransitionWakelock is processed.
6269 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6270 String event = eventName(eventId);
6271 synchronized (this) {
6272 if (!mNetTransitionWakeLock.isHeld()) {
6273 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006274 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006275 return;
6276 }
6277 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006278 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6279 mTotalWakelockDurationMs += lockDuration;
6280 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6281 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006282 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006283 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006284 }
6285
Robert Greenwalt986c7412010-09-08 15:24:47 -07006286 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006287 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006288 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006289 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006290 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006291 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006292 }
6293
Lorenzo Colittid6459092016-07-04 12:55:44 +09006294 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006295 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006296 enforceAccessPermission();
6297 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006298 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006299 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006300
6301 final NetworkAgentInfo nai;
6302 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006303 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006304 } else {
6305 nai = getNetworkAgentInfoForNetwork(network);
6306 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006307
6308 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006309 mHandler.obtainMessage(
6310 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006311 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006312
Hugo Benichid6b510a2017-04-06 17:22:18 +09006313 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006314 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006315 if (nai == null
6316 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006317 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006318 return;
6319 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006320 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006321 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006322 mConnectivityDiagnosticsHandler.sendMessage(
6323 mConnectivityDiagnosticsHandler.obtainMessage(
6324 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6325 new ReportedNetworkConnectivityInfo(
6326 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006327 return;
6328 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006329 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006330 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006331 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006332 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006333 // Validating a network that has not yet connected could result in a call to
6334 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006335 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006336 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006337 }
paulhu7aeba372020-12-30 00:42:19 +08006338 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6339 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006340 return;
6341 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006342
6343 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6344 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6345 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6346 // completed.
6347 mConnectivityDiagnosticsHandler.sendMessage(
6348 mConnectivityDiagnosticsHandler.obtainMessage(
6349 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6350 new ReportedNetworkConnectivityInfo(
6351 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006352 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006353 }
6354
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006355 // TODO: call into netd.
6356 private boolean queryUserAccess(int uid, Network network) {
6357 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6358 if (nai == null) return false;
6359
6360 // Any UID can use its default network.
6361 if (nai == getDefaultNetworkForUid(uid)) return true;
6362
6363 // Privileged apps can use any network.
6364 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6365 return true;
6366 }
6367
6368 // An unprivileged UID can use a VPN iff the VPN applies to it.
6369 if (nai.isVPN()) {
6370 return nai.networkCapabilities.appliesToUid(uid);
6371 }
6372
6373 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6374 // sockets, i.e., if it is the owner.
6375 final NetworkAgentInfo vpn = getVpnForUid(uid);
6376 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6377 && uid != vpn.networkCapabilities.getOwnerUid()) {
6378 return false;
6379 }
6380
6381 // The UID's permission must be at least sufficient for the network. Since the restricted
6382 // permission was already checked above, that just leaves background networks.
6383 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6384 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6385 }
6386
6387 // Unrestricted network. Anyone gets to use it.
6388 return true;
6389 }
6390
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006391 /**
6392 * Returns information about the proxy a certain network is using. If given a null network, it
6393 * it will return the proxy for the bound network for the caller app or the default proxy if
6394 * none.
6395 *
6396 * @param network the network we want to get the proxy information for.
6397 * @return Proxy information if a network has a proxy configured, or otherwise null.
6398 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006399 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006400 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006401 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006402 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006403 if (network == null) {
6404 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006405 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006406 true);
6407 if (activeNetwork == null) {
6408 return null;
6409 }
6410 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006411 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006412 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6413 // caller may not have.
6414 return getLinkPropertiesProxyInfo(network);
6415 }
6416 // No proxy info available if the calling UID does not have network access.
6417 return null;
6418 }
6419
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006420
6421 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006422 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6423 if (nai == null) return null;
6424 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006425 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6426 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006427 }
6428 }
6429
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006430 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006431 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006432 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006433 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006434 }
6435
Chalard Jean777e2e52018-06-07 18:02:37 +09006436 @Override
6437 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006438 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006439 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006440 }
6441
Aaron Huang9fe47be2021-06-08 13:11:45 +08006442 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006443 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006444 final NetworkAgentInfo nai = getDefaultNetwork();
6445 // TODO : this method should check that net == nai.network, unfortunately at this point
6446 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6447 // is only ever installed on the default network so in practice this is okay.
6448 if (null == nai) return;
6449 // PAC proxies only work on the default network. Therefore, only the default network
6450 // should have its link properties fixed up for PAC proxies.
6451 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6452 if (nai.everConnected()) {
6453 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6454 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006455 }
6456
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006457 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6458 // when any network changes proxy.
6459 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6460 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006461 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6462 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006463 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6464
Chalard Jean7d97afc2018-06-07 17:41:29 +09006465 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006466 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006467 }
6468 }
6469
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006470 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006471 final private HashMap<Uri, Integer> mUriEventMap;
6472 final private Context mContext;
6473 final private Handler mHandler;
6474
6475 SettingsObserver(Context context, Handler handler) {
6476 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006477 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006478 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006479 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006480 }
6481
Erik Kline05f2b402015-04-30 12:58:40 +09006482 void observe(Uri uri, int what) {
6483 mUriEventMap.put(uri, what);
6484 final ContentResolver resolver = mContext.getContentResolver();
6485 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006486 }
6487
6488 @Override
6489 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006490 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006491 }
6492
6493 @Override
6494 public void onChange(boolean selfChange, Uri uri) {
6495 final Integer what = mUriEventMap.get(uri);
6496 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006497 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006498 } else {
6499 loge("No matching event to send for URI=" + uri);
6500 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006501 }
6502 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006503
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006504 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006505 Log.d(TAG, s);
6506 }
6507
6508 private static void logw(String s) {
6509 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006510 }
6511
Daniel Brightf9e945b2020-06-15 16:10:01 -07006512 private static void logwtf(String s) {
6513 Log.wtf(TAG, s);
6514 }
6515
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006516 private static void logwtf(String s, Throwable t) {
6517 Log.wtf(TAG, s, t);
6518 }
6519
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006520 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006521 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006522 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006523
Hugo Benichi39621362017-02-11 17:04:43 +09006524 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006525 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006526 }
6527
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006528 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006529 * Return the information of all ongoing VPNs.
6530 *
6531 * <p>This method is used to update NetworkStatsService.
6532 *
6533 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006534 */
junyulai2050bed2021-01-23 09:46:34 +08006535 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006536 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006537 if (mLockdownEnabled) {
6538 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006539 }
junyulai2050bed2021-01-23 09:46:34 +08006540 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006541 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006542 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006543 if (info != null) {
6544 infoList.add(info);
6545 }
6546 }
junyulai2050bed2021-01-23 09:46:34 +08006547 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006548 }
6549
6550 /**
6551 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006552 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006553 */
junyulai2050bed2021-01-23 09:46:34 +08006554 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006555 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006556 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6557 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006558 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6559 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6560 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006561 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6562 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006563 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006564 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006565 }
6566 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006567
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006568 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006569
6570 List<String> interfaces = new ArrayList<>();
6571 for (Network network : underlyingNetworks) {
6572 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6573 if (underlyingNai == null) continue;
6574 LinkProperties lp = underlyingNai.linkProperties;
6575 for (String iface : lp.getAllInterfaceNames()) {
6576 if (!TextUtils.isEmpty(iface)) {
6577 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006578 }
6579 }
Benedict Wong34857f82019-06-12 17:46:15 +00006580 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006581
6582 if (interfaces.isEmpty()) return null;
6583
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006584 // Must be non-null or NetworkStatsService will crash.
6585 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6586 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006587 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006588 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006589
junyulai2050bed2021-01-23 09:46:34 +08006590 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6591 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006592 }
6593
James Mattisd31bdfa2020-12-23 16:37:26 -08006594 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006595 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6596 Network[] underlyingNetworks) {
6597 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006598 if (underlyingNetworks == null && defaultNetwork != null) {
6599 // null underlying networks means to track the default.
6600 underlyingNetworks = new Network[] { defaultNetwork };
6601 }
6602 return underlyingNetworks;
6603 }
6604
6605 // Returns true iff |network| is an underlying network of |nai|.
6606 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6607 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6608 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006609 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006610 final Network[] underlying = underlyingNetworksOrDefault(
6611 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006612 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006613 }
6614
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006615 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006616 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006617 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006618 * When underlying networks change, such networks may have to update capabilities to reflect
6619 * things like the metered bit, their transports, and so on. The capabilities are calculated
6620 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006621 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006622 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006623 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006624 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006625 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006626 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006627 }
6628 }
6629 }
6630
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006631 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6632 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6633 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6634 // a VPN is not up.
6635 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6636 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6637 for (UidRange range : blockedUidRanges) {
6638 if (range.contains(uid)) return true;
6639 }
6640 return false;
6641 }
6642
6643 @Override
6644 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006645 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006646 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6647 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6648 }
6649
6650 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6651 if (DBG) {
6652 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6653 + Arrays.toString(ranges));
6654 }
6655 // Cannot use a Set since the list of UID ranges might contain duplicates.
6656 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6657 for (int i = 0; i < ranges.length; i++) {
6658 if (requireVpn) {
6659 newVpnBlockedUidRanges.add(ranges[i]);
6660 } else {
6661 newVpnBlockedUidRanges.remove(ranges[i]);
6662 }
6663 }
6664
6665 try {
6666 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6667 } catch (RemoteException | ServiceSpecificException e) {
6668 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6669 + Arrays.toString(ranges) + "): netd command failed: " + e);
6670 }
6671
Chalard Jeandf29a852023-05-29 17:02:43 +09006672 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006673 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6674 }
6675
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006676 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6677 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006678 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6679 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006680 }
6681
6682 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6683 }
6684
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006685 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006686 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006687 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006688 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006689 }
6690
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006691 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6692 return mLockdownEnabled
6693 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6694 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006695 }
6696
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006697 private NetworkAgentInfo getLegacyLockdownNai() {
6698 if (!mLockdownEnabled) {
6699 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006700 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006701 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006702 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6703 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006704
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006705 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006706 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6707 // a local variable. There is no need to make a copy because its contents cannot change.
6708 final Network[] underlying = nai.declaredUnderlyingNetworks;
6709 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006710 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006711 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006712
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006713 // The legacy lockdown VPN always uses the default network.
6714 // If the VPN's underlying network is no longer the current default network, it means that
6715 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006716 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6717 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006718 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006719 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006720 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006721 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006722
6723 return nai;
6724 };
6725
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006726 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6727 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6728 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006729 private DetailedState getLegacyLockdownState(DetailedState origState) {
6730 if (origState != DetailedState.CONNECTED) {
6731 return origState;
6732 }
6733 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6734 ? DetailedState.CONNECTING
6735 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006736 }
6737
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006738 private void filterForLegacyLockdown(NetworkInfo ni) {
6739 if (!mLockdownEnabled || !ni.isConnected()) return;
6740 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6741 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6742 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6743 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6744 // network, this time with a state of CONNECTED.
6745 //
6746 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6747 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6748 // is not too far off the truth, since an always-on VPN, when not connected, is always
6749 // trying to reconnect.
6750 if (getLegacyLockdownNai() == null) {
6751 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6752 }
6753 }
6754
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006755 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006756 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006757 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006758 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006759 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6760 return;
6761 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006762 final long ident = Binder.clearCallingIdentity();
6763 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006764 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006765 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006766 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006767 } finally {
6768 Binder.restoreCallingIdentity(ident);
6769 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006770 }
Wink Savillecb117d32013-08-29 14:57:08 -07006771
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006772 @Override
6773 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006774 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006775 final long ident = Binder.clearCallingIdentity();
6776 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006777 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006778 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006779 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6780 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006781 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006782 } finally {
6783 Binder.restoreCallingIdentity(ident);
6784 }
6785 }
6786
James Mattis02220e22021-03-13 19:27:21 -08006787 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006788 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6789 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6790 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006791 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006792 }
6793
James Mattis02220e22021-03-13 19:27:21 -08006794 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006795 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006796 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006797 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6798 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006799 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006800 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6801 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6802 }
junyulaid91e7052020-08-28 13:44:33 +08006803 }
6804
James Mattis02220e22021-03-13 19:27:21 -08006805 private void onPackageChanged(@NonNull final String packageName) {
6806 // This is necessary in case a package is added or removed, but also when it's replaced to
6807 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6808 // as one in the preferences, then it should follow the same routing as that other package,
6809 // which means updating the rules is never to be needed in this case (whether it joins or
6810 // leaves a UID with a preference).
6811 if (isMappedInOemNetworkPreference(packageName)) {
6812 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6813 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006814
6815 // Invalidates cache entry when the package is updated.
6816 synchronized (mSelfCertifiedCapabilityCache) {
6817 mSelfCertifiedCapabilityCache.remove(packageName);
6818 }
James Mattis02220e22021-03-13 19:27:21 -08006819 }
6820
6821 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006822 @Override
6823 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006824 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006825 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006826 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006827
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006828 // User should be filled for below intents, check the existence.
6829 if (user == null) {
6830 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6831 return;
6832 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006833
Lorenzo Colitticd675292021-02-04 17:32:07 +09006834 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006835 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006836 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006837 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006838 } else {
junyulaid91e7052020-08-28 13:44:33 +08006839 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006840 }
6841 }
6842 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006843
James Mattis02220e22021-03-13 19:27:21 -08006844 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6845 @Override
6846 public void onReceive(Context context, Intent intent) {
6847 ensureRunningOnConnectivityServiceThread();
6848 switch (intent.getAction()) {
6849 case Intent.ACTION_PACKAGE_ADDED:
6850 case Intent.ACTION_PACKAGE_REMOVED:
6851 case Intent.ACTION_PACKAGE_REPLACED:
6852 onPackageChanged(intent.getData().getSchemeSpecificPart());
6853 break;
6854 default:
6855 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6856 }
6857 }
6858 };
6859
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006860 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006861 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006862
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006863 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006864 public final String name;
6865 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006866 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006867 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006868
lifraf3a3492021-03-10 13:58:14 +08006869 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6870 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006871 this.name = name;
6872 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006873 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006874 mDeathRecipient = deathRecipient;
6875
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006876 if (mDeathRecipient == null) {
6877 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006878 }
6879 }
6880
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006881 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006882 try {
6883 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6884 } catch (RemoteException e) {
6885 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006886 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006887 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006888 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006889
James Mattis4fce5d12020-11-12 15:53:42 -08006890 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6891 for (int i = 0; i < requests.size(); i++) {
6892 ensureNetworkRequestHasType(requests.get(i));
6893 }
6894 }
6895
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006896 private void ensureNetworkRequestHasType(NetworkRequest request) {
6897 if (request.type == NetworkRequest.Type.NONE) {
6898 throw new IllegalArgumentException(
6899 "All NetworkRequests in ConnectivityService must have a type");
6900 }
6901 }
6902
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006903 /**
6904 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006905 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006906 */
James Mattis258ea3c2020-11-15 15:04:40 -08006907 @VisibleForTesting
6908 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006909 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6910 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006911 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006912
James Mattisa076c532020-12-02 14:12:41 -08006913 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6914 void setSatisfier(
6915 @Nullable final NetworkAgentInfo satisfier,
6916 @Nullable final NetworkRequest activeRequest) {
6917 mSatisfier = satisfier;
6918 mActiveRequest = activeRequest;
6919 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006920
James Mattisd31bdfa2020-12-23 16:37:26 -08006921 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006922 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006923 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006924 private NetworkAgentInfo mSatisfier;
6925 NetworkAgentInfo getSatisfier() {
6926 return mSatisfier;
6927 }
6928
6929 // The request in mRequests assigned to a network agent. This is null if none of the
6930 // requests in mRequests can be satisfied. This member has the constraint of only being
6931 // accessible on the handler thread.
6932 @Nullable
6933 private NetworkRequest mActiveRequest;
6934 NetworkRequest getActiveRequest() {
6935 return mActiveRequest;
6936 }
6937
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006938 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006939 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006940 @Nullable
6941 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006942
6943 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006944 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006945 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006946 final int mPid;
6947 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006948 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006949 @Nullable
6950 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006951
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006952 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006953 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006954
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006955 // Effective UID of this request. This is different from mUid when a privileged process
6956 // files a request on behalf of another UID. This UID is used to determine blocked status,
6957 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6958 // maximum limit of registered callbacks per UID.
6959 final int mAsUid;
6960
paulhu48291862021-07-14 14:53:57 +08006961 // Preference order of this request.
6962 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006963
James Mattis3ce3d3c2021-02-09 18:18:28 -08006964 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6965 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6966 // maintained for keying off of. This is only a concern when the original nri
6967 // mNetworkRequests changes which happens currently for apps that register callbacks to
6968 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6969 // that match the per-app default nri that currently tracks the calling app's uid so that
6970 // callbacks are fired at the appropriate time. When the callbacks fire,
6971 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6972 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6973 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6974 @NonNull
6975 private final NetworkRequest mNetworkRequestForCallback;
6976 NetworkRequest getNetworkRequestForCallback() {
6977 return mNetworkRequestForCallback;
6978 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006979
James Mattisd31bdfa2020-12-23 16:37:26 -08006980 /**
6981 * Get the list of UIDs this nri applies to.
6982 */
6983 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006984 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006985 // networkCapabilities.getUids() returns a defensive copy.
6986 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006987 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6988 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006989 }
6990
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006991 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6992 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006993 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006994 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006995 }
6996
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006997 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006998 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006999 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007000 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007001 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007002 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007003 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007004 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007005 mBinder = null;
7006 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007007 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007008 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007009 mPerUidCounter = getRequestCounter(this);
7010 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007011 /**
7012 * Location sensitive data not included in pending intent. Only included in
7013 * {@link NetworkCallback}.
7014 */
7015 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007016 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007017 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007018 }
7019
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007020 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007021 @Nullable final IBinder binder,
7022 @NetworkCallback.Flag int callbackFlags,
7023 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007024 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7025 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007026 }
7027
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007028 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007029 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007030 @Nullable final IBinder binder,
7031 @NetworkCallback.Flag int callbackFlags,
7032 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007033 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007034 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007035 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007036 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007037 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007038 mBinder = binder;
7039 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007040 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007041 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007042 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007043 mPerUidCounter = getRequestCounter(this);
7044 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007045 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007046 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007047 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007048 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007049 }
7050
James Mattis3ce3d3c2021-02-09 18:18:28 -08007051 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7052 @NonNull final List<NetworkRequest> r) {
7053 super();
7054 ensureAllNetworkRequestsHaveType(r);
7055 mRequests = initializeRequests(r);
7056 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007057 final NetworkAgentInfo satisfier = nri.getSatisfier();
7058 if (null != satisfier) {
7059 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7060 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007061 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007062 // As this code creates a new NRI with a new set of requests, figure out which of
7063 // the list of requests should be the active request. It is always the first
7064 // request of the list that can be satisfied by the satisfier since the order of
7065 // requests is a priority order.
7066 // Note even in the presence of a satisfier there may not be an active request,
7067 // when the satisfier is the no-service network.
7068 NetworkRequest activeRequest = null;
7069 for (final NetworkRequest candidate : r) {
7070 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7071 activeRequest = candidate;
7072 break;
7073 }
7074 }
7075 setSatisfier(satisfier, activeRequest);
7076 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007077 mMessenger = nri.mMessenger;
7078 mBinder = nri.mBinder;
7079 mPid = nri.mPid;
7080 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007081 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007082 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007083 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007084 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007085 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007086 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007087 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007088 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007089 }
7090
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007091 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007092 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007093 }
7094
paulhue9913722021-05-26 15:19:20 +08007095 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007096 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007097 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007098 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007099 }
7100
James Mattis2516da32021-01-31 17:06:19 -08007101 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7102 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7103 // false.
7104 boolean isBeingSatisfied() {
7105 return (null != mSatisfier && null != mActiveRequest);
7106 }
7107
James Mattis3d229892020-11-16 16:46:28 -08007108 boolean isMultilayerRequest() {
7109 return mRequests.size() > 1;
7110 }
7111
James Mattis45d81842021-01-10 14:24:24 -08007112 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7113 // Creating a defensive copy to prevent the sender from modifying the list being
7114 // reflected in the return value of this method.
7115 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007116 return Collections.unmodifiableList(tempRequests);
7117 }
7118
James Mattisb1392002021-03-31 13:57:52 -07007119 void linkDeathRecipient() {
7120 if (null != mBinder) {
7121 try {
7122 mBinder.linkToDeath(this, 0);
7123 } catch (RemoteException e) {
7124 binderDied();
7125 }
7126 }
7127 }
7128
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007129 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007130 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007131 try {
7132 mBinder.unlinkToDeath(this, 0);
7133 } catch (NoSuchElementException e) {
7134 // Temporary workaround for b/194394697 pending analysis of additional logs
7135 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7136 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007137 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007138 }
7139
paulhu48291862021-07-14 14:53:57 +08007140 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7141 // Compare two preference orders.
7142 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007143 }
7144
paulhu48291862021-07-14 14:53:57 +08007145 int getPreferenceOrderForNetd() {
7146 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7147 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7148 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007149 }
paulhu48291862021-07-14 14:53:57 +08007150 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007151 }
7152
James Mattis4fce5d12020-11-12 15:53:42 -08007153 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007154 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007155 // As an immutable collection, mRequests cannot change by the time the
7156 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7157 // is acceptable. Use handleReleaseNetworkRequest and not directly
7158 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7159 // the app already unregistered the request.
7160 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7161 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007162 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007163
James Mattis4fce5d12020-11-12 15:53:42 -08007164 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007165 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007166 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7167 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007168 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007169 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007170 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007171 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007172 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007173 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007174 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007175 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007176 }
7177
Junyu Lai00d92df2022-07-05 11:01:52 +08007178 // Keep backward compatibility since the ServiceSpecificException is used by
7179 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7180 public static class RequestInfoPerUidCounter extends PerUidCounter {
7181 RequestInfoPerUidCounter(int maxCountPerUid) {
7182 super(maxCountPerUid);
7183 }
7184
7185 @Override
7186 public synchronized void incrementCountOrThrow(int uid) {
7187 try {
7188 super.incrementCountOrThrow(uid);
7189 } catch (IllegalStateException e) {
7190 throw new ServiceSpecificException(
7191 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7192 "Uid " + uid + " exceeded its allotted requests limit");
7193 }
7194 }
7195
7196 @Override
7197 public synchronized void decrementCountOrThrow(int uid) {
7198 throw new UnsupportedOperationException("Use decrementCount instead.");
7199 }
7200
7201 public synchronized void decrementCount(int uid) {
7202 try {
7203 super.decrementCountOrThrow(uid);
7204 } catch (IllegalStateException e) {
7205 logwtf("Exception when decrement per uid request count: ", e);
7206 }
7207 }
7208 }
7209
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007210 // This checks that the passed capabilities either do not request a
7211 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007212 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007213 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007214 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007215 throw new SecurityException("Insufficient permissions to request a specific SSID");
7216 }
paulhu1a407652019-03-22 16:35:06 +08007217
7218 if (nc.hasSignalStrength()
7219 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7220 throw new SecurityException(
7221 "Insufficient permissions to request a specific signal strength");
7222 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007223 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007224
junyulai2217bec2021-04-14 23:33:31 +08007225 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007226 enforceNetworkFactoryPermission();
7227 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007228 }
7229
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007230 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007231 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007232 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007233 // mNetworkRequests may contain the same value multiple times in case of
7234 // multilayer requests. It won't matter in this case because the thresholds
7235 // will then be the same and be deduplicated as they enter the `thresholds` set.
7236 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007237 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7238 for (final NetworkRequest req : nri.mRequests) {
7239 if (req.networkCapabilities.hasSignalStrength()
7240 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7241 thresholds.add(req.networkCapabilities.getSignalStrength());
7242 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007243 }
7244 }
7245 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007246 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007247 }
7248
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007249 private void updateSignalStrengthThresholds(
7250 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007251 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007252
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007253 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007254 String detail;
7255 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7256 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7257 } else {
7258 detail = reason;
7259 }
7260 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007261 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007262 }
7263
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007264 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007265 }
7266
Chalard Jeandd421992021-12-16 23:16:02 +09007267 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007268 if (nc == null) {
7269 return;
7270 }
7271 NetworkSpecifier ns = nc.getNetworkSpecifier();
7272 if (ns == null) {
7273 return;
7274 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007275 if (ns instanceof MatchAllNetworkSpecifier) {
7276 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7277 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007278 }
7279
Chalard Jeandd421992021-12-16 23:16:02 +09007280 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007281 ensureValidNetworkSpecifier(nc);
7282 if (nc.isPrivateDnsBroken()) {
7283 throw new IllegalArgumentException("Can't request broken private DNS");
7284 }
Chalard Jeande665262022-02-25 16:12:12 +09007285 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007286 throw new IllegalArgumentException("Can't request access UIDs");
7287 }
lucasline117e2e2019-10-22 18:27:33 +08007288 }
7289
Chalard Jeandd421992021-12-16 23:16:02 +09007290 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7291 ensureListenableCapabilities(nc);
7292 final String badCapability = nc.describeFirstNonRequestableCapability();
7293 if (badCapability != null) {
7294 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7295 }
7296 }
7297
Chiachang Wang3bc52762021-11-25 14:17:57 +08007298 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7299 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007300 private boolean isTargetSdkAtleast(int version, int callingUid,
7301 @NonNull String callingPackageName) {
7302 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007303 final PackageManager pm =
7304 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007305 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007306 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007307 if (callingVersion < version) return false;
7308 } catch (PackageManager.NameNotFoundException e) { }
7309 return true;
7310 }
7311
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007312 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007313 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007314 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007315 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007316 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007317 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007318 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7319 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007320 throw new SecurityException("Insufficient permissions to specify legacy type");
7321 }
markchienfac84a22020-03-18 21:16:15 +08007322 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007323 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007324 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007325 // Privileged callers can track the default network of another UID by passing in a UID.
7326 if (asUid != Process.INVALID_UID) {
7327 enforceSettingsPermission();
7328 } else {
7329 asUid = callingUid;
7330 }
junyulaiad010792021-01-11 16:53:38 +08007331 final NetworkRequest.Type reqType;
7332 try {
7333 reqType = NetworkRequest.Type.values()[reqTypeInt];
7334 } catch (ArrayIndexOutOfBoundsException e) {
7335 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7336 }
7337 switch (reqType) {
7338 case TRACK_DEFAULT:
7339 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007340 // is unused and will be replaced by ones appropriate for the UID (usually, the
7341 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007342 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007343 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007344 enforceAccessPermission();
7345 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007346 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007347 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007348 networkCapabilities = new NetworkCapabilities(defaultNc);
7349 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007350 case BACKGROUND_REQUEST:
7351 enforceNetworkStackOrSettingsPermission();
7352 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007353 case REQUEST:
7354 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7355 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007356 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007357 // TODO: this is incorrect. We mark the request as metered or not depending on
7358 // the state of the app when the request is filed, but we never change the
7359 // request if the app changes network state. http://b/29964605
7360 enforceMeteredApnPolicy(networkCapabilities);
7361 break;
junyulai1b1c8742021-03-12 20:05:08 +08007362 case LISTEN_FOR_BEST:
7363 enforceAccessPermission();
7364 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7365 break;
junyulaiad010792021-01-11 16:53:38 +08007366 default:
7367 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007368 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007369 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007370 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007371 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007372
junyulai1b1c8742021-03-12 20:05:08 +08007373 // Enforce FOREGROUND if the caller does not have permission to use background network.
7374 if (reqType == LISTEN_FOR_BEST) {
7375 restrictBackgroundRequestForCaller(networkCapabilities);
7376 }
7377
7378 // Set the UID range for this request to the single UID of the requester, unless the
7379 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007380 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7381 // are no visible methods to set the UIDs, an app could use reflection to try and get
7382 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007383 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007384 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7385 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007386
Etan Cohen85000162017-02-05 10:42:27 -08007387 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007388 throw new IllegalArgumentException("Bad timeout specified");
7389 }
Etan Cohen9786d922015-11-18 10:56:15 -08007390
James Mattis3ce3d3c2021-02-09 18:18:28 -08007391 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007392 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007393 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007394 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007395 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007396 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007397
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007398 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7399 // copied from the default request above. (This is necessary to ensure, for example, that
7400 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7401 // changes don't alter request matching.
7402 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7403 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007404 throw new IllegalStateException(
7405 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007406 + networkCapabilities + " vs. " + defaultNc);
7407 }
7408
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007409 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007410 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007411 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007412 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007413 }
7414 return networkRequest;
7415 }
7416
James Mattis3ce3d3c2021-02-09 18:18:28 -08007417 /**
7418 * Return the nri to be used when registering a network request. Specifically, this is used with
7419 * requests registered to track the default request. If there is currently a per-app default
7420 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7421 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007422 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7423 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007424 * @param nr the network request for the nri.
7425 * @param msgr the messenger for the nri.
7426 * @param binder the binder for the nri.
7427 * @param callingAttributionTag the calling attribution tag for the nri.
7428 * @return the nri to register.
7429 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007430 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007431 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007432 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007433 @Nullable String callingAttributionTag) {
7434 final List<NetworkRequest> requests;
7435 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7436 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007437 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007438 } else {
7439 requests = Collections.singletonList(nr);
7440 }
Roshan Pius951c0032020-12-22 15:10:42 -08007441 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007442 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007443 }
7444
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007445 private boolean shouldCheckCapabilitiesDeclaration(
7446 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7447 @NonNull final String callingPackageName) {
7448 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7449 // Only run the check if the change is enabled.
7450 if (!mDeps.isChangeEnabled(
7451 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7452 callingPackageName, user)) {
7453 return false;
7454 }
7455
7456 return networkCapabilities.hasCapability(
7457 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7458 || networkCapabilities.hasCapability(
7459 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7460 }
7461
7462 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
7463 @NonNull final NetworkCapabilities networkCapabilities) {
7464 // This check is added to fix the linter error for "current min is 30", which is not going
7465 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007466 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007467 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7468 return;
7469 }
7470 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007471 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007472 try {
7473 synchronized (mSelfCertifiedCapabilityCache) {
7474 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7475 callerPackageName);
7476 if (applicationNetworkCapabilities == null) {
7477 final PackageManager packageManager = mContext.getPackageManager();
7478 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7479 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7480 callerPackageName
7481 );
7482 final XmlResourceParser parser = packageManager
7483 .getResourcesForApplication(callerPackageName)
7484 .getXml(networkSliceProperty.getResourceId());
7485 applicationNetworkCapabilities =
7486 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7487 mSelfCertifiedCapabilityCache.put(callerPackageName,
7488 applicationNetworkCapabilities);
7489 }
7490
7491 }
7492 } catch (PackageManager.NameNotFoundException ne) {
7493 throw new SecurityException(
7494 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7495 + " property");
7496 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7497 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007498 } finally {
7499 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007500 }
7501
7502 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7503 networkCapabilities);
7504 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007505 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007506 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007507 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7508 callingPackageName)) {
7509 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7510 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007511 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007512 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7513 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7514 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7515 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007516 }
junyulai96bd9fe2022-03-08 17:36:42 +08007517 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007518 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007519 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007520 }
7521 }
7522
fenglu3f357402015-03-20 11:29:56 -07007523 @Override
fenglub00f4882015-04-21 17:12:05 -07007524 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007525 enforceAccessPermission();
7526 NetworkAgentInfo nai = null;
7527 if (network == null) {
7528 return false;
7529 }
7530 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007531 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007532 }
7533 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007534 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007535 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007536 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007537 Integer uidReqs = mBandwidthRequests.get(uid);
7538 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007539 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007540 }
7541 mBandwidthRequests.put(uid, ++uidReqs);
7542 }
fenglu3f357402015-03-20 11:29:56 -07007543 return true;
7544 }
7545 return false;
7546 }
7547
Felipe Leme0a5ae422016-06-20 16:36:29 -07007548 private boolean isSystem(int uid) {
7549 return uid < Process.FIRST_APPLICATION_UID;
7550 }
fenglu3f357402015-03-20 11:29:56 -07007551
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007552 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007553 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007554 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007555 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007556 return;
7557 }
Hugo Benichi39621362017-02-11 17:04:43 +09007558 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7559 // Policy already enforced.
7560 return;
7561 }
paulhuaf50d7d2020-12-24 19:47:34 +08007562 final long ident = Binder.clearCallingIdentity();
7563 try {
7564 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7565 // If UID is restricted, don't allow them to bring up metered APNs.
7566 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7567 }
7568 } finally {
7569 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007570 }
7571 }
7572
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007573 @Override
7574 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007575 PendingIntent operation, @NonNull String callingPackageName,
7576 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007577 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007578 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007579 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007580 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007581 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007582 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007583 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007584 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007585 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007586 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7587 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007588
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007589 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007590 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007591 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7592 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007593 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007594 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7595 nri));
7596 return networkRequest;
7597 }
7598
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007599 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7600 mHandler.sendMessageDelayed(
7601 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007602 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007603 }
7604
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007605 @Override
7606 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007607 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007608 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007609 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007610 }
7611
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007612 // In order to implement the compatibility measure for pre-M apps that call
7613 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7614 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7615 // This ensures it has permission to do so.
7616 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7617 if (nc == null) {
7618 return false;
7619 }
7620 int[] transportTypes = nc.getTransportTypes();
7621 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7622 return false;
7623 }
7624 try {
7625 mContext.enforceCallingOrSelfPermission(
7626 android.Manifest.permission.ACCESS_WIFI_STATE,
7627 "ConnectivityService");
7628 } catch (SecurityException e) {
7629 return false;
7630 }
7631 return true;
7632 }
7633
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007634 @Override
7635 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007636 Messenger messenger, IBinder binder,
7637 @NetworkCallback.Flag int callbackFlags,
7638 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007639 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007640 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7641 enforceAccessPermission();
7642 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007643
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007644 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007645 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007646 Binder.getCallingPid(), callingUid, callingPackageName);
7647 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007648 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7649 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7650 // onLost and onAvailable callbacks when networks move in and out of the background.
7651 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7652 // can't request networks.
7653 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007654 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007655
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007656 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007657 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007658 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007659 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007660 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007661 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007662
7663 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7664 return networkRequest;
7665 }
7666
7667 @Override
7668 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007669 PendingIntent operation, @NonNull String callingPackageName,
7670 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007671 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007672 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007673 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7674 enforceAccessPermission();
7675 }
Chalard Jeandd421992021-12-16 23:16:02 +09007676 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007677 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007678 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007679 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007680 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007681
7682 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007683 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007684 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7685 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007686 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007687
WeiZhang1cc3f172021-06-03 19:02:04 -05007688 mHandler.sendMessage(mHandler.obtainMessage(
7689 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007690 }
7691
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007692 /** Returns the next Network provider ID. */
7693 public final int nextNetworkProviderId() {
7694 return mNextNetworkProviderId.getAndIncrement();
7695 }
7696
Erik Kline0c04b742016-07-07 16:50:58 +09007697 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007698 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007699 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007700 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007701 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007702 }
7703
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007704 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7705 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007706 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7707 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7708 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007709 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007710 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007711 return;
7712 }
7713
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007714 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7715 mNetworkProviderInfos.put(npi.messenger, npi);
7716 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007717 }
7718
7719 @Override
7720 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007721 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007722 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007723 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007724 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007725 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7726 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007727 }
7728
7729 @Override
7730 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007731 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007732 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007733 }
7734
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007735 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007736 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007737 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7738 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007739 Objects.requireNonNull(score);
7740 Objects.requireNonNull(caps);
7741 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007742 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007743 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007744 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7745 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007746 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7747 }
7748
Chalard Jeanbb902a52021-08-18 01:35:19 +09007749 private void updateOfferScore(final NetworkOffer offer) {
7750 final boolean yieldToBadWiFi =
7751 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7752 final NetworkOffer newOffer = new NetworkOffer(
7753 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7754 offer.caps, offer.callback, offer.providerId);
7755 if (offer.equals(newOffer)) return;
7756 handleRegisterNetworkOffer(newOffer);
7757 }
7758
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007759 @Override
7760 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007761 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007762 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7763 }
7764
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007765 private void handleUnregisterNetworkProvider(Messenger messenger) {
7766 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7767 if (npi == null) {
7768 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007769 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007770 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007771 // Unregister all the offers from this provider
7772 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7773 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007774 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007775 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7776 toRemove.add(noi);
7777 }
7778 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007779 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007780 handleUnregisterNetworkOffer(noi);
7781 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007782 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007783 }
7784
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007785 @Override
James Mattisf7027322020-12-13 16:28:14 -08007786 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007787 if (request.hasTransport(TRANSPORT_TEST)) {
7788 enforceNetworkFactoryOrTestNetworksPermission();
7789 } else {
7790 enforceNetworkFactoryPermission();
7791 }
James Mattisf7027322020-12-13 16:28:14 -08007792 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7793 if (nri != null) {
7794 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7795 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7796 mHandler.post(() -> handleReleaseNetworkRequest(
7797 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7798 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007799 }
7800
Paul Jensen1f567382015-02-13 14:18:39 -05007801 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7802 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007803 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007804 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007805 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007806 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007807 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007808
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007809 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007810 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007811 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007812
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007813 // UID ranges for users that are currently blocked by VPNs.
7814 // This array is accessed and iterated on multiple threads without holding locks, so its
7815 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7816 // (on the handler thread).
7817 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7818
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007819 // Must only be accessed on the handler thread
7820 @NonNull
7821 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7822
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007823 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007824 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007825
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007826 // Current OEM network preferences. This object must only be written to on the handler thread.
7827 // Since it is immutable and always non-null, other threads may read it if they only care
7828 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007829 @NonNull
7830 private OemNetworkPreferences mOemNetworkPreferences =
7831 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007832 // Current per-profile network preferences. This object follows the same threading rules as
7833 // the OEM network preferences above.
7834 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007835 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7836 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007837
lucaslin3ba7cc22022-12-19 02:35:33 +00007838 // Current VPN network preferences. This object follows the same threading rules as the OEM
7839 // network preferences above.
7840 @NonNull
7841 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7842 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7843
paulhu51f77dc2021-06-07 02:34:20 +00007844 // A set of UIDs that should use mobile data preferentially if available. This object follows
7845 // the same threading rules as the OEM network preferences above.
7846 @NonNull
7847 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7848
James Mattiscb1e0362021-04-06 17:07:42 -07007849 // OemNetworkPreferences activity String log entries.
7850 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7851 @NonNull
7852 private final LocalLog mOemNetworkPreferencesLogs =
7853 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7854
James Mattis02220e22021-03-13 19:27:21 -08007855 /**
7856 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7857 * @param packageName the package name to check existence of a mapping for.
7858 * @return true if a mapping exists, false otherwise
7859 */
7860 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7861 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7862 }
7863
James Mattise3ef1912020-12-20 11:09:58 -08007864 // The always-on request for an Internet-capable network that apps without a specific default
7865 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007866 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007867 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007868 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007869 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007870 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007871 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007872 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007873
James Mattisd31bdfa2020-12-23 16:37:26 -08007874 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7875 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7876 }
7877
7878 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007879 * Return the default network request currently tracking the given uid.
7880 * @param uid the uid to check.
7881 * @return the NetworkRequestInfo tracking the given uid.
7882 */
7883 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007884 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007885 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007886 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007887 // Checking the first request is sufficient as only multilayer requests will have more
7888 // than one request and for multilayer, all requests will track the same uids.
7889 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007890 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007891 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007892 highestPriorityNri = nri;
7893 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007894 }
7895 }
paulhuaa0743d2021-05-26 21:56:03 +08007896 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007897 }
7898
7899 /**
7900 * Get a copy of the network requests of the default request that is currently tracking the
7901 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007902 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7903 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007904 * @param requestorUid the uid to check the default for.
7905 * @param requestorPackageName the requestor's package name.
7906 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7907 */
7908 @NonNull
7909 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007910 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007911 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007912 getDefaultRequestTrackingUid(asUid).mRequests,
7913 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007914 }
7915
7916 /**
7917 * Copy the given nri's NetworkRequest collection.
7918 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007919 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7920 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007921 * @param requestorUid the uid to set on the copied collection.
7922 * @param requestorPackageName the package name to set on the copied collection.
7923 * @return the copied NetworkRequest collection.
7924 */
7925 @NonNull
7926 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007927 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7928 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007929 final List<NetworkRequest> requests = new ArrayList<>();
7930 for (final NetworkRequest nr : requestsToCopy) {
7931 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007932 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007933 nr.legacyType, nextNetworkRequestId(), nr.type));
7934 }
7935 return requests;
7936 }
7937
7938 @NonNull
7939 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007940 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7941 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007942 // These capabilities are for a TRACK_DEFAULT callback, so:
7943 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7944 // mDefaultRequest and a per-UID default request.
7945 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007946 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007947 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007948 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7949 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007950 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007951 restrictRequestUidsForCallerAndSetRequestorInfo(
7952 netCap, requestorUid, requestorPackageName);
7953 return netCap;
7954 }
7955
7956 /**
7957 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7958 * @param nr the network request to check for equality against.
7959 * @return the nri if one exists, null otherwise.
7960 */
7961 @Nullable
7962 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7963 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7964 if (nri.getNetworkRequestForCallback().equals(nr)) {
7965 return nri;
7966 }
7967 }
7968 return null;
7969 }
7970
7971 /**
7972 * Check if an nri is currently being managed by per-app default networking.
7973 * @param nri the nri to check.
7974 * @return true if this nri is currently being managed by per-app default networking.
7975 */
7976 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7977 // nri.mRequests.get(0) is only different from the original request filed in
7978 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7979 // functionality therefore if these two don't match, it means this particular nri is
7980 // currently being managed by a per-app default.
7981 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7982 }
7983
7984 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007985 * Determine if an nri is a managed default request that disallows default networking.
7986 * @param nri the request to evaluate
7987 * @return true if device-default networking is disallowed
7988 */
7989 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7990 // Check if this nri is a managed default that supports the default network at its
7991 // lowest priority request.
7992 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7993 final NetworkCapabilities lowestPriorityNetCap =
7994 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7995 return isPerAppDefaultRequest(nri)
7996 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7997 lowestPriorityNetCap));
7998 }
7999
Erik Kline05f2b402015-04-30 12:58:40 +09008000 // Request used to optionally keep mobile data active even when higher
8001 // priority networks like Wi-Fi are active.
8002 private final NetworkRequest mDefaultMobileDataRequest;
8003
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008004 // Request used to optionally keep wifi data active even when higher
8005 // priority networks like ethernet are active.
8006 private final NetworkRequest mDefaultWifiRequest;
8007
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008008 // Request used to optionally keep vehicle internal network always active
8009 private final NetworkRequest mDefaultVehicleRequest;
8010
James Mattisd31bdfa2020-12-23 16:37:26 -08008011 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8012 // network with no service. This NAI should never be matched against, nor should any public API
8013 // ever return the associated network. For this reason, this NAI is not in the list of available
8014 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8015 // default requests that don't support using the device default network which will ultimately
8016 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8017 @VisibleForTesting
8018 final NetworkAgentInfo mNoServiceNetwork;
8019
Chalard Jean5b409c72021-02-04 13:12:59 +09008020 // The NetworkAgentInfo currently satisfying the default request, if any.
8021 private NetworkAgentInfo getDefaultNetwork() {
8022 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008023 }
8024
James Mattis2516da32021-01-31 17:06:19 -08008025 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008026 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008027 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8028 // Currently, all network requests will have the same uids therefore checking the first
8029 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008030 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008031 if (null == uids) {
8032 continue;
8033 }
8034 for (final UidRange range : uids) {
8035 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008036 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008037 highestPriorityNri = nri;
8038 }
James Mattis2516da32021-01-31 17:06:19 -08008039 }
8040 }
8041 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008042 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008043 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008044 }
8045
Varun Ananddf569952019-02-06 10:13:38 -08008046 @Nullable
8047 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8048 return nai != null ? nai.network : null;
8049 }
8050
8051 private void ensureRunningOnConnectivityServiceThread() {
8052 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8053 throw new IllegalStateException(
8054 "Not running on ConnectivityService thread: "
8055 + Thread.currentThread().getName());
8056 }
8057 }
8058
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008059 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008060 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8061 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008062 }
8063
Chalard Jean29d06db2018-05-02 21:14:54 +09008064 /**
Chalard Jeane0aaca52023-10-17 13:23:07 +09008065 * Returns whether local agents are supported on this device.
8066 *
8067 * Local agents are supported from U on TVs, and from V on all devices.
8068 */
8069 @VisibleForTesting
8070 public boolean areLocalAgentsSupported() {
8071 final PackageManager pm = mContext.getPackageManager();
8072 // Local agents are supported starting on U on TVs and on V on everything else.
8073 return mDeps.isAtLeastV() || (mDeps.isAtLeastU() && pm.hasSystemFeature(FEATURE_LEANBACK));
8074 }
8075
8076 /**
Chalard Jean29d06db2018-05-02 21:14:54 +09008077 * Register a new agent with ConnectivityService to handle a network.
8078 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008079 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008080 * @param networkInfo the initial info associated with this network. It can be updated later :
8081 * see {@link #updateNetworkInfo}.
8082 * @param linkProperties the initial link properties of this network. They can be updated
8083 * later : see {@link #updateLinkProperties}.
8084 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008085 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008086 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008087 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008088 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008089 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008090 */
Anton Kulakov6eea22b2023-10-13 15:04:01 +00008091 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
8092 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
8093 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09008094 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008095 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8096 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8097 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008098 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008099 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008100 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008101 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008102 } else {
8103 enforceNetworkFactoryPermission();
8104 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09008105 final boolean hasLocalCap =
8106 networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
8107 if (hasLocalCap && !areLocalAgentsSupported()) {
8108 // Before U, netd doesn't support PHYSICAL_LOCAL networks so this can't work.
8109 throw new IllegalArgumentException("Local agents are not supported in this version");
8110 }
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008111
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008112 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008113 final long token = Binder.clearCallingIdentity();
8114 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008115 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Anton Kulakov6eea22b2023-10-13 15:04:01 +00008116 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008117 } finally {
8118 Binder.restoreCallingIdentity(token);
8119 }
8120 }
8121
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008122 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008123 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Anton Kulakov6eea22b2023-10-13 15:04:01 +00008124 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09008125 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008126
Chalard Jeandbc46952022-02-02 00:14:18 +09008127 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8128 // and mutate them at any time.
8129 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8130 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8131 final LinkProperties lpCopy = new LinkProperties(linkProperties);
8132
Chalard Jean366c5252022-01-25 18:27:53 +09008133 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008134 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008135 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8136 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008137 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008138 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Anton Kulakov6eea22b2023-10-13 15:04:01 +00008139 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
8140 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
8141 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008142
Chalard Jeandbc46952022-02-02 00:14:18 +09008143 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008144 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008145 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008146 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008147 mDeps.getNetworkStack().makeNetworkMonitor(
8148 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008149 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8150 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008151 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008152 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008153 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008154 }
8155
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008156 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008157 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008158 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008159 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008160 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008161 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8162 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8163 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008164
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008165 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008166
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008167 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008168 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008169 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008170 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008171
8172 try {
8173 networkMonitor.start();
8174 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008175 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008176 }
Chalard Jean366c5252022-01-25 18:27:53 +09008177
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008178 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008179 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008180 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008181 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008182 }
8183
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008184 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8185 @NonNull public final NetworkOffer offer;
8186
8187 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8188 this.offer = offer;
8189 }
8190
8191 @Override
8192 public void binderDied() {
8193 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8194 }
8195 }
8196
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008197 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8198 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8199 if (npi.providerId == providerId) return true;
8200 }
8201 return false;
8202 }
8203
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008204 /**
8205 * Register or update a network offer.
8206 * @param newOffer The new offer. If the callback member is the same as an existing
8207 * offer, it is an update of that offer.
8208 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008209 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008210 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8211 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008212 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008213 // This may actually happen if a provider updates its score or registers and then
8214 // immediately unregisters. The offer would still be in the handler queue, but the
8215 // provider would have been removed.
8216 if (DBG) log("Received offer from an unregistered provider");
8217 return;
8218 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008219 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8220 if (null != existingOffer) {
8221 handleUnregisterNetworkOffer(existingOffer);
8222 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008223 if (DBG) {
8224 // handleUnregisterNetworkOffer has already logged the old offer
8225 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8226 }
8227 } else {
8228 if (DBG) {
8229 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8230 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008231 }
8232 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8233 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008234 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008235 } catch (RemoteException e) {
8236 noi.binderDied();
8237 return;
8238 }
8239 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008240 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008241 }
8242
8243 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8244 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008245 if (DBG) {
8246 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8247 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008248
8249 // If the provider removes the offer and dies immediately afterwards this
8250 // function may be called twice in a row, but the array will no longer contain
8251 // the offer.
8252 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008253 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008254 }
8255
8256 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8257 @NonNull final INetworkOfferCallback callback) {
8258 ensureRunningOnConnectivityServiceThread();
8259 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008260 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008261 }
8262 return null;
8263 }
8264
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008265 /**
8266 * Called when receiving LinkProperties directly from a NetworkAgent.
8267 * Stores into |nai| any data coming from the agent that might also be written to the network's
8268 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8269 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008270 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008271 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008272 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8273 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008274 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008275 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008276 }
8277
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008278 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008279 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008280 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008281
Lorenzo Colittid523d142020-04-01 20:16:30 +09008282 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8283 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8284 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008285 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008286
Suprabh Shukla1e312032023-01-24 03:36:37 -08008287 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008288
8289 // update filtering rules, need to happen after the interface update so netd knows about the
8290 // new interface (the interface name -> index map becomes initialized)
8291 updateVpnFiltering(newLp, oldLp, networkAgent);
8292
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008293 updateMtu(newLp, oldLp);
8294 // TODO - figure out what to do for clat
8295// for (LinkProperties lp : newLp.getStackedLinks()) {
8296// updateMtu(lp, null);
8297// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008298 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008299 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008300 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8301 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008302
Erik Klineb9888902016-04-05 13:30:49 +09008303 updateRoutes(newLp, oldLp, netId);
8304 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008305 // Make sure LinkProperties represents the latest private DNS status.
8306 // This does not need to be done before updateDnses because the
8307 // LinkProperties are not the source of the private DNS configuration.
8308 // updateDnses will fetch the private DNS configuration from DnsManager.
8309 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008310
Chalard Jean5b409c72021-02-04 13:12:59 +09008311 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008312 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008313 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008314 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008315 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008316
8317 updateWakeOnLan(newLp);
8318
Hai Shalome58bdc62021-01-11 18:45:34 -08008319 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8320 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8321 // does, it needs to be merged here.
8322 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8323 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008324
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008325 // TODO - move this check to cover the whole function
8326 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008327 synchronized (networkAgent) {
8328 networkAgent.linkProperties = newLp;
8329 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008330 // Start or stop DNS64 detection and 464xlat according to network state.
8331 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008332 // Notify NSS when relevant events happened. Currently, NSS only cares about
8333 // interface changed to update clat interfaces accounting.
8334 final boolean interfacesChanged = oldLp == null
8335 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8336 if (interfacesChanged) {
8337 notifyIfacesChangedForNetworkStats();
8338 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008339 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8340 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008341 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008342 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008343
8344 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008345 }
8346
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008347 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8348 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8349 }
8350
Hai Shalome58bdc62021-01-11 18:45:34 -08008351 /**
8352 * @param naData captive portal data from NetworkAgent
8353 * @param apiData captive portal data from capport API
8354 */
8355 @Nullable
8356 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8357 CaptivePortalData apiData) {
8358 if (naData == null || apiData == null) {
8359 return naData == null ? apiData : naData;
8360 }
8361 final CaptivePortalData.Builder captivePortalBuilder =
8362 new CaptivePortalData.Builder(naData);
8363
8364 if (apiData.isCaptive()) {
8365 captivePortalBuilder.setCaptive(true);
8366 }
8367 if (apiData.isSessionExtendable()) {
8368 captivePortalBuilder.setSessionExtendable(true);
8369 }
8370 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8371 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8372 // otherwise data would be inconsistent. Prefer the capport API info if present,
8373 // as it can generally be refreshed more often.
8374 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8375 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8376 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8377 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8378 // No source has time / bytes remaining information: surface the newest refresh time
8379 // for other fields
8380 captivePortalBuilder.setRefreshTime(
8381 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8382 }
8383
Hai Shalom7c6ab402021-02-04 19:34:06 -08008384 // Prioritize the user portal URL from the network agent if the source is authenticated.
8385 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8386 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8387 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8388 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008389 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008390 // Prioritize the venue information URL from the network agent if the source is
8391 // authenticated.
8392 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8393 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8394 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8395 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008396 }
8397 return captivePortalBuilder.build();
8398 }
8399
Suprabh Shukla53e16392023-04-26 18:47:36 -07008400 @VisibleForTesting
8401 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008402 // This needs to be kept in sync and backwards compatible with the decoding logic in
8403 // NetdEventListenerService, which is non-mainline code.
8404 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8405 }
8406
Suprabh Shukla75642282023-04-25 23:15:43 -07008407 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8408 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8409 return true;
8410 }
8411 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8412 return true;
8413 }
8414 return false;
8415 }
8416
Suprabh Shukla1e312032023-01-24 03:36:37 -08008417 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008418 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008419 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008420 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008421 return;
8422 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008423
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008424 // Mask/mark of zero will not detect anything interesting.
8425 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008426 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008427 return;
8428 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008429
Suprabh Shukla1e312032023-01-24 03:36:37 -08008430 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008431 try {
8432 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008433 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008434 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008435 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008436 }
8437 } catch (Exception e) {
8438 loge("Exception modifying wakeup packet monitoring: " + e);
8439 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008440 }
8441
Junyu Lai970963e2022-10-25 15:46:47 +08008442 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008443 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008444 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008445 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008446 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008447 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008448 for (final String iface : interfaceDiff.added) {
8449 try {
8450 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008451 mNetd.networkAddInterface(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008452 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008453 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008454 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008455 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008456 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008457 }
Paul Jensenbff73492014-04-28 10:33:11 -04008458 }
8459 }
Chalard Jean9589e722019-11-19 19:03:53 +09008460 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008461 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008462 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008463 wakeupModifyInterface(iface, nai, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008464 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008465 } catch (Exception e) {
8466 loge("Exception removing interface: " + e);
8467 }
8468 }
8469 }
8470
Tyler Weare4314862019-12-05 14:55:30 -08008471 // TODO: move to frameworks/libs/net.
8472 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
8473 final String nextHop;
8474
8475 switch (route.getType()) {
8476 case RouteInfo.RTN_UNICAST:
8477 if (route.hasGateway()) {
8478 nextHop = route.getGateway().getHostAddress();
8479 } else {
8480 nextHop = INetd.NEXTHOP_NONE;
8481 }
8482 break;
8483 case RouteInfo.RTN_UNREACHABLE:
8484 nextHop = INetd.NEXTHOP_UNREACHABLE;
8485 break;
8486 case RouteInfo.RTN_THROW:
8487 nextHop = INetd.NEXTHOP_THROW;
8488 break;
8489 default:
8490 nextHop = INetd.NEXTHOP_NONE;
8491 break;
8492 }
8493
8494 final RouteInfoParcel rip = new RouteInfoParcel();
8495 rip.ifName = route.getInterface();
8496 rip.destination = route.getDestination().toString();
8497 rip.nextHop = nextHop;
8498 rip.mtu = route.getMtu();
8499
8500 return rip;
8501 }
8502
Paul Jensene0fd4a82014-08-06 15:51:33 -04008503 /**
8504 * Have netd update routes from oldLp to newLp.
8505 * @return true if routes changed between oldLp and newLp
8506 */
Junyu Lai970963e2022-10-25 15:46:47 +08008507 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8508 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008509 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008510 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8511 new CompareOrUpdateResult<>(
8512 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008513 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008514 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008515
8516 // add routes before removing old in case it helps with continuous connectivity
8517
Chalard Jean9dd11612018-06-04 16:52:49 +09008518 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008519 for (RouteInfo route : routeDiff.added) {
8520 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008521 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008522 try {
Tyler Weare4314862019-12-05 14:55:30 -08008523 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008524 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008525 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008526 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008527 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008528 }
8529 }
8530 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008531 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008532 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008533 try {
Tyler Weare4314862019-12-05 14:55:30 -08008534 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008535 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008536 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008537 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008538 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008539 }
8540 }
8541
8542 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008543 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008544 try {
Tyler Weare4314862019-12-05 14:55:30 -08008545 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008546 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08008547 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008548 }
8549 }
Tyler Weare4314862019-12-05 14:55:30 -08008550
8551 for (RouteInfo route : routeDiff.updated) {
8552 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8553 try {
8554 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
8555 } catch (Exception e) {
8556 loge("Exception in networkUpdateRouteParcel: " + e);
8557 }
8558 }
8559 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8560 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008561 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008562
Junyu Lai970963e2022-10-25 15:46:47 +08008563 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8564 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008565 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8566 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008567 }
Erik Klineb9888902016-04-05 13:30:49 +09008568
Erik Kline31b4a9e2018-01-11 21:07:29 +09008569 if (DBG) {
8570 final Collection<InetAddress> dnses = newLp.getDnsServers();
8571 log("Setting DNS servers for network " + netId + " to " + dnses);
8572 }
Erik Klineb9888902016-04-05 13:30:49 +09008573 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008574 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008575 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008576 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008577 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008578 }
Erik Kline54e35c02017-04-07 15:29:29 +09008579 }
8580
Junyu Lai970963e2022-10-25 15:46:47 +08008581 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8582 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008583 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8584 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008585 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8586 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008587
8588 if (!wasFiltering && !needsFiltering) {
8589 // Nothing to do.
8590 return;
8591 }
8592
8593 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8594 // Nothing changed.
8595 return;
8596 }
8597
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008598 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008599 if (ranges == null || ranges.isEmpty()) {
8600 return;
8601 }
8602
Qingxi Libb8da982020-01-17 17:54:27 -08008603 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008604 // TODO: this create a window of opportunity for apps to receive traffic between the time
8605 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008606 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008607 // old rules are being removed.
8608 if (wasFiltering) {
8609 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8610 }
8611 if (needsFiltering) {
8612 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8613 }
8614 }
8615
Valentin Iftime9fa35092019-09-24 13:32:13 +02008616 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008617 if (mWolSupportedInterfaces == null) {
8618 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008619 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008620 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008621 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8622 }
8623
Luke Huangb913c812018-08-24 20:33:16 +08008624 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008625 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008626 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008627 }
8628 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008629 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008630 }
Luke Huangb913c812018-08-24 20:33:16 +08008631 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008632 }
8633
Chalard Jean62edfd82019-12-02 18:39:29 +09008634 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8635 @NonNull final NetworkCapabilities newNc) {
8636 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8637 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008638 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008639 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008640 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008641 } catch (RemoteException | ServiceSpecificException e) {
8642 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008643 }
8644 }
8645 }
8646
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008647 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008648 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008649 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008650 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008651 underlyingNetworks = underlyingNetworksOrDefault(
8652 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008653 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008654 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8655 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008656 // metered if any underlying is metered, or originally declared metered by the agent.
8657 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008658 boolean roaming = false; // roaming if any underlying is roaming
8659 boolean congested = false; // congested if any underlying is congested
8660 boolean suspended = true; // suspended if all underlying are suspended
8661
8662 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008663 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008664 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008665 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008666 for (Network underlyingNetwork : underlyingNetworks) {
8667 final NetworkAgentInfo underlying =
8668 getNetworkAgentInfoForNetwork(underlyingNetwork);
8669 if (underlying == null) continue;
8670
8671 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8672 hadUnderlyingNetworks = true;
8673 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008674 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008675 }
8676
8677 // Merge capabilities of this underlying network. For bandwidth, assume the
8678 // worst case.
8679 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8680 underlyingCaps.getLinkDownstreamBandwidthKbps());
8681 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8682 underlyingCaps.getLinkUpstreamBandwidthKbps());
8683 // If this underlying network is metered, the VPN is metered (it may cost money
8684 // to send packets on this network).
8685 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8686 // If this underlying network is roaming, the VPN is roaming (the billing structure
8687 // is different than the usual, local one).
8688 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8689 // If this underlying network is congested, the VPN is congested (the current
8690 // condition of the network affects the performance of this network).
8691 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8692 // If this network is not suspended, the VPN is not suspended (the VPN
8693 // is able to transfer some data).
8694 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008695 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008696 }
8697 }
8698 if (!hadUnderlyingNetworks) {
8699 // No idea what the underlying networks are; assume reasonable defaults
8700 metered = true;
8701 roaming = false;
8702 congested = false;
8703 suspended = false;
8704 }
8705
Chalard Jean1d420b32022-10-12 16:39:37 +09008706 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008707 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8708 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8709 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8710 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8711 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8712 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008713 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008714 }
8715
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008716 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008717 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8718 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8719 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008720 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008721 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008722 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008723 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008724 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8725 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008726 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008727 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008728 if (nai.everConnected()
8729 && !nai.isVPN()
8730 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008731 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008732 // does not cause any request (that is not a listen) currently matching that agent to
8733 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008734 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008735 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008736 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008737 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008738 }
8739
Paul Jensen53f08952015-06-16 14:27:36 -04008740 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008741 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008742 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008743 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008744 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008745 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008746 }
Chalard Jean254bd162022-08-25 13:04:51 +09008747 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008748 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008749 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008750 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008751 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008752 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008753 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008754 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008755 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008756 }
Chalard Jean254bd162022-08-25 13:04:51 +09008757 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008758 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8759 } else {
8760 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8761 }
lucasline117e2e2019-10-22 18:27:33 +08008762 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008763
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008764 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008765 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8766 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008767 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008768 }
8769
Lorenzo Colittibd079452021-07-02 11:47:57 +09008770 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008771 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008772 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008773 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008774 }
8775
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008776 return newNc;
8777 }
8778
Lorenzo Colitti44840702021-01-11 22:27:57 +09008779 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8780 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8781 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8782 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8783 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8784 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8785 if (prevSuspended != suspended) {
8786 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8787 // onResumed have been removed.
8788 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8789 : ConnectivityManager.CALLBACK_RESUMED);
8790 }
8791 if (prevSuspended != suspended || prevRoaming != roaming) {
8792 // updateNetworkInfo will mix in the suspended info from the capabilities and
8793 // take appropriate action for the network having possibly changed state.
8794 updateNetworkInfo(nai, nai.networkInfo);
8795 }
8796 }
8797
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008798 /**
8799 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8800 *
8801 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8802 * capabilities we manage and store in {@code nai}, such as validated status and captive
8803 * portal status)
8804 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8805 * potentially triggers rematches.
8806 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8807 * change.)
8808 *
8809 * @param oldScore score of the network before any of the changes that prompted us
8810 * to call this function.
8811 * @param nai the network having its capabilities updated.
8812 * @param nc the new network capabilities.
8813 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008814 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008815 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008816 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008817 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008818 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8819 if (null != differences) {
8820 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8821 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008822 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008823 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008824
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008825 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008826 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008827 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008828
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008829 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008830 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8831 // the change we're processing can't affect any requests, it can only affect the listens
8832 // on this network. We might have been called by rematchNetworkAndRequests when a
8833 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008834 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008835 } else {
8836 // If the requestable capabilities have changed or the score changed, we can't have been
8837 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008838 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008839 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008840 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008841 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008842
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008843 final boolean oldMetered = prevNc.isMetered();
8844 final boolean newMetered = newNc.isMetered();
8845 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008846
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008847 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008848 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8849 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008850 }
junyulaif2c67e42018-08-07 19:50:45 +08008851
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008852 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8853 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008854
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008855 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008856 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008857 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008858 }
8859
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008860 // This network might have been underlying another network. Propagate its capabilities.
8861 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008862
8863 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008864 mDnsManager.updateTransportsForNetwork(
8865 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008866 }
lucaslin53e8a262021-06-08 01:43:59 +08008867
8868 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008869 }
8870
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008871 /** Convenience method to update the capabilities for a given network. */
8872 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008873 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008874 }
8875
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008876 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008877 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008878 *
8879 * Ingress interface filtering enforces that all apps under the given network can only receive
8880 * packets from the network's interface (and loopback). This is important for VPNs because
8881 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8882 * non-VPN interfaces.
8883 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008884 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008885 * 1. the network is an app VPN (not legacy VPN)
8886 * 2. the VPN does not allow bypass
8887 * 3. the VPN is fully-routed
8888 * 4. the VPN interface is non-null
8889 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008890 * @see INetd#firewallAddUidInterfaceRules
8891 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008892 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008893 @Nullable
8894 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008895 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008896 if (nc == null || lp == null) return null;
8897 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008898 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008899 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008900 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008901 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008902 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008903 && !lp.hasExcludeRoute()) {
8904 return lp.getInterfaceName();
8905 }
8906 return null;
8907 }
8908
8909 /**
8910 * Returns whether we need to set interface filtering rule or not
8911 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008912 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008913 String isolationIface) {
8914 // Allow rules are always needed if VPN isolation is enabled.
8915 if (isolationIface != null) return true;
8916
8917 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8918 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8919 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09008920 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008921 }
8922
Chiachang Wang28afaff2020-12-10 22:24:47 +08008923 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8924 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8925 int index = 0;
8926 for (UidRange range : ranges) {
8927 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8928 index++;
8929 }
8930 return stableRanges;
8931 }
8932
Chalard Jeane6c95272022-01-25 21:04:21 +09008933 private static UidRangeParcel[] intsToUidRangeStableParcels(
8934 final @NonNull ArraySet<Integer> uids) {
8935 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8936 int index = 0;
8937 for (int uid : uids) {
8938 stableRanges[index] = new UidRangeParcel(uid, uid);
8939 index++;
8940 }
8941 return stableRanges;
8942 }
8943
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008944 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8945 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8946 for (int i = 0; i < ranges.length; i++) {
8947 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8948 }
8949 return stableRanges;
8950 }
8951
Motomu Utsumi93a22182023-03-16 17:04:21 +09008952 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09008953 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08008954 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8955 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09008956 if (mDeps.isAtLeastU()) {
8957 final Set<Integer> exemptUidSet = new ArraySet<>();
8958 for (final int uid: exemptUids) {
8959 exemptUidSet.add(uid);
8960 }
8961 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
8962 } else {
8963 mNetd.socketDestroy(uidRangeParcels, exemptUids);
8964 }
Ken Chen5e65a852020-12-24 12:59:10 +08008965 } catch (Exception e) {
8966 loge("Exception in socket destroy: ", e);
8967 }
8968 }
8969 }
8970
paulhuaa0743d2021-05-26 21:56:03 +08008971 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09008972 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08008973 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8974 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8975 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09008976 exemptUids[0] = VPN_UID;
8977 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08008978 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8979
Motomu Utsumi6345e462023-03-13 13:24:50 +09008980 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09008981 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008982 try {
8983 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008984 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008985 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008986 } else {
paulhu0e79d952021-06-09 16:11:35 +08008987 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008988 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008989 }
8990 } catch (Exception e) {
8991 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8992 " on netId " + nai.network.netId + ". " + e);
8993 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09008994 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09008995 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008996 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008997
lucaslin53e8a262021-06-08 01:43:59 +08008998 private boolean isProxySetOnAnyDefaultNetwork() {
8999 ensureRunningOnConnectivityServiceThread();
9000 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9001 final NetworkAgentInfo nai = nri.getSatisfier();
9002 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9003 return true;
9004 }
9005 }
9006 return false;
9007 }
9008
9009 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9010 NetworkCapabilities newNc) {
9011 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9012 // the proxy might be changed since the default network satisfied by the apps might also
9013 // changed.
9014 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9015 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009016 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9017 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009018 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009019 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9020 mProxyTracker.sendProxyBroadcast();
9021 }
9022 }
9023
Chalard Jeane6c95272022-01-25 21:04:21 +09009024 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9025 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009026 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9027 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009028 if (null == prevRanges) prevRanges = new ArraySet<>();
9029 if (null == newRanges) newRanges = new ArraySet<>();
9030 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9031
9032 prevRanges.removeAll(newRanges);
9033 newRanges.removeAll(prevRangesCopy);
9034
9035 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009036 // When updating the VPN uid routing rules, add the new range first then remove the old
9037 // range. If old range were removed first, there would be a window between the old
9038 // range being removed and the new range being added, during which UIDs contained
9039 // in both ranges are not subject to any VPN routing rules. Adding new range before
9040 // removing old range works because, unlike the filtering rules below, it's possible to
9041 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009042 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9043 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9044 // [1-5] & [1-2],[4-5] == [3]
9045 // Then we can do:
9046 // maybeCloseSockets([3])
9047 // mNetd.networkAddUidRanges([1-2],[4-5])
9048 // mNetd.networkRemoveUidRanges([1-5])
9049 // maybeCloseSockets([3])
9050 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9051 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009052 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009053 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009054 }
9055 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009056 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009057 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009058 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9059 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009060 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9061 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009062 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009063 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009064 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9065 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9066 // were added first and then newRanges got removed later, there would be only one uid
9067 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9068 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9069 // Note that this is in contrast with the (more robust) update of VPN routing rules
9070 // above, where the addition of new ranges happens before the removal of old ranges.
9071 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9072 // to be removed will never overlap with the new range to be added.
9073 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009074 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9075 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009076 }
9077 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009078 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009079 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009080 } catch (Exception e) {
9081 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009082 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009083 }
9084 }
9085
Chalard Jeande665262022-02-25 16:12:12 +09009086 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009087 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9088 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009089 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9090 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009091 if (prevEmpty && newEmpty) return;
9092
9093 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009094 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009095 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009096 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009097
9098 if (prevUids.equals(newUids)) return;
9099
9100 // This implementation is very simple and vastly faster for sets of Integers than
9101 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9102 // a key computed from the value and has storage for that.
9103 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9104 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9105 toRemove.removeAll(newUids);
9106 toAdd.removeAll(prevUids);
9107
9108 try {
9109 if (!toAdd.isEmpty()) {
9110 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9111 nai.network.netId,
9112 intsToUidRangeStableParcels(toAdd),
9113 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9114 }
9115 if (!toRemove.isEmpty()) {
9116 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9117 nai.network.netId,
9118 intsToUidRangeStableParcels(toRemove),
9119 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9120 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009121 } catch (ServiceSpecificException e) {
9122 // Has the interface disappeared since the network was built ?
9123 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009124 } catch (RemoteException e) {
9125 // Netd died. This usually causes a runtime restart anyway.
9126 }
9127 }
9128
Junyu Lai2ed7d412022-10-07 16:52:21 +08009129 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9130 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009131 ensureRunningOnConnectivityServiceThread();
9132
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009133 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009134 // Ignore updates for disconnected networks
9135 return;
9136 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009137 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009138 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009139 + "; created=" + nai.getCreatedTime()
9140 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009141 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009142 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9143 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009144 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009145 }
9146
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009147 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9148 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009149 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009150 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009151 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009152 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9153 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9154 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009155 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9156 // need to be sent as a separate extra.
9157 final NetworkRequest req = nri.isMultilayerRequest()
9158 ? nri.getActiveRequest()
9159 // Non-multilayer listen requests do not have an active request
9160 : nri.mRequests.get(0);
9161 if (req == null) {
9162 Log.wtf(TAG, "No request in NRI " + nri);
9163 }
9164 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009165 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009166 sendIntent(nri.mPendingIntent, intent);
9167 }
9168 // else not handled
9169 }
9170
Michael Groover73f69482023-01-27 11:01:25 -06009171 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9172 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009173 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9174 mPendingIntentWakeLock.acquire();
9175 try {
9176 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009177 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009178 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009179 // Explicitly disallow the receiver from starting activities, to prevent apps from
9180 // utilizing the PendingIntent as a backdoor to do this.
9181 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9182 }
9183 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9184 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009185 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009186 } catch (PendingIntent.CanceledException e) {
9187 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9188 mPendingIntentWakeLock.release();
9189 releasePendingNetworkRequest(pendingIntent);
9190 }
9191 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9192 }
9193
9194 @Override
9195 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9196 String resultData, Bundle resultExtras) {
9197 if (DBG) log("Finished sending " + pendingIntent);
9198 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009199 // Release with a delay so the receiving client has an opportunity to put in its
9200 // own request.
9201 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009202 }
9203
Chalard Jean46bfbf02022-02-02 00:56:25 +09009204 // networkAgent is only allowed to be null if notificationType is
9205 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9206 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009207 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009208 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009209 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009210 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009211 // Default request has no msgr. Also prevents callbacks from being invoked for
9212 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9213 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9214 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009215 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09009216 final Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009217 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009218 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009219 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009220 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009221 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009222 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9223 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009224 }
Roshan Pius951c0032020-12-22 15:10:42 -08009225 final boolean includeLocationSensitiveInfo =
9226 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009227 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009228 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009229 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009230 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009231 networkCapabilitiesRestrictedForCallerPermissions(
9232 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9233 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009234 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009235 nri.mCallingAttributionTag);
9236 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009237 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9238 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08009239 // For this notification, arg1 contains the blocked status.
9240 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009241 break;
9242 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009243 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009244 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009245 break;
9246 }
9247 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009248 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009249 final NetworkCapabilities netCap =
9250 networkCapabilitiesRestrictedForCallerPermissions(
9251 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9252 putParcelable(
9253 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009254 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009255 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009256 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009257 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009258 break;
9259 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009260 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009261 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9262 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009263 break;
9264 }
junyulaif2c67e42018-08-07 19:50:45 +08009265 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009266 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009267 msg.arg1 = arg1;
9268 break;
9269 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009270 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009271 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009272 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009273 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009274 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009275 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009276 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009277 }
James Mattis45d81842021-01-10 14:24:24 -08009278 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009279 } catch (RemoteException e) {
9280 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009281 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009282 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009283 }
9284
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009285 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9286 bundle.putParcelable(t.getClass().getSimpleName(), t);
9287 }
9288
Chalard Jean0702f982021-09-16 21:50:07 +09009289 /**
9290 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9291 *
9292 * When a request should be assigned to a new network, it is normally lingered to give
9293 * time for apps to gracefully migrate their connections. When both networks are on the same
9294 * radio, but that radio can't do time-sharing efficiently, this may end up being
9295 * counter-productive because any traffic on the old network may drastically reduce the
9296 * performance of the new network.
9297 * The stack supports a configuration to let modem vendors state that their radio can't
9298 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9299 * from one cell network to another can't be done gracefully.
9300 *
9301 * @param oldNai the old network serving the request
9302 * @param newNai the new network serving the request
9303 * @return whether the switch can be graceful
9304 */
9305 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9306 @NonNull final NetworkAgentInfo newSatisfier) {
9307 if (mCellularRadioTimesharingCapable) return true;
9308 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9309 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9310 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9311 }
9312
Paul Jensenaf94b982014-09-30 15:37:41 -04009313 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009314 if (nai.numRequestNetworkRequests() != 0) {
9315 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9316 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009317 // Ignore listening and track default requests.
9318 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009319 loge("Dead network still had at least " + nr);
9320 break;
9321 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009322 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009323 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009324 }
9325
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009326 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9327 if (oldNetwork == null) {
9328 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9329 return;
9330 }
Chalard Jean49707572019-12-10 21:07:02 +09009331 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009332
9333 // If we get here it means that the last linger timeout for this network expired. So there
9334 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009335 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009336
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009337 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009338 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009339 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009340 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009341 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009342 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009343 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009344 }
9345
James Mattise3ef1912020-12-20 11:09:58 -08009346 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9347 boolean isDefaultChanged = false;
9348 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9349 final NetworkReassignment.RequestReassignment reassignment =
9350 changes.getReassignment(defaultRequestInfo);
9351 if (null == reassignment) {
9352 continue;
9353 }
9354 // reassignment only contains those instances where the satisfying network changed.
9355 isDefaultChanged = true;
9356 // Notify system services of the new default.
9357 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9358 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009359
James Mattise3ef1912020-12-20 11:09:58 -08009360 if (isDefaultChanged) {
9361 // Hold a wakelock for a short time to help apps in migrating to a new default.
9362 scheduleReleaseNetworkTransitionWakelock();
9363 }
9364 }
9365
Aaron Huang9fe47be2021-06-08 13:11:45 +08009366 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9367 if (null == oldDefaultNetwork) return;
9368 // The network stopped being the default. If it was using a PAC proxy, then the
9369 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9370 // to the local proxy server, which would forward them over the newly default network.
9371 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9372 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9373 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9374 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9375 }
9376
James Mattise3ef1912020-12-20 11:09:58 -08009377 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9378 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9379 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9380 if (DBG) {
9381 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9382 }
Chalard Jean8e382112019-12-03 20:45:30 +09009383
James Mattisd31bdfa2020-12-23 16:37:26 -08009384 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9385 if (newDefaultNetwork != null) {
9386 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009387 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009388
James Mattisd31bdfa2020-12-23 16:37:26 -08009389 // Set an app level managed default and return since further processing only applies to the
9390 // default network.
9391 if (mDefaultRequest != nri) {
9392 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9393 return;
9394 }
9395
9396 makeDefaultNetwork(newDefaultNetwork);
9397
James Mattise3ef1912020-12-20 11:09:58 -08009398 if (oldDefaultNetwork != null) {
9399 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9400 }
9401 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009402 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009403 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009404 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009405 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009406 updateTcpBufferSizes(null != newDefaultNetwork
9407 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009408 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009409 }
9410
James Mattisd31bdfa2020-12-23 16:37:26 -08009411 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9412 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9413 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9414 try {
9415 if (VDBG) {
9416 log("Setting default network for " + nri
9417 + " using UIDs " + nri.getUids()
9418 + " with old network " + (oldDefaultNetwork != null
9419 ? oldDefaultNetwork.network().getNetId() : "null")
9420 + " and new network " + (newDefaultNetwork != null
9421 ? newDefaultNetwork.network().getNetId() : "null"));
9422 }
9423 if (nri.getUids().isEmpty()) {
9424 throw new IllegalStateException("makeDefaultForApps called without specifying"
9425 + " any applications to set as the default." + nri);
9426 }
9427 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009428 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009429 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009430 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009431 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009432 }
9433 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009434 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009435 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009436 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009437 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009438 }
9439 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009440 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009441 }
9442 }
9443
Junyu Lai35665cc2022-12-19 17:37:48 +08009444 /**
9445 * Collect restricted uid ranges for the given network and UserHandle, these uids
9446 * are not restricted for matched enterprise networks but being restricted for non-matched
9447 * enterprise networks and non-enterprise networks.
9448 */
9449 @NonNull
9450 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9451 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9452 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9453 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9454 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9455
9456 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9457 // The NC is built from a `ProfileNetworkPreference` which has only one
9458 // enterprise ID, so it's guaranteed to have exactly one.
9459 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9460 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9461 continue;
9462 }
9463 }
9464
9465 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9466 pref.capabilities.getUidRanges())) {
9467 throw new IllegalArgumentException(
9468 "Overlapping uid range in preference: " + pref);
9469 }
9470 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9471 }
9472 return restrictedUidRanges;
9473 }
9474
9475 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009476 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +09009477 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009478
Junyu Lai35665cc2022-12-19 17:37:48 +08009479 ensureRunningOnConnectivityServiceThread();
9480 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9481 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9482 .getUserHandles(true /* excludeDying */);
9483 if (users.isEmpty()) {
9484 throw new IllegalStateException("No user is available");
9485 }
9486
9487 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9488 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9489 for (final UserHandle user : users) {
9490 final ArraySet<UidRange> restrictedUidRanges =
9491 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9492 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9493 UidRange.createForUser(user), restrictedUidRanges));
9494 }
9495
9496 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9497 configs.add(new NativeUidRangeConfig(
9498 nai.network.netId, rangesParcel, 0 /* subPriority */));
9499 }
9500
9501 // The netd API replaces the previous configs with the current configs.
9502 // Thus, for network disconnection or preference removal, no need to
9503 // unset previous config. Instead, collecting all currently needed
9504 // configs and issue to netd.
9505 try {
9506 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9507 } catch (ServiceSpecificException e) {
9508 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009509 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009510 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009511 // Netd died. This will cause a runtime restart anyway.
9512 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009513 }
9514 }
9515
James Mattisd31bdfa2020-12-23 16:37:26 -08009516 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9517 try {
9518 if (null != newDefaultNetwork) {
9519 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9520 } else {
9521 mNetd.networkClearDefault();
9522 }
9523 } catch (RemoteException | ServiceSpecificException e) {
9524 loge("Exception setting default network :" + e);
9525 }
9526 }
9527
Chalard Jean05cbe972019-12-09 11:50:38 +09009528 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009529 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009530 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009531 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009532 processNewlySatisfiedListenRequests(nai);
9533 }
9534
9535 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009536 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9537 if (nri.isMultilayerRequest()) {
9538 continue;
9539 }
9540 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009541 if (!nr.isListen()) continue;
9542 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009543 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009544 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9545 }
9546 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009547 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009548
Chalard Jeancd397a22019-11-22 22:33:33 +09009549 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009550 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9551 if (nri.isMultilayerRequest()) {
9552 continue;
9553 }
9554 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009555 if (!nr.isListen()) continue;
9556 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9557 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009558 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009559 }
9560 }
9561 }
9562
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009563 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009564 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009565 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009566 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009567 @Nullable public final NetworkRequest mOldNetworkRequest;
9568 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009569 @Nullable public final NetworkAgentInfo mOldNetwork;
9570 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009571 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009572 @Nullable final NetworkRequest oldNetworkRequest,
9573 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009574 @Nullable final NetworkAgentInfo oldNetwork,
9575 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009576 mNetworkRequestInfo = networkRequestInfo;
9577 mOldNetworkRequest = oldNetworkRequest;
9578 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009579 mOldNetwork = oldNetwork;
9580 mNewNetwork = newNetwork;
9581 }
Chalard Jean49707572019-12-10 21:07:02 +09009582
9583 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009584 final NetworkRequest requestToShow = null != mNewNetworkRequest
9585 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9586 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009587 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9588 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009589 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009590 }
9591
Chalard Jean46a62372019-12-10 21:25:24 +09009592 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009593
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009594 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009595 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009596 }
9597
9598 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009599 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009600 // The code is never supposed to add two reassignments of the same request. Make
9601 // sure this stays true, but without imposing this expensive check on all
9602 // reassignments on all user devices.
9603 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009604 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009605 throw new IllegalStateException("Trying to reassign ["
9606 + reassignment + "] but already have ["
9607 + existing + "]");
9608 }
9609 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009610 }
Chalard Jean46a62372019-12-10 21:25:24 +09009611 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009612 }
9613
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009614 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009615 // the passed request.
9616 @Nullable
9617 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009618 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009619 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009620 }
9621 return null;
9622 }
Chalard Jean49707572019-12-10 21:07:02 +09009623
9624 public String toString() {
9625 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9626 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009627 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009628 for (final RequestReassignment rr : getRequestReassignments()) {
9629 sj.add(rr.toString());
9630 }
9631 return sj.toString();
9632 }
9633
9634 public String debugString() {
9635 final StringBuilder sb = new StringBuilder();
9636 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009637 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009638 for (final RequestReassignment rr : getRequestReassignments()) {
9639 sb.append("\n ").append(rr);
9640 }
9641 return sb.append("\n").toString();
9642 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009643 }
9644
Chalard Jean24344d72019-12-04 13:32:31 +09009645 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009646 @Nullable final NetworkRequest previousRequest,
9647 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009648 @Nullable final NetworkAgentInfo previousSatisfier,
9649 @Nullable final NetworkAgentInfo newSatisfier,
9650 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009651 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009652 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009653 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009654 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009655 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09009656 }
James Mattisa076c532020-12-02 14:12:41 -08009657 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009658 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009659 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009660 // If this network switch can't be supported gracefully, the request is not
9661 // lingered. This allows letting go of the network sooner to reclaim some
9662 // performance on the new network, since the radio can't do both at the same
9663 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009664 //
9665 // Also don't linger the request if the old network has been destroyed.
9666 // A destroyed network does not provide actual network connectivity, so
9667 // lingering it is not useful. In particular this ensures that a destroyed
9668 // network is outscored by its replacement,
9669 // then it is torn down immediately instead of being lingered, and any apps that
9670 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009671 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9672 }
Chalard Jean24344d72019-12-04 13:32:31 +09009673 } else {
9674 if (VDBG || DDBG) log(" accepting network in place of null");
9675 }
junyulai0ac374f2020-12-14 18:41:52 +08009676
9677 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9678 // and immediately satisfies a request then remove the timer. This will happen for
9679 // all networks except in the case of an underlying network for a VCN.
9680 if (newSatisfier.isNascent()) {
9681 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009682 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009683 }
9684
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009685 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009686 newSatisfier.unlingerRequest(newRequest.requestId);
9687 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009688 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009689 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009690 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009691 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009692 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009693 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009694 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009695 }
James Mattisa076c532020-12-02 14:12:41 -08009696 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009697 }
James Mattisa076c532020-12-02 14:12:41 -08009698 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009699 }
9700
James Mattisa076c532020-12-02 14:12:41 -08009701 /**
9702 * This function is triggered when something can affect what network should satisfy what
9703 * request, and it computes the network reassignment from the passed collection of requests to
9704 * network match to the one that the system should now have. That data is encoded in an
9705 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9706 * satisfier.
9707 *
9708 * After the reassignment is computed, it is applied to the state objects.
9709 *
9710 * @param networkRequests the nri objects to evaluate for possible network reassignment
9711 * @return NetworkReassignment listing of proposed network assignment changes
9712 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009713 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009714 private NetworkReassignment computeNetworkReassignment(
9715 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009716 final NetworkReassignment changes = new NetworkReassignment();
9717
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009718 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009719 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009720 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009721 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009722 }
Chalard Jean857a1712019-12-10 21:08:07 +09009723
James Mattisa076c532020-12-02 14:12:41 -08009724 for (final NetworkRequestInfo nri : networkRequests) {
9725 // Non-multilayer listen requests can be ignored.
9726 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9727 continue;
9728 }
9729 NetworkAgentInfo bestNetwork = null;
9730 NetworkRequest bestRequest = null;
9731 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009732 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009733 // Stop evaluating as the highest possible priority request is satisfied.
9734 if (null != bestNetwork) {
9735 bestRequest = req;
9736 break;
9737 }
9738 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009739 if (null == bestNetwork && isDefaultBlocked(nri)) {
9740 // Remove default networking if disallowed for managed default requests.
9741 bestNetwork = mNoServiceNetwork;
9742 }
9743 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009744 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009745 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009746 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009747 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009748 }
9749 return changes;
9750 }
9751
James Mattisa076c532020-12-02 14:12:41 -08009752 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9753 return new HashSet<>(mNetworkRequests.values());
9754 }
9755
Paul Jensenc88b39b2015-06-16 14:27:36 -04009756 /**
James Mattisa076c532020-12-02 14:12:41 -08009757 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009758 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009759 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009760 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009761 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9762 }
9763
9764 /**
9765 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9766 * being disconnected.
9767 */
9768 private void rematchNetworksAndRequests(
9769 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9770 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009771 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009772 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009773 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009774 final long computed = SystemClock.elapsedRealtime();
9775 applyNetworkReassignment(changes, start);
9776 final long applied = SystemClock.elapsedRealtime();
9777 issueNetworkNeeds();
9778 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009779 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009780 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9781 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009782 log(changes.debugString());
9783 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009784 // Shorter form, only one line of log
9785 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9786 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009787 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009788 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009789
Chalard Jeand7f762d2019-12-10 19:01:29 +09009790 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009791 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009792 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009793
9794 // Since most of the time there are only 0 or 1 background networks, it would probably
9795 // be more efficient to just use an ArrayList here. TODO : measure performance
9796 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9797 for (final NetworkAgentInfo nai : nais) {
9798 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9799 }
9800
Chalard Jeand7f762d2019-12-10 19:01:29 +09009801 // First, update the lists of satisfied requests in the network agents. This is necessary
9802 // because some code later depends on this state to be correct, most prominently computing
9803 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009804 for (final NetworkReassignment.RequestReassignment event :
9805 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009806 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9807 event.mOldNetworkRequest, event.mNewNetworkRequest,
9808 event.mOldNetwork, event.mNewNetwork,
9809 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009810 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009811
James Mattise3ef1912020-12-20 11:09:58 -08009812 // Process default network changes if applicable.
9813 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009814
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009815 // Notify requested networks are available after the default net is switched, but
9816 // before LegacyTypeTracker sends legacy broadcasts
9817 for (final NetworkReassignment.RequestReassignment event :
9818 changes.getRequestReassignments()) {
9819 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009820 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009821 } else {
James Mattisa076c532020-12-02 14:12:41 -08009822 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009823 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009824 }
9825 }
9826
junyulai0ac374f2020-12-14 18:41:52 +08009827 // Update the inactivity state before processing listen callbacks, because the background
9828 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009829 // just yet though, because they have to be sent after the listens are processed to keep
9830 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009831 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009832 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009833 // Rematching may have altered the inactivity state of some networks, so update all
9834 // inactivity timers. updateInactivityState reads the state from the network agent
9835 // and does nothing if the state has not changed : the source of truth is controlled
9836 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9837 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009838 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009839 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009840 }
9841 }
9842
Chalard Jeanb10ab412019-12-11 14:12:30 +09009843 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009844 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009845 // Process listen requests and update capabilities if the background state has
9846 // changed for this network. For consistency with previous behavior, send onLost
9847 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009848 processNewlyLostListenRequests(nai);
9849 if (oldBackground != nai.isBackgroundNetwork()) {
9850 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009851 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009852 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009853 }
9854
junyulai0ac374f2020-12-14 18:41:52 +08009855 for (final NetworkAgentInfo nai : inactiveNetworks) {
9856 // For nascent networks, if connecting with no foreground request, skip broadcasting
9857 // LOSING for backward compatibility. This is typical when mobile data connected while
9858 // wifi connected with mobile data always-on enabled.
9859 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009860 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009861 }
9862
James Mattise3ef1912020-12-20 11:09:58 -08009863 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009864
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009865 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +00009866 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009867 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009868 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009869 // This network has active linger timers and no requests, but is not
9870 // lingering. Linger it.
9871 //
9872 // One way (the only way?) this can happen if this network is unvalidated
9873 // and became unneeded due to another network improving its score to the
9874 // point where this network will no longer be able to satisfy any requests
9875 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009876 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009877 notifyNetworkLosing(nai, now);
9878 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009879 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009880 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009881 teardownUnneededNetwork(nai);
9882 }
9883 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009884 }
9885 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009886
Chalard Jean62edfd82019-12-02 18:39:29 +09009887 /**
9888 * Apply a change in background state resulting from rematching networks with requests.
9889 *
9890 * During rematch, a network may change background states by starting to satisfy or stopping
9891 * to satisfy a foreground request. Listens don't count for this. When a network changes
9892 * background states, its capabilities need to be updated and callbacks fired for the
9893 * capability change.
9894 *
9895 * @param nai The network that changed background states
9896 */
9897 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
9898 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
9899 if (Objects.equals(nai.networkCapabilities, newNc)) return;
9900 updateNetworkPermissions(nai, newNc);
9901 nai.getAndSetNetworkCapabilities(newNc);
9902 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
9903 }
9904
Chalard Jeanf0344532019-11-19 19:23:38 +09009905 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08009906 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009907 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09009908 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
9909 changes.getReassignment(mDefaultRequest);
9910 final NetworkAgentInfo oldDefaultNetwork =
9911 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
9912 final NetworkAgentInfo newDefaultNetwork =
9913 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08009914
Chalard Jean5b409c72021-02-04 13:12:59 +09009915 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009916 // Maintain the illusion : since the legacy API only understands one network at a time,
9917 // if the default network changed, apps should see a disconnected broadcast for the
9918 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009919 if (oldDefaultNetwork != null) {
9920 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9921 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009922 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009923 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009924 // The new default network can be newly null if and only if the old default
9925 // network doesn't satisfy the default request any more because it lost a
9926 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009927 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009928 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009929 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009930 }
9931 }
9932
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009933 // Now that all the callbacks have been sent, send the legacy network broadcasts
9934 // as needed. This is necessary so that legacy requests correctly bind dns
9935 // requests to this network. The legacy users are listening for this broadcast
9936 // and will generally do a dns request so they can ensureRouteToHost and if
9937 // they do that before the callbacks happen they'll use the default network.
9938 //
9939 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
9940 // callbacks, but if apps can receive the broadcast before the callback, they still might
9941 // have an inconsistent view of networking.
9942 //
9943 // This *does* introduce a race where if the user uses the new api
9944 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
9945 // they may get old info. Reverse this after the old startUsing api is removed.
9946 // This is on top of the multiple intent sequencing referenced in the todo above.
9947 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09009948 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009949 addNetworkToLegacyTypeTracker(nai);
9950 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08009951 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009952 }
9953
Chalard Jean0354d8c2021-01-12 10:58:56 +09009954 private void issueNetworkNeeds() {
9955 ensureRunningOnConnectivityServiceThread();
9956 for (final NetworkOfferInfo noi : mNetworkOffers) {
9957 issueNetworkNeeds(noi);
9958 }
9959 }
9960
9961 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
9962 ensureRunningOnConnectivityServiceThread();
9963 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9964 informOffer(nri, noi.offer, mNetworkRanker);
9965 }
9966 }
9967
9968 /**
9969 * Inform a NetworkOffer about any new situation of a request.
9970 *
9971 * This function handles updates to offers. A number of events may happen that require
9972 * updating the registrant for this offer about the situation :
9973 * • The offer itself was updated. This may lead the offer to no longer being able
9974 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
9975 * or conversely being strengthened enough to beat the satisfier (and therefore
9976 * start being needed)
9977 * • The network satisfying a request changed (including cases where the request
9978 * starts or stops being satisfied). The new network may be a stronger or weaker
9979 * match than the old one, possibly affecting whether the offer is needed.
9980 * • The network satisfying a request updated their score. This may lead the offer
9981 * to no longer be able to beat it if the current satisfier got better, or
9982 * conversely start being a good choice if the current satisfier got weaker.
9983 *
9984 * @param nri The request
9985 * @param offer The offer. This may be an updated offer.
9986 */
9987 private static void informOffer(@NonNull NetworkRequestInfo nri,
9988 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9989 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9990 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009991
9992 // Multi-layer requests have a currently active request, the one being satisfied.
9993 // Since the system will try to bring up a better network than is currently satisfying
9994 // the request, NetworkProviders need to be told the offers matching the requests *above*
9995 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9996 // not needed, and the offer is needed for the active request iff the offer can beat
9997 // the satisfier.
9998 // For non-multilayer requests, the logic above gracefully degenerates to only the
9999 // last case.
10000 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10001 // providers that the offer is needed for this request, until the active request is found.
10002 // In a second phase, deal with the currently active request. In a third phase, inform
10003 // the providers that offer is unneeded for the remaining requests.
10004
10005 // First phase : inform providers of all requests above the active request.
10006 int i;
10007 for (i = 0; nri.mRequests.size() > i; ++i) {
10008 final NetworkRequest request = nri.mRequests.get(i);
10009 if (activeRequest == request) break; // Found the active request : go to phase 2
10010 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10011 // Since this request is higher-priority than the one currently satisfied, if the
10012 // offer can satisfy it, the provider should try and bring up the network for sure ;
10013 // no need to even ask the ranker – an offer that can satisfy is always better than
10014 // no network. Hence tell the provider so unless it already knew.
10015 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10016 offer.onNetworkNeeded(request);
10017 }
10018 }
10019
10020 // Second phase : deal with the active request (if any)
10021 if (null != activeRequest && activeRequest.isRequest()) {
10022 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010023 // If an offer can satisfy the request, it is considered needed if it is currently
10024 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010025 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010026 && satisfier.factorySerialNumber == offer.providerId
10027 && activeRequest.canBeSatisfiedBy(offer.caps);
10028 final boolean newNeeded = currentlyServing
10029 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010030 if (newNeeded != oldNeeded) {
10031 if (newNeeded) {
10032 offer.onNetworkNeeded(activeRequest);
10033 } else {
10034 // The offer used to be able to beat the satisfier. Now it can't.
10035 offer.onNetworkUnneeded(activeRequest);
10036 }
10037 }
10038 }
10039
10040 // Third phase : inform the providers that the offer isn't needed for any request
10041 // below the active one.
10042 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10043 final NetworkRequest request = nri.mRequests.get(i);
10044 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10045 // Since this request is lower-priority than the one currently satisfied, if the
10046 // offer can satisfy it, the provider should not try and bring up the network.
10047 // Hence tell the provider so unless it already knew.
10048 if (offer.neededFor(request)) {
10049 offer.onNetworkUnneeded(request);
10050 }
10051 }
10052 }
10053
Chalard Jean61c79252019-11-07 23:07:32 +090010054 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10055 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10056 NetworkRequest nr = nai.requestAt(i);
10057 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10058 // legacy type tracker filters out repeat adds
10059 mLegacyTypeTracker.add(nr.legacyType, nai);
10060 }
10061 }
10062
10063 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010064 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010065 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10066 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10067 if (nai.isVPN()) {
10068 mLegacyTypeTracker.add(TYPE_VPN, nai);
10069 }
10070 }
10071
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010072 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010073 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010074 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010075 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010076 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010077 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010078
Chalard Jean254bd162022-08-25 13:04:51 +090010079 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010080 // Don't repeat publish.
10081 if (newInetCondition == mDefaultInetConditionPublished) return;
10082
10083 mDefaultInetConditionPublished = newInetCondition;
10084 sendInetConditionBroadcast(nai.networkInfo);
10085 }
10086
Chalard Jeand61375d2020-01-14 22:46:36 +090010087 @NonNull
10088 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10089 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010090 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010091 final boolean suspended =
10092 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10093 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10094 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10095 // state. This is because the network could have been suspended before connecting,
10096 // or it could be disconnecting while being suspended, and in both these cases
10097 // the state should not be overridden. Note that the only detailed state that
10098 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10099 // worry about multiple different substates of CONNECTED.
10100 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10101 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010102 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10103 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10104 // network agent is created, then goes to suspended, then goes out of suspended without
10105 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010106 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010107 ? NetworkInfo.DetailedState.CONNECTED
10108 : NetworkInfo.DetailedState.CONNECTING,
10109 info.getReason(),
10110 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010111 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010112 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010113 return newInfo;
10114 }
10115
10116 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10117 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10118
Erik Kline99f301b2017-02-15 19:59:17 +090010119 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010120 NetworkInfo oldInfo = null;
10121 synchronized (networkAgent) {
10122 oldInfo = networkAgent.networkInfo;
10123 networkAgent.networkInfo = newInfo;
10124 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010125
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010126 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010127 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10128 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010129 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010130
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010131 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010132 // A network that has just connected has zero requests and is thus a foreground network.
10133 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10134
Luke Huangfdd11f82019-04-09 18:41:49 +080010135 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010136
10137 networkAgent.setCreated();
10138
10139 // If the network is created immediately on register, then apply the LinkProperties now.
10140 // Otherwise, this is done further down when the network goes into connected state.
10141 // Applying the LinkProperties means that the network is ready to carry traffic -
10142 // interfaces and routing rules have been added, DNS servers programmed, etc.
10143 // For VPNs, this must be done before the capabilities are updated, because as soon as
10144 // that happens, UIDs are routed to the network.
10145 if (shouldCreateNetworksImmediately()) {
10146 applyInitialLinkProperties(networkAgent);
10147 }
10148
10149 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10150 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010151 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010152 // Initialize the network's capabilities to their starting values according to the
10153 // underlying networks. This ensures that the capabilities are correct before
10154 // anything happens to the network.
10155 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010156 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010157 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010158 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010159 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010160 }
10161
Chalard Jean254bd162022-08-25 13:04:51 +090010162 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10163 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010164
lucaslin45e639b2019-04-03 17:09:28 +080010165 // NetworkCapabilities need to be set before sending the private DNS config to
10166 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010167 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10168
Erik Kline9a62f012018-03-21 07:18:33 -070010169 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010170 if (!shouldCreateNetworksImmediately()) {
10171 applyInitialLinkProperties(networkAgent);
10172 } else {
10173 // The network was created when the agent registered, and the LinkProperties are
10174 // already up-to-date. However, updateLinkProperties also makes some changes only
10175 // when the network connects. Apply those changes here. On T and below these are
10176 // handled by the applyInitialLinkProperties call just above.
10177 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10178 // If something depends on both LinkProperties and connected state, it should be in
10179 // this method as well.
10180 networkAgent.clatd.update();
10181 updateProxy(networkAgent.linkProperties, null);
10182 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010183
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010184 // If a rate limit has been configured and is applicable to this network (network
10185 // provides internet connectivity), apply it. The tc police filter cannot be attached
10186 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
10187 // updateInterfaces -> INetd#networkAddInterface.
10188 // Note: in case of a system server crash, the NetworkController constructor in netd
10189 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10190 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10191 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10192 mIngressRateLimit);
10193 }
10194
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010195 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10196 // command must be sent after updating LinkProperties to maximize chances of
10197 // NetworkMonitor seeing the correct LinkProperties when starting.
10198 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010199 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010200 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010201 }
Chalard Jeand4900722022-02-06 12:25:38 +090010202 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10203 params.networkAgentConfig = networkAgent.networkAgentConfig;
10204 params.networkCapabilities = networkAgent.networkCapabilities;
10205 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10206 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010207 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10208 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10209 // call that would cause a Log.wtf to be emitted from the system_server process, and
10210 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10211 // process to check the interface version, just use an SDK check. NetworkStack will
10212 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010213 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010214 networkAgent.networkMonitor().notifyNetworkConnected(params);
10215 } else {
10216 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10217 params.networkCapabilities);
10218 }
Chalard Jean0f141332023-06-05 19:26:17 +090010219 final long evaluationDelay;
10220 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10221 // If the network is anything other than pure wifi, use the default timeout.
10222 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10223 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10224 // If the network is explicitly selected, use the default timeout because it's
10225 // shorter and the user is likely staring at the screen expecting it to validate
10226 // right away.
10227 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10228 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10229 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10230 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10231 } else {
10232 // It's wifi, automatically connected, and bad wifi is preferred : use the
10233 // longer timeout to avoid the device switching to captive portals with bad
10234 // signal or very slow response.
10235 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10236 }
10237 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010238
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010239 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10240 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10241 // capabilities, so it only needs to be done once on initial connect, not every time the
10242 // network's capabilities change. Note that we do this before rematching the network,
10243 // so we could decide to tear it down immediately afterwards. That's fine though - on
10244 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10245 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010246 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010247
junyulai0ac374f2020-12-14 18:41:52 +080010248 // Before first rematching networks, put an inactivity timer without any request, this
10249 // allows {@code updateInactivityState} to update the state accordingly and prevent
10250 // tearing down for any {@code unneeded} evaluation in this period.
10251 // Note that the timer will not be rescheduled since the expiry time is
10252 // fixed after connection regardless of the network satisfying other requests or not.
10253 // But it will be removed as soon as the network satisfies a request for the first time.
10254 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10255 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010256 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010257
Paul Jensen05e85ee2014-09-11 11:00:39 -040010258 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010259 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010260
10261 // This has to happen after matching the requests, because callbacks are just requests.
10262 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010263 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010264 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010265 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010266 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010267 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010268 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010269 if (networkAgent.isVPN()) {
10270 // As the active or bound network changes for apps, broadcast the default proxy, as
10271 // apps may need to update their proxy data. This is called after disconnecting from
10272 // VPN to make sure we do not broadcast the old proxy data.
10273 // TODO(b/122649188): send the broadcast only to VPN users.
10274 mProxyTracker.sendProxyBroadcast();
10275 }
Chalard Jean254bd162022-08-25 13:04:51 +090010276 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10277 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010278 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010279 }
10280 }
10281
Chalard Jean28018572020-12-21 18:36:52 +090010282 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010283 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10284 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010285 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010286 }
10287
Erik Kline99f301b2017-02-15 19:59:17 +090010288 // Notify only this one new request of the current state. Transfer all the
10289 // current state by calling NetworkCapabilities and LinkProperties callbacks
10290 // so that callers can be guaranteed to have as close to atomicity in state
10291 // transfer as can be supported by this current API.
10292 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010293 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010294 if (nri.mPendingIntent != null) {
10295 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10296 // Attempt no subsequent state pushes where intents are involved.
10297 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010298 }
Erik Kline99f301b2017-02-15 19:59:17 +090010299
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010300 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010301 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010302 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10303 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10304 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010305 }
10306
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010307 // Notify the requests on this NAI that the network is now lingered.
10308 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010309 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010310 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10311 }
10312
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010313 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10314 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10315 return vpnBlocked
10316 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10317 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10318 }
10319
10320 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10321 if (blockedReasons == BLOCKED_REASON_NONE) {
10322 mUidBlockedReasons.delete(uid);
10323 } else {
10324 mUidBlockedReasons.put(uid, blockedReasons);
10325 }
10326 }
10327
junyulaif2c67e42018-08-07 19:50:45 +080010328 /**
10329 * Notify of the blocked state apps with a registered callback matching a given NAI.
10330 *
10331 * Unlike other callbacks, blocked status is different between each individual uid. So for
10332 * any given nai, all requests need to be considered according to the uid who filed it.
10333 *
10334 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010335 * @param oldMetered True if the previous network capabilities were metered.
10336 * @param newMetered True if the current network capabilities are metered.
10337 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10338 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010339 */
10340 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010341 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10342 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010343
10344 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10345 NetworkRequest nr = nai.requestAt(i);
10346 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010347
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010348 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10349 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10350 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010351 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010352 : oldVpnBlocked;
10353
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010354 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10355 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10356 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010357 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010358 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010359 }
10360 }
10361 }
10362
10363 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010364 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010365 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010366 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010367 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010368 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010369 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010370 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010371 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010372
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010373 final int oldBlockedState = getBlockedState(
10374 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10375 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10376 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010377 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010378 }
junyulaif2c67e42018-08-07 19:50:45 +080010379 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10380 NetworkRequest nr = nai.requestAt(i);
10381 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010382 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010383 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10384 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010385 }
10386 }
10387 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010388 }
10389
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010390 @VisibleForTesting
10391 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010392 // The NetworkInfo we actually send out has no bearing on the real
10393 // state of affairs. For example, if the default connection is mobile,
10394 // and a request for HIPRI has just gone away, we need to pretend that
10395 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10396 // the state to DISCONNECTED, even though the network is of type MOBILE
10397 // and is still connected.
10398 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10399 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010400 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010401 if (state != DetailedState.DISCONNECTED) {
10402 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010403 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010404 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010405 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010406 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10407 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10408 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10409 if (info.isFailover()) {
10410 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10411 nai.networkInfo.setFailover(false);
10412 }
10413 if (info.getReason() != null) {
10414 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10415 }
10416 if (info.getExtraInfo() != null) {
10417 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10418 }
10419 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010420 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010421 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010422 if (newDefaultAgent != null) {
10423 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10424 newDefaultAgent.networkInfo);
10425 } else {
10426 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10427 }
10428 }
10429 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10430 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010431 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010432 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010433 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010434 }
10435 }
10436 }
10437
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010438 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010439 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010440 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010441 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010442 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010443 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10444 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010445 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10446 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010447 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010448 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010449 } else {
10450 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10451 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010452 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010453 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010454
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010455 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10456 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10457 }
10458
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010459 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010460 * Returns the list of all interfaces that could be used by network traffic that does not
10461 * explicitly specify a network. This includes the default network, but also all VPNs that are
10462 * currently connected.
10463 *
10464 * Must be called on the handler thread.
10465 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010466 @NonNull
10467 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010468 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010469 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010470 final Set<Integer> activeNetIds = new ArraySet<>();
10471 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10472 if (nri.isBeingSatisfied()) {
10473 activeNetIds.add(nri.getSatisfier().network().netId);
10474 }
10475 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010476 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010477 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010478 defaultNetworks.add(nai.network);
10479 }
10480 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010481 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010482 }
10483
10484 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010485 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10486 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010487 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010488 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010489 ensureRunningOnConnectivityServiceThread();
10490 String activeIface = null;
10491 LinkProperties activeLinkProperties = getActiveLinkProperties();
10492 if (activeLinkProperties != null) {
10493 activeIface = activeLinkProperties.getInterfaceName();
10494 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010495
junyulai2050bed2021-01-23 09:46:34 +080010496 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010497 try {
junyulaide41fc22021-01-22 22:46:01 +080010498 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010499 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010500 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10501 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010502 } catch (Exception ignored) {
10503 }
10504 }
10505
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010506 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010507 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010508 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010509 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010510 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010511
10512 if (!TextUtils.isEmpty(settingUrl)) {
10513 return settingUrl;
10514 }
10515
10516 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010517 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010518 if (!TextUtils.isEmpty(settingUrl)) {
10519 return settingUrl;
10520 }
10521
10522 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010523 }
10524
10525 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010526 public void startNattKeepalive(Network network, int intervalSeconds,
10527 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010528 enforceKeepalivePermission();
10529 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010530 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010531 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10532 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010533 // false and set the underpinned network to null because there is no way and no
10534 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10535 // deprecated method.
10536 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010537 }
10538
10539 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010540 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010541 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010542 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010543 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010544 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010545 mKeepaliveTracker.startNattKeepalive(
10546 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010547 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10548 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010549 } finally {
10550 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10551 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010552 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10553 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010554 }
10555 }
junyulaid05a1922019-01-15 11:32:44 +080010556 }
10557
10558 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010559 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010560 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010561 try {
10562 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010563 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010564 mKeepaliveTracker.startTcpKeepalive(
10565 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10566 } finally {
10567 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10568 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010569 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10570 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010571 }
10572 }
junyulai0835a1e2019-01-08 20:04:33 +080010573 }
10574
10575 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010576 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010577 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010578 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10579 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010580 }
10581
10582 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090010583 public int[] getSupportedKeepalives() {
10584 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10585 // Backwards compatibility with CTS 13
10586 android.Manifest.permission.QUERY_ALL_PACKAGES);
10587
10588 return BinderUtils.withCleanCallingIdentity(() ->
10589 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10590 }
10591
10592 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010593 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010594 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010595
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010596 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010597 final long token = Binder.clearCallingIdentity();
10598 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010599 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10600 UserHandle.getUserHandleForUid(uid))) {
10601 return;
10602 }
10603
Heemin Seogdb8489d2019-06-12 09:21:44 -070010604 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10605 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010606
10607 // Turn airplane mode off
10608 setAirplaneMode(false);
10609
10610 // restore private DNS settings to default mode (opportunistic)
10611 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10612 UserHandle.getUserHandleForUid(uid))) {
10613 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10614 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10615 }
10616
10617 Settings.Global.putString(mContext.getContentResolver(),
10618 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010619 } finally {
10620 Binder.restoreCallingIdentity(token);
10621 }
Stuart Scottd5463642015-04-02 18:00:02 -070010622 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010623
Ricky Wai7097cc92018-01-23 04:09:45 +000010624 @Override
10625 public byte[] getNetworkWatchlistConfigHash() {
10626 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10627 if (nwm == null) {
10628 loge("Unable to get NetworkWatchlistManager");
10629 return null;
10630 }
10631 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10632 return nwm.getWatchlistConfigHash();
10633 }
10634
Hugo Benichibe0c7652016-05-31 16:28:06 +090010635 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010636 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010637 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010638 }
Hugo Benichif4210292017-04-21 15:07:12 +090010639
10640 private static boolean toBool(int encodedBoolean) {
10641 return encodedBoolean != 0; // Only 0 means false.
10642 }
10643
10644 private static int encodeBool(boolean b) {
10645 return b ? 1 : 0;
10646 }
mswest4632928412018-03-12 10:34:34 -070010647
10648 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010649 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10650 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10651 @NonNull String[] args) {
10652 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10653 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010654 }
10655
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010656 private Boolean parseBooleanArgument(final String arg) {
10657 if ("true".equals(arg)) {
10658 return true;
10659 } else if ("false".equals(arg)) {
10660 return false;
10661 } else {
10662 return null;
10663 }
10664 }
10665
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010666 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010667 @Override
10668 public int onCommand(String cmd) {
10669 if (cmd == null) {
10670 return handleDefaultCommands(cmd);
10671 }
10672 final PrintWriter pw = getOutPrintWriter();
10673 try {
10674 switch (cmd) {
10675 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010676 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
10677 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070010678 final String action = getNextArg();
10679 if ("enable".equals(action)) {
10680 setAirplaneMode(true);
10681 return 0;
10682 } else if ("disable".equals(action)) {
10683 setAirplaneMode(false);
10684 return 0;
10685 } else if (action == null) {
10686 final ContentResolver cr = mContext.getContentResolver();
10687 final int enabled = Settings.Global.getInt(cr,
10688 Settings.Global.AIRPLANE_MODE_ON);
10689 pw.println(enabled == 0 ? "disabled" : "enabled");
10690 return 0;
10691 } else {
10692 onHelp();
10693 return -1;
10694 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010695 case "set-chain3-enabled": {
10696 final Boolean enabled = parseBooleanArgument(getNextArg());
10697 if (null == enabled) {
10698 onHelp();
10699 return -1;
10700 }
10701 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
10702 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
10703 enabled);
10704 return 0;
10705 }
10706 case "get-chain3-enabled": {
10707 final boolean chainEnabled = getFirewallChainEnabled(
10708 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
10709 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
10710 return 0;
10711 }
10712 case "set-package-networking-enabled": {
10713 final Boolean enabled = parseBooleanArgument(getNextArg());
10714 final String packageName = getNextArg();
10715 if (null == enabled || null == packageName) {
10716 onHelp();
10717 return -1;
10718 }
10719 // Throws NameNotFound if the package doesn't exist.
10720 final int appId = setPackageFirewallRule(
10721 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
10722 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
10723 final String msg = (enabled ? "Enabled" : "Disabled")
10724 + " networking for " + packageName + ", appId " + appId;
10725 Log.i(TAG, msg);
10726 pw.println(msg);
10727 return 0;
10728 }
10729 case "get-package-networking-enabled": {
10730 final String packageName = getNextArg();
10731 final int rule = getPackageFirewallRule(
10732 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
10733 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
10734 pw.println(packageName + ":" + "allow");
10735 } else if (FIREWALL_RULE_DENY == rule) {
10736 pw.println(packageName + ":" + "deny");
10737 } else {
10738 throw new IllegalStateException("Unknown rule " + rule + " for package "
10739 + packageName);
10740 }
10741 return 0;
10742 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010743 case "reevaluate":
10744 // Usage : adb shell cmd connectivity reevaluate <netId>
10745 // If netId is omitted, then reevaluate the default network
10746 final String netId = getNextArg();
10747 final NetworkAgentInfo nai;
10748 if (null == netId) {
10749 // Note that the command is running on the wrong thread to call this,
10750 // so this could in principle return stale data. But it can't crash.
10751 nai = getDefaultNetwork();
10752 } else {
10753 // If netId can't be parsed, this throws NumberFormatException, which
10754 // is passed back to adb who prints it.
10755 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10756 }
10757 if (null == nai) {
10758 pw.println("Unknown network (net ID not found or no default network)");
10759 return 0;
10760 }
10761 Log.d(TAG, "Reevaluating network " + nai.network);
10762 reportNetworkConnectivity(nai.network, !nai.isValidated());
10763 return 0;
mswest4632928412018-03-12 10:34:34 -070010764 default:
10765 return handleDefaultCommands(cmd);
10766 }
10767 } catch (Exception e) {
10768 pw.println(e);
10769 }
10770 return -1;
10771 }
10772
10773 @Override
10774 public void onHelp() {
10775 PrintWriter pw = getOutPrintWriter();
10776 pw.println("Connectivity service commands:");
10777 pw.println(" help");
10778 pw.println(" Print this help text.");
10779 pw.println(" airplane-mode [enable|disable]");
10780 pw.println(" Turn airplane mode on or off.");
10781 pw.println(" airplane-mode");
10782 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010783 pw.println(" set-chain3-enabled [true|false]");
10784 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
10785 pw.println(" get-chain3-enabled");
10786 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
10787 pw.println(" set-package-networking-enabled [true|false] [package name]");
10788 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
10789 + " no effect if the chain is disabled.");
10790 pw.println(" get-package-networking-enabled [package name]");
10791 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
mswest4632928412018-03-12 10:34:34 -070010792 }
10793 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010794
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010795 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010796 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10797 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10798 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010799 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010800 }
10801
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010802 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10803 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010804 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10805 final TransportInfo newInfo = nc.getTransportInfo();
10806 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10807 return;
10808 }
10809 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010810 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010811 }
10812 }
10813
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010814 /**
10815 * @param connectionInfo the connection to resolve.
10816 * @return {@code uid} if the connection is found and the app has permission to observe it
10817 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10818 * connection is not found.
10819 */
10820 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010821 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10822 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10823 }
10824
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010825 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010826 connectionInfo.local, connectionInfo.remote);
10827
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010828 if (uid == INVALID_UID) return uid; // Not found.
10829
10830 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10831 // VPN, if any, that applies to the UID that owns the connection.
10832 if (checkNetworkStackPermission()) return uid;
10833
10834 final NetworkAgentInfo vpn = getVpnForUid(uid);
10835 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010836 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010837 return INVALID_UID;
10838 }
10839
10840 return uid;
10841 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010842
Benedict Wong493e04b2018-11-09 14:45:34 -080010843 /**
10844 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10845 *
10846 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10847 */
10848 @Override
10849 public IBinder startOrGetTestNetworkService() {
10850 synchronized (mTNSLock) {
10851 TestNetworkService.enforceTestNetworkPermissions(mContext);
10852
10853 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010854 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010855 }
10856
10857 return mTNS;
10858 }
10859 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010860
Cody Kesting73708bf2019-12-18 10:57:50 -080010861 /**
10862 * Handler used for managing all Connectivity Diagnostics related functions.
10863 *
10864 * @see android.net.ConnectivityDiagnosticsManager
10865 *
10866 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10867 */
10868 @VisibleForTesting
10869 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010870 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10871
Cody Kesting73708bf2019-12-18 10:57:50 -080010872 /**
10873 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10874 * android.net.ConnectivityDiagnosticsManager}.
10875 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10876 * NetworkRequestInfo to be registered
10877 */
10878 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10879
10880 /**
10881 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10882 * android.net.ConnectivityDiagnosticsManager}.
10883 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10884 * arg1 = the uid of the caller
10885 */
10886 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10887
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010888 /**
10889 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010890 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010891 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10892 * NetworkMonitor.
10893 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010894 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010895 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010896
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010897 /**
10898 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10899 * been detected on the network.
10900 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10901 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10902 * arg2 = NetID.
10903 * data = PersistableBundle of extras passed from NetworkMonitor.
10904 */
10905 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10906
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010907 /**
10908 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10909 * the platform. This event will invoke {@link
10910 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10911 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070010912 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010913 */
10914 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
10915
Cody Kesting73708bf2019-12-18 10:57:50 -080010916 private ConnectivityDiagnosticsHandler(Looper looper) {
10917 super(looper);
10918 }
10919
10920 @Override
10921 public void handleMessage(Message msg) {
10922 switch (msg.what) {
10923 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10924 handleRegisterConnectivityDiagnosticsCallback(
10925 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
10926 break;
10927 }
10928 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10929 handleUnregisterConnectivityDiagnosticsCallback(
10930 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
10931 break;
10932 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010933 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010934 final ConnectivityReportEvent reportEvent =
10935 (ConnectivityReportEvent) msg.obj;
10936
Aaron Huang959d3642021-01-21 15:47:41 +080010937 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010938 break;
10939 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010940 case EVENT_DATA_STALL_SUSPECTED: {
10941 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080010942 final Pair<Long, PersistableBundle> arg =
10943 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010944 if (nai == null) break;
10945
Aaron Huang959d3642021-01-21 15:47:41 +080010946 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010947 break;
10948 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010949 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070010950 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010951 break;
10952 }
10953 default: {
10954 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
10955 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010956 }
10957 }
10958 }
10959
10960 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
10961 @VisibleForTesting
10962 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
10963 @NonNull private final IConnectivityDiagnosticsCallback mCb;
10964 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010965 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010966
10967 @VisibleForTesting
10968 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010969 @NonNull IConnectivityDiagnosticsCallback cb,
10970 @NonNull NetworkRequestInfo nri,
10971 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010972 mCb = cb;
10973 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010974 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010975 }
10976
10977 @Override
10978 public void binderDied() {
10979 log("ConnectivityDiagnosticsCallback IBinder died.");
10980 unregisterConnectivityDiagnosticsCallback(mCb);
10981 }
10982 }
10983
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010984 /**
10985 * Class used for sending information from {@link
10986 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
10987 */
10988 private static class NetworkTestedResults {
10989 private final int mNetId;
10990 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010991 @Nullable private final String mRedirectUrl;
10992
10993 private NetworkTestedResults(
10994 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
10995 mNetId = netId;
10996 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010997 mRedirectUrl = redirectUrl;
10998 }
10999 }
11000
11001 /**
11002 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11003 * ConnectivityDiagnosticsHandler}.
11004 */
11005 private static class ConnectivityReportEvent {
11006 private final long mTimestampMillis;
11007 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011008 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011009
Aaron Huang959d3642021-01-21 15:47:41 +080011010 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11011 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011012 mTimestampMillis = timestampMillis;
11013 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011014 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011015 }
11016 }
11017
Cody Kestingf1120be2020-08-03 18:01:40 -070011018 /**
11019 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11020 * ConnectivityDiagnosticsHandler}.
11021 */
11022 private static class ReportedNetworkConnectivityInfo {
11023 public final boolean hasConnectivity;
11024 public final boolean isNetworkRevalidating;
11025 public final int reporterUid;
11026 @NonNull public final NetworkAgentInfo nai;
11027
11028 private ReportedNetworkConnectivityInfo(
11029 boolean hasConnectivity,
11030 boolean isNetworkRevalidating,
11031 int reporterUid,
11032 @NonNull NetworkAgentInfo nai) {
11033 this.hasConnectivity = hasConnectivity;
11034 this.isNetworkRevalidating = isNetworkRevalidating;
11035 this.reporterUid = reporterUid;
11036 this.nai = nai;
11037 }
11038 }
11039
Cody Kesting73708bf2019-12-18 10:57:50 -080011040 private void handleRegisterConnectivityDiagnosticsCallback(
11041 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11042 ensureRunningOnConnectivityServiceThread();
11043
11044 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011045 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011046 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11047
James Mattis64b8b0f2020-11-24 17:40:49 -080011048 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11049 // confusing for these networks to change when an NRI is satisfied in another layer.
11050 if (nri.isMultilayerRequest()) {
11051 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11052 + "network requests.");
11053 }
11054
Cody Kesting73708bf2019-12-18 10:57:50 -080011055 // This means that the client registered the same callback multiple times. Do
11056 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011057 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011058 if (VDBG) log("Diagnostics callback is already registered");
11059
11060 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11061 // incremented when the NetworkRequestInfo is created as part of
11062 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011063 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011064 return;
11065 }
11066
Cody Kesting31f1ff62020-03-05 10:46:02 -080011067 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011068
11069 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011070 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011071 } catch (RemoteException e) {
11072 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011073 return;
11074 }
11075
11076 // Once registered, provide ConnectivityReports for matching Networks
11077 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11078 synchronized (mNetworkForNetId) {
11079 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11080 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011081 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11082 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011083 matchingNetworks.add(nai);
11084 }
11085 }
11086 }
11087 for (final NetworkAgentInfo nai : matchingNetworks) {
11088 final ConnectivityReport report = nai.getConnectivityReport();
11089 if (report == null) {
11090 continue;
11091 }
11092 if (!checkConnectivityDiagnosticsPermissions(
11093 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11094 continue;
11095 }
11096
11097 try {
11098 cb.onConnectivityReportAvailable(report);
11099 } catch (RemoteException e) {
11100 // Exception while sending the ConnectivityReport. Move on to the next network.
11101 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011102 }
11103 }
11104
11105 private void handleUnregisterConnectivityDiagnosticsCallback(
11106 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11107 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011108 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011109
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011110 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11111 mConnectivityDiagnosticsCallbacks.remove(iCb);
11112 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011113 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11114 return;
11115 }
11116
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011117 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011118
Cody Kesting70fa2b22020-12-02 12:16:56 -080011119 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11120 // (if the Binder died)
11121 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11122 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011123 return;
11124 }
11125
Cody Kesting46cb1672020-03-04 13:35:20 -080011126 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11127 // incremented when the NetworkRequestInfo is created as part of
11128 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011129 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011130
Cody Kesting31f1ff62020-03-05 10:46:02 -080011131 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011132 }
11133
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011134 private void handleNetworkTestedWithExtras(
11135 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11136 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011137 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011138 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011139 final ConnectivityReport report =
11140 new ConnectivityReport(
11141 reportEvent.mNai.network,
11142 reportEvent.mTimestampMillis,
11143 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011144 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011145 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011146 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011147
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011148 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011149 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011150 for (final IConnectivityDiagnosticsCallback cb : results) {
11151 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011152 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011153 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011154 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011155 }
11156 }
11157 }
11158
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011159 private void handleDataStallSuspected(
11160 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11161 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011162 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011163 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011164 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011165 new DataStallReport(
11166 nai.network,
11167 timestampMillis,
11168 detectionMethod,
11169 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011170 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011171 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011172 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011173 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011174 for (final IConnectivityDiagnosticsCallback cb : results) {
11175 try {
11176 cb.onDataStallSuspected(report);
11177 } catch (RemoteException ex) {
11178 loge("Error invoking onDataStallSuspected", ex);
11179 }
11180 }
11181 }
11182
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011183 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011184 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11185 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11186 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11187
11188 // If the Network is being re-validated as a result of this call to
11189 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11190 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011191 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011192 getMatchingPermissionedCallbacks(
11193 nai,
11194 reportedNetworkConnectivityInfo.isNetworkRevalidating
11195 ? Process.INVALID_UID
11196 : reportedNetworkConnectivityInfo.reporterUid);
11197
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011198 for (final IConnectivityDiagnosticsCallback cb : results) {
11199 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011200 cb.onNetworkConnectivityReported(
11201 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011202 } catch (RemoteException ex) {
11203 loge("Error invoking onNetworkConnectivityReported", ex);
11204 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011205
11206 // If the Network isn't re-validating, also provide the cached report. If there is no
11207 // cached report, the Network is still being validated and a report will be sent once
11208 // validation is complete. Note that networks which never undergo validation will still
11209 // have a cached ConnectivityReport with RESULT_SKIPPED.
11210 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11211 try {
11212 cb.onConnectivityReportAvailable(cachedReport);
11213 } catch (RemoteException ex) {
11214 loge("Error invoking onConnectivityReportAvailable", ex);
11215 }
11216 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011217 }
11218 }
11219
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011220 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011221 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11222 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011223 sanitized.setUids(null);
11224 sanitized.setAdministratorUids(new int[0]);
11225 sanitized.setOwnerUid(Process.INVALID_UID);
11226 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011227 }
11228
Cody Kestingf1120be2020-08-03 18:01:40 -070011229 /**
11230 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11231 *
11232 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11233 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011234 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011235 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011236 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011237 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011238 mConnectivityDiagnosticsCallbacks.entrySet()) {
11239 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11240 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011241
James Mattis64b8b0f2020-11-24 17:40:49 -080011242 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011243 if (!nai.satisfies(nri.mRequests.get(0))) {
11244 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011245 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011246
11247 // UID for this callback must either be:
11248 // - INVALID_UID (which sends callbacks to all UIDs), or
11249 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11250 // notified as a result)
11251 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11252 continue;
11253 }
11254
11255 if (!checkConnectivityDiagnosticsPermissions(
11256 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11257 continue;
11258 }
11259
11260 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011261 }
11262 return results;
11263 }
11264
Cody Kesting7474f672021-05-11 14:22:40 -070011265 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11266 @NonNull NetworkAgentInfo nai) {
11267 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11268 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11269 }
11270
Cody Kesting160ef392021-05-05 13:17:22 -070011271 private boolean hasLocationPermission(String packageName, int uid) {
11272 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11273 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11274 // call in a try-catch.
11275 try {
11276 if (!mLocationPermissionChecker.checkLocationPermission(
11277 packageName, null /* featureId */, uid, null /* message */)) {
11278 return false;
11279 }
11280 } catch (SecurityException e) {
11281 return false;
11282 }
11283
11284 return true;
11285 }
11286
11287 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11288 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011289 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011290 && virtual.networkCapabilities.getOwnerUid() == uid
11291 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11292 return true;
11293 }
11294 }
11295
11296 return false;
11297 }
11298
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011299 @VisibleForTesting
11300 boolean checkConnectivityDiagnosticsPermissions(
11301 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
11302 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
11303 return true;
11304 }
11305
Cody Kesting160ef392021-05-05 13:17:22 -070011306 // Administrator UIDs also contains the Owner UID
11307 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11308 if (!CollectionUtils.contains(administratorUids, callbackUid)
11309 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011310 return false;
11311 }
11312
Cody Kesting7474f672021-05-11 14:22:40 -070011313 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11314 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011315 }
11316
Cody Kestingd199a9d2019-12-17 12:55:28 -080011317 @Override
11318 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011319 @NonNull IConnectivityDiagnosticsCallback callback,
11320 @NonNull NetworkRequest request,
11321 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011322 Objects.requireNonNull(callback, "callback must not be null");
11323 Objects.requireNonNull(request, "request must not be null");
11324 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11325
Cody Kesting73708bf2019-12-18 10:57:50 -080011326 if (request.legacyType != TYPE_NONE) {
11327 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11328 + " Please use NetworkCapabilities instead.");
11329 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011330 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011331 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011332
11333 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11334 // and administrator uids to be safe.
11335 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011336 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011337
11338 final NetworkRequest requestWithId =
11339 new NetworkRequest(
11340 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11341
11342 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11343 //
11344 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11345 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11346 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011347 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011348 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011349 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011350
11351 mConnectivityDiagnosticsHandler.sendMessage(
11352 mConnectivityDiagnosticsHandler.obtainMessage(
11353 ConnectivityDiagnosticsHandler
11354 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11355 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011356 }
11357
11358 @Override
11359 public void unregisterConnectivityDiagnosticsCallback(
11360 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011361 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011362 mConnectivityDiagnosticsHandler.sendMessage(
11363 mConnectivityDiagnosticsHandler.obtainMessage(
11364 ConnectivityDiagnosticsHandler
11365 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011366 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011367 0,
11368 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011369 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011370
Yan Yanfe96dde2022-12-05 23:00:01 +000011371 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11372 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11373 if (underlyingNetworks == null) return false;
11374
11375 for (Network network : underlyingNetworks) {
11376 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11377 return true;
11378 }
11379 }
11380 return false;
11381 }
11382
Cody Kestingf53a0752020-04-15 12:33:28 -070011383 @Override
11384 public void simulateDataStall(int detectionMethod, long timestampMillis,
11385 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011386 Objects.requireNonNull(network, "network must not be null");
11387 Objects.requireNonNull(extras, "extras must not be null");
11388
paulhu3ffffe72021-09-16 10:15:22 +080011389 enforceAnyPermissionOf(mContext,
11390 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011391 android.Manifest.permission.NETWORK_STACK);
11392 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011393 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11394 throw new SecurityException(
11395 "Data Stall simulation is only possible for test networks or networks built on"
11396 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011397 }
11398
11399 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011400 if (nai == null
11401 || (nai.creatorUid != mDeps.getCallingUid()
11402 && nai.creatorUid != Process.SYSTEM_UID)) {
11403 throw new SecurityException(
11404 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011405 }
11406
Cody Kesting652e3ec2020-05-21 12:08:21 -070011407 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11408 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11409 // Data Stall information as a DataStallReportParcelable and passing to
11410 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11411 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011412 final DataStallReportParcelable p = new DataStallReportParcelable();
11413 p.timestampMillis = timestampMillis;
11414 p.detectionMethod = detectionMethod;
11415
11416 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11417 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11418 }
11419 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11420 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11421 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11422 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11423 }
11424
Serik Beketayevec8ad212020-12-07 22:43:07 -080011425 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011426 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011427
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011428 /**
11429 * Class to hold the information for network activity change event from idle timers
11430 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
11431 */
11432 private static final class NetworkActivityParams {
11433 public final boolean isActive;
11434 // Label used for idle timer. Transport type is used as label.
11435 // label is int since NMS was using the identifier as int, and it has not been changed
11436 public final int label;
11437 public final long timestampNs;
11438 // Uid represents the uid that was responsible for waking the radio.
11439 // -1 for no uid and uid is -1 if isActive is false.
11440 public final int uid;
11441
11442 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
11443 this.isActive = isActive;
11444 this.label = label;
11445 this.timestampNs = timestampNs;
11446 this.uid = uid;
11447 }
11448 }
11449
lucaslin66f44212021-02-23 01:12:55 +080011450 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11451 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011452 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080011453 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011454 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
11455 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080011456 }
lucaslin37a16d92021-01-21 19:48:09 +080011457
11458 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011459 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011460 mHandler.post(() -> {
11461 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011462 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011463 }
11464 });
lucaslin37a16d92021-01-21 19:48:09 +080011465 }
11466
11467 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011468 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011469 mHandler.post(() -> {
11470 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011471 nai.clatd.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011472 }
11473 });
lucaslin66f44212021-02-23 01:12:55 +080011474 }
11475 }
11476
lucaslin1a8b4c62021-01-21 02:02:55 +080011477 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11478
11479 /**
11480 * Class used for updating network activity tracking with netd and notify network activity
11481 * changes.
11482 */
11483 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011484 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011485 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011486 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011487 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080011488 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11489 new RemoteCallbackList<>();
11490 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090011491 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011492 // If there is no default network, default network is considered active to keep the existing
11493 // behavior. Initial value is used until first connect to the default network.
11494 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011495 // Key is netId. Value is configured idle timer information.
11496 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080011497
Chalard Jean46bfbf02022-02-02 00:56:25 +090011498 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011499 public final int timeout;
11500 public final int transportType;
11501
11502 IdleTimerParams(int timeout, int transport) {
11503 this.timeout = timeout;
11504 this.transportType = transport;
11505 }
11506 }
11507
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011508 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011509 @NonNull Handler handler) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011510 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011511 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011512 mHandler = handler;
11513 }
11514
11515 private void ensureRunningOnConnectivityServiceThread() {
11516 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
11517 throw new IllegalStateException("Not running on ConnectivityService thread: "
11518 + Thread.currentThread().getName());
11519 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011520 }
11521
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011522 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011523 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011524 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011525 // This activity change is not for the current default network.
11526 // This can happen if netd callback post activity change event message but
11527 // the default network is lost before processing this message.
11528 return;
11529 }
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011530 sendDataActivityBroadcast(transportTypeToLegacyType(activityParams.label),
11531 activityParams.isActive, activityParams.timestampNs);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011532 mIsDefaultNetworkActive = activityParams.isActive;
11533 if (mIsDefaultNetworkActive) {
11534 reportNetworkActive();
lucaslin66f44212021-02-23 01:12:55 +080011535 }
11536 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011537
lucaslin1193a5d2021-01-21 02:04:15 +080011538 private void reportNetworkActive() {
11539 final int length = mNetworkActivityListeners.beginBroadcast();
11540 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
11541 try {
11542 for (int i = 0; i < length; i++) {
11543 try {
11544 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
11545 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011546 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080011547 }
11548 }
11549 } finally {
11550 mNetworkActivityListeners.finishBroadcast();
11551 }
11552 }
11553
lucaslin1a8b4c62021-01-21 02:02:55 +080011554 // This is deprecated and only to support legacy use cases.
11555 private int transportTypeToLegacyType(int type) {
11556 switch (type) {
11557 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011558 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080011559 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011560 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080011561 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011562 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080011563 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011564 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080011565 default:
11566 loge("Unexpected transport in transportTypeToLegacyType: " + type);
11567 }
11568 return ConnectivityManager.TYPE_NONE;
11569 }
11570
11571 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
11572 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
11573 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
11574 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
11575 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
11576 final long ident = Binder.clearCallingIdentity();
11577 try {
11578 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
11579 RECEIVE_DATA_ACTIVITY_CHANGE,
11580 null /* resultReceiver */,
11581 null /* scheduler */,
11582 0 /* initialCode */,
11583 null /* initialData */,
11584 null /* initialExtra */);
11585 } finally {
11586 Binder.restoreCallingIdentity(ident);
11587 }
11588 }
11589
11590 /**
11591 * Setup data activity tracking for the given network.
11592 *
11593 * Every {@code setupDataActivityTracking} should be paired with a
11594 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090011595 *
11596 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080011597 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090011598 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011599 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011600 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080011601
11602 final int timeout;
11603 final int type;
11604
11605 if (networkAgent.networkCapabilities.hasTransport(
11606 NetworkCapabilities.TRANSPORT_CELLULAR)) {
11607 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011608 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080011609 10);
11610 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11611 } else if (networkAgent.networkCapabilities.hasTransport(
11612 NetworkCapabilities.TRANSPORT_WIFI)) {
11613 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011614 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080011615 15);
11616 type = NetworkCapabilities.TRANSPORT_WIFI;
11617 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011618 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080011619 }
11620
lucaslinb961efc2021-01-21 02:03:17 +080011621 updateRadioPowerState(true /* isActive */, type);
11622
lucaslin1a8b4c62021-01-21 02:02:55 +080011623 if (timeout > 0 && iface != null) {
11624 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011625 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, type));
Motomu Utsumic298cf02023-05-31 12:06:12 +090011626 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
Motomu Utsumi6225d572023-05-29 15:08:57 +090011627 return true;
lucaslin1a8b4c62021-01-21 02:02:55 +080011628 } catch (Exception e) {
11629 // You shall not crash!
11630 loge("Exception in setupDataActivityTracking " + e);
11631 }
11632 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011633 return false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011634 }
11635
11636 /**
11637 * Remove data activity tracking when network disconnects.
11638 */
11639 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
11640 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011641 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080011642 final NetworkCapabilities caps = networkAgent.networkCapabilities;
11643
lucaslinb961efc2021-01-21 02:03:17 +080011644 if (iface == null) return;
11645
11646 final int type;
11647 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
11648 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11649 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
11650 type = NetworkCapabilities.TRANSPORT_WIFI;
11651 } else {
11652 return; // do not track any other networks
11653 }
11654
11655 try {
11656 updateRadioPowerState(false /* isActive */, type);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011657 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011658 if (params == null) {
11659 // IdleTimer is not added if the configured timeout is 0 or negative value
11660 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080011661 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011662 mActiveIdleTimers.remove(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011663 // The call fails silently if no idle timer setup for this interface
11664 mNetd.idletimerRemoveInterface(iface, params.timeout,
11665 Integer.toString(params.transportType));
lucaslinb961efc2021-01-21 02:03:17 +080011666 } catch (Exception e) {
11667 // You shall not crash!
11668 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080011669 }
11670 }
11671
Motomu Utsumi6225d572023-05-29 15:08:57 +090011672 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
11673 boolean hasIdleTimer) {
11674 if (defaultNetwork != null) {
11675 mIsDefaultNetworkActive = true;
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011676 // Callbacks are called only when the network has the idle timer.
11677 if (hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011678 reportNetworkActive();
11679 }
11680 } else {
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011681 // If there is no default network, default network is considered active to keep the
11682 // existing behavior.
11683 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090011684 }
11685 }
11686
lucaslin1a8b4c62021-01-21 02:02:55 +080011687 /**
11688 * Update data activity tracking when network state is updated.
11689 */
11690 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
11691 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011692 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi6225d572023-05-29 15:08:57 +090011693 boolean hasIdleTimer = false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011694 if (newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011695 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080011696 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011697 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
lucaslin1a8b4c62021-01-21 02:02:55 +080011698 if (oldNetwork != null) {
11699 removeDataActivityTracking(oldNetwork);
11700 }
11701 }
lucaslinb961efc2021-01-21 02:03:17 +080011702
11703 private void updateRadioPowerState(boolean isActive, int transportType) {
11704 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
11705 switch (transportType) {
11706 case NetworkCapabilities.TRANSPORT_CELLULAR:
11707 bs.reportMobileRadioPowerState(isActive, NO_UID);
11708 break;
11709 case NetworkCapabilities.TRANSPORT_WIFI:
11710 bs.reportWifiRadioPowerState(isActive, NO_UID);
11711 break;
11712 default:
11713 logw("Untracked transport type:" + transportType);
11714 }
11715 }
lucaslin1193a5d2021-01-21 02:04:15 +080011716
11717 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011718 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080011719 }
11720
11721 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
11722 mNetworkActivityListeners.register(l);
11723 }
11724
11725 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
11726 mNetworkActivityListeners.unregister(l);
11727 }
lucaslin012f7a12021-01-21 02:04:35 +080011728
11729 public void dump(IndentingPrintWriter pw) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011730 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
11731 pw.println("Idle timers:");
11732 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011733 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
11734 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
11735 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080011736 pw.print(" timeout="); pw.print(params.timeout);
11737 pw.print(" type="); pw.println(params.transportType);
11738 }
Motomu Utsumic298cf02023-05-31 12:06:12 +090011739 } catch (Exception e) {
11740 // mActiveIdleTimers should only be accessed from handler thread, except dump().
11741 // As dump() is never called in normal usage, it would be needlessly expensive
11742 // to lock the collection only for its benefit.
11743 // Also, mActiveIdleTimers is not expected to be updated frequently.
11744 // So catching the exception and logging.
11745 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080011746 }
11747 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011748 }
James Mattis47db0582021-01-01 14:13:35 -080011749
Daniel Brightf9e945b2020-06-15 16:10:01 -070011750 /**
11751 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
11752 *
11753 * @param socketInfo the socket information
11754 * @param callback the callback to register
11755 */
11756 @Override
11757 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
11758 @NonNull final IQosCallback callback) {
11759 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
11760 if (nai == null || nai.networkCapabilities == null) {
11761 try {
11762 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
11763 } catch (final RemoteException ex) {
11764 loge("registerQosCallbackInternal: RemoteException", ex);
11765 }
11766 return;
11767 }
11768 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
11769 }
11770
11771 /**
11772 * Register a {@link IQosCallback} with base {@link QosFilter}.
11773 *
11774 * @param filter the filter to register
11775 * @param callback the callback to register
11776 * @param nai the agent information related to the filter's network
11777 */
11778 @VisibleForTesting
11779 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
11780 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011781 Objects.requireNonNull(filter, "filter must be non-null");
11782 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011783
11784 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080011785 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
11786 // on this network is unregistered when the app loses permission or b) no QoS
11787 // callbacks are sent for restricted networks unless the app currently has permission
11788 // to access restricted networks.
11789 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070011790 }
11791 mQosCallbackTracker.registerCallback(callback, filter, nai);
11792 }
11793
11794 /**
11795 * Unregisters the given callback.
11796 *
11797 * @param callback the callback to unregister
11798 */
11799 @Override
11800 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011801 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011802 mQosCallbackTracker.unregisterCallback(callback);
11803 }
James Mattis47db0582021-01-01 14:13:35 -080011804
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011805 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
11806 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
11807 // Enterprise device can be fully managed like device owner and such use case
11808 // also should be supported. Calling app check for work profile and fully managed device
11809 // is already done in DevicePolicyManager.
11810 // This check is an extra caution to be sure device is fully managed or not.
11811 final UserManager um = mContext.getSystemService(UserManager.class);
11812 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
11813 if (um.isManagedProfile(profile.getIdentifier())) {
11814 return true;
11815 }
Chalard Jeandf29a852023-05-29 17:02:43 +090011816 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011817 return false;
11818 }
11819
James Mattis45d81842021-01-10 14:24:24 -080011820 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011821 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011822 *
11823 * See the documentation for the individual preferences for a description of the supported
11824 * behaviors.
11825 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011826 * @param profile If the device owner is set, any profile is allowed.
11827 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011828 * @param preferences the list of profile network preferences for the
11829 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011830 * @param listener an optional listener to listen for completion of the operation.
11831 */
11832 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011833 public void setProfileNetworkPreferences(
11834 @NonNull final UserHandle profile,
11835 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090011836 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011837 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011838 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011839
11840 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011841 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11842 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11843 .build();
11844 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011845 }
11846
paulhu3ffffe72021-09-16 10:15:22 +080011847 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011848 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011849 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011850 }
11851 if (profile.getIdentifier() < 0) {
11852 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11853 + "UserHandle.CURRENT not supported)");
11854 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011855 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11856 throw new IllegalArgumentException("Profile must be a managed profile "
11857 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011858 }
paulhuaa0743d2021-05-26 21:56:03 +080011859
Chalard Jean0606fc82022-12-14 20:34:43 +090011860 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011861 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011862 for (final ProfileNetworkPreference preference : preferences) {
11863 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011864 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011865 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011866 switch (preference.getPreference()) {
11867 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11868 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011869 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011870 if (preference.getPreferenceEnterpriseId() != 0) {
11871 throw new IllegalArgumentException(
11872 "Invalid enterprise identifier in setProfileNetworkPreferences");
11873 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011874 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011875 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11876 blockingNonEnterprise = true;
11877 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011878 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11879 allowFallback = false;
11880 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011881 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011882 // This code is needed even though there is a check later on,
11883 // because isRangeAlreadyInPreferenceList assumes that every preference
11884 // has a UID list.
11885 if (hasDefaultPreference) {
11886 throw new IllegalArgumentException(
11887 "Default profile preference should not be set along with other "
11888 + "preference");
11889 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011890 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11891 throw new IllegalArgumentException(
11892 "Invalid enterprise identifier in setProfileNetworkPreferences");
11893 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011894 final Set<UidRange> uidRangeSet =
11895 getUidListToBeAppliedForNetworkPreference(profile, preference);
11896 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11897 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11898 } else {
11899 throw new IllegalArgumentException(
11900 "Overlapping uid range in setProfileNetworkPreferences");
11901 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011902 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011903 nc.addEnterpriseId(
11904 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011905 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11906 break;
11907 default:
11908 throw new IllegalArgumentException(
11909 "Invalid preference in setProfileNetworkPreferences");
11910 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011911 preferenceList.add(new ProfileNetworkPreferenceInfo(
11912 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011913 if (hasDefaultPreference && preferenceList.size() > 1) {
11914 throw new IllegalArgumentException(
11915 "Default profile preference should not be set along with other preference");
11916 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011917 }
11918 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011919 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011920 }
11921
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011922 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
11923 @NonNull final UserHandle profile,
11924 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
11925 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080011926 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
11927 profileNetworkPreference.getIncludedUids());
11928
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011929 if (uidRangeSet.size() > 0) {
11930 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
11931 throw new IllegalArgumentException(
11932 "Allow uid range is outside the uid range of profile.");
11933 }
11934 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080011935 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011936 profileNetworkPreference.getExcludedUids());
11937 if (disallowUidRangeSet.size() > 0) {
11938 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
11939 throw new IllegalArgumentException(
11940 "disallow uid range is outside the uid range of profile.");
11941 }
11942 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
11943 disallowUidRangeSet);
11944 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011945 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011946 uidRangeSet.add(profileUids);
11947 }
11948 }
11949 return uidRangeSet;
11950 }
11951
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011952 private boolean isEnterpriseIdentifierValid(
11953 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011954 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011955 return true;
11956 }
11957 return false;
11958 }
11959
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011960 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090011961 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011962 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090011963 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011964 // The NRI for a user should contain the request for capabilities.
11965 // If fallback to default network is needed then NRI should include
11966 // the request for the default network. Create an image of it to
11967 // have the correct UIDs in it (also a request can only be part of one NRI, because
11968 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011969 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
11970 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011971 if (pref.allowFallback) {
11972 nrs.add(createDefaultInternetRequestForTransport(
11973 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11974 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011975 if (VDBG) {
11976 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
11977 pref.capabilities.getUids()));
11978 }
11979
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011980 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080011981 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080011982 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011983 result.add(nri);
11984 }
11985 return result;
11986 }
11987
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011988 /**
11989 * Compare if the given UID range sets have the same UIDs.
11990 *
11991 */
11992 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090011993 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011994 @NonNull Set<UidRange> uidRangeSet) {
11995 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
11996 return false;
11997 }
Chalard Jean0606fc82022-12-14 20:34:43 +090011998 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011999 if (UidRangeUtils.doesRangeSetOverlap(
12000 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12001 return true;
12002 }
12003 }
12004 return false;
12005 }
12006
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012007 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012008 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012009 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012010 /*
12011 * handleSetProfileNetworkPreference is always called for single user.
12012 * preferenceList only contains preferences for different uids within the same user
12013 * (enforced by getUidListToBeAppliedForNetworkPreference).
12014 * Clear all the existing preferences for the user before applying new preferences.
12015 *
12016 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012017 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12018 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012019 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12020 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012021
paulhu74128522021-09-28 02:29:03 +000012022 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12023 addPerAppDefaultNetworkRequests(
12024 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012025 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012026
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012027 // Finally, rematch.
12028 rematchAllNetworksAndRequests();
12029
12030 if (null != listener) {
12031 try {
12032 listener.onComplete();
12033 } catch (RemoteException e) {
12034 loge("Listener for setProfileNetworkPreference has died");
12035 }
12036 }
12037 }
12038
paulhu51f77dc2021-06-07 02:34:20 +000012039 @VisibleForTesting
12040 @NonNull
12041 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12042 @NonNull final Set<Integer> uids) {
12043 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12044 if (uids.size() == 0) {
12045 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12046 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
12047 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
12048 return nris;
12049 }
12050
12051 final List<NetworkRequest> requests = new ArrayList<>();
12052 // The NRI should be comprised of two layers:
12053 // - The request for the mobile network preferred.
12054 // - The request for the default network, for fallback.
12055 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012056 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012057 requests.add(createDefaultInternetRequestForTransport(
12058 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12059 final Set<UidRange> ranges = new ArraySet<>();
12060 for (final int uid : uids) {
12061 ranges.add(new UidRange(uid, uid));
12062 }
12063 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080012064 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080012065 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000012066 return nris;
12067 }
12068
12069 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012070 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012071 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12072 addPerAppDefaultNetworkRequests(
12073 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012074 // Finally, rematch.
12075 rematchAllNetworksAndRequests();
12076 }
12077
Patrick Rohr2857ac42022-01-21 14:58:16 +010012078 private void handleIngressRateLimitChanged() {
12079 final long oldIngressRateLimit = mIngressRateLimit;
12080 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12081 mContext);
12082 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12083 if (canNetworkBeRateLimited(networkAgent)) {
12084 // If rate limit has previously been enabled, remove the old limit first.
12085 if (oldIngressRateLimit >= 0) {
12086 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12087 }
12088 if (mIngressRateLimit >= 0) {
12089 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12090 mIngressRateLimit);
12091 }
12092 }
12093 }
12094 }
12095
12096 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012097 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090012098 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012099
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012100 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12101 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12102 // internet connectivity can be rate limited.
12103 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12104 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012105 return false;
12106 }
12107
12108 final String iface = networkAgent.linkProperties.getInterfaceName();
12109 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012110 // This may happen in tests, but if there is no interface then there is nothing that
12111 // can be rate limited.
12112 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012113 return false;
12114 }
12115 return true;
12116 }
12117
James Mattis45d81842021-01-10 14:24:24 -080012118 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012119 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12120 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012121 }
12122
12123 /**
12124 * Used by automotive devices to set the network preferences used to direct traffic at an
12125 * application level as per the given OemNetworkPreferences. An example use-case would be an
12126 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12127 * vehicle via a particular network.
12128 *
12129 * Calling this will overwrite the existing preference.
12130 *
James Mattisda32cfe2021-01-26 16:23:52 -080012131 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012132 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012133 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012134 */
James Mattis47db0582021-01-01 14:13:35 -080012135 @Override
James Mattis45d81842021-01-10 14:24:24 -080012136 public void setOemNetworkPreference(
12137 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012138 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012139
James Mattisfa270db2021-05-31 17:11:10 -070012140 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12141 // Only bypass the permission/device checks if this is a valid test request.
12142 if (isValidTestOemNetworkPreference(preference)) {
12143 enforceManageTestNetworksPermission();
12144 } else {
12145 enforceAutomotiveDevice();
12146 enforceOemNetworkPreferencesPermission();
12147 validateOemNetworkPreferences(preference);
12148 }
James Mattis45d81842021-01-10 14:24:24 -080012149
James Mattis45d81842021-01-10 14:24:24 -080012150 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12151 new Pair<>(preference, listener)));
12152 }
12153
James Mattisfa270db2021-05-31 17:11:10 -070012154 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012155 * Sets the specified UIDs to get/receive the VPN as the only default network.
12156 *
12157 * Calling this will overwrite the existing network preference for this session, and the
12158 * specified UIDs won't get any default network when no VPN is connected.
12159 *
12160 * @param session The VPN session which manages the passed UIDs.
12161 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12162 * setting for this session if the array is empty. Null is not allowed, the
12163 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12164 * @hide
12165 */
12166 @Override
12167 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12168 Objects.requireNonNull(ranges);
12169 enforceNetworkStackOrSettingsPermission();
12170 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12171 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12172 throw new IllegalArgumentException(
12173 "setVpnNetworkPreference: Passed UID ranges overlap");
12174 }
12175
12176 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12177 new VpnNetworkPreferenceInfo(session,
12178 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12179 }
12180
12181 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12182 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12183
12184 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12185 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12186
12187 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12188 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12189 // Finally, rematch.
12190 rematchAllNetworksAndRequests();
12191 }
12192
12193 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12194 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12195 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12196 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
12197 final List<NetworkRequest> requests = new ArrayList<>();
12198 // Request VPN only, so other networks won't be the fallback options when VPN is not
12199 // connected temporarily.
12200 requests.add(createVpnRequest());
12201 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
12202 setNetworkRequestUids(requests, uidRanges);
12203 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
12204 }
12205 return nris;
12206 }
12207
12208 /**
James Mattisfa270db2021-05-31 17:11:10 -070012209 * Check the validity of an OEM network preference to be used for testing purposes.
12210 * @param preference the preference to validate
12211 * @return true if this is a valid OEM network preference test request.
12212 */
12213 private boolean isValidTestOemNetworkPreference(
12214 @NonNull final OemNetworkPreferences preference) {
12215 // Allow for clearing of an existing OemNetworkPreference used for testing.
12216 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
12217 // changes after this check is complete. This is an unlikely scenario as calling of this API
12218 // is controlled by the OEM therefore the added complexity is not worth adding given those
12219 // circumstances. That said, it is an edge case to be aware of hence this comment.
12220 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
12221 && isTestOemNetworkPreference(mOemNetworkPreferences);
12222 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
12223 }
12224
12225 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
12226 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
12227 return prefMap.size() == 1
12228 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
12229 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
12230 }
12231
James Mattis45d81842021-01-10 14:24:24 -080012232 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
12233 for (@OemNetworkPreferences.OemNetworkPreference final int pref
12234 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070012235 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
12236 throw new IllegalArgumentException(
12237 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
12238 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080012239 }
12240 }
12241 }
12242
12243 private void handleSetOemNetworkPreference(
12244 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012245 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080012246 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12247 if (DBG) {
12248 log("set OEM network preferences :" + preference.toString());
12249 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012250
James Mattiscb1e0362021-04-06 17:07:42 -070012251 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012252 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12253 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12254 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012255 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012256
12257 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012258 try {
12259 listener.onComplete();
12260 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012261 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012262 }
James Mattis45d81842021-01-10 14:24:24 -080012263 }
12264 }
12265
paulhu74128522021-09-28 02:29:03 +000012266 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012267 // Skip the requests which are set by other network preference. Because the uid range rules
12268 // should stay in netd.
12269 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012270 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012271 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012272 }
12273
James Mattis3ce3d3c2021-02-09 18:18:28 -080012274 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12275 ensureRunningOnConnectivityServiceThread();
12276 mDefaultNetworkRequests.addAll(nris);
12277 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12278 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012279 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012280 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12281 nrisToRegister.addAll(
12282 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12283 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012284 }
12285
12286 /**
12287 * All current requests that are tracking the default network need to be assessed as to whether
12288 * or not the current set of per-application default requests will be changing their default
12289 * network. If so, those requests will need to be updated so that they will send callbacks for
12290 * default network changes at the appropriate time. Additionally, those requests tracking the
12291 * default that were previously updated by this flow will need to be reassessed.
12292 * @return the nris which will need to be updated.
12293 */
12294 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12295 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12296 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12297 // same nri in the map's values for each of its NetworkRequest objects.
12298 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012299 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012300 // Include this nri if it is currently being tracked.
12301 if (isPerAppTrackedNri(nri)) {
12302 defaultCallbackRequests.add(nri);
12303 continue;
12304 }
12305 // We only track callbacks for requests tracking the default.
12306 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12307 continue;
12308 }
12309 // Include this nri if it will be tracked by the new per-app default requests.
12310 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012311 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012312 if (isNriGoingToBeTracked) {
12313 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012314 }
12315 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012316 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012317 }
12318
James Mattis3ce3d3c2021-02-09 18:18:28 -080012319 /**
12320 * Create nris for those network requests that are currently tracking the default network that
12321 * are being controlled by a per-application default.
12322 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12323 * foundation when creating the nri. Important items include the calling uid's original
12324 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12325 * requests are assumed to have already been validated as needing to be updated.
12326 * @return the Set of nris to use when registering network requests.
12327 */
12328 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12329 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12330 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12331 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12332 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012333 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012334
Chalard Jean9473c982021-07-29 20:03:04 +090012335 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012336 if (trackingNri == mDefaultRequest) {
12337 callbackRequestsToRegister.add(new NetworkRequestInfo(
12338 callbackRequest,
12339 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12340 continue;
12341 }
12342
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012343 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012344 callbackRequestsToRegister.add(new NetworkRequestInfo(
12345 callbackRequest,
12346 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012347 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012348 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012349 }
12350 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012351 }
12352
Chalard Jean17215832021-03-01 14:06:28 +090012353 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12354 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012355 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012356 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012357 }
12358 }
12359
James Mattis45d81842021-01-10 14:24:24 -080012360 /**
12361 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12362 */
12363 @VisibleForTesting
12364 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012365 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080012366 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012367 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080012368 final SparseArray<Set<Integer>> uids =
12369 createUidsFromOemNetworkPreferences(preference);
12370 for (int i = 0; i < uids.size(); i++) {
12371 final int key = uids.keyAt(i);
12372 final Set<Integer> value = uids.valueAt(i);
12373 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
12374 // No need to add an nri without any requests.
12375 if (0 == nri.mRequests.size()) {
12376 continue;
12377 }
12378 nris.add(nri);
12379 }
12380
12381 return nris;
12382 }
12383
12384 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
12385 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070012386 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080012387 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080012388 final List<UserHandle> users =
12389 mContext.getSystemService(UserManager.class).getUserHandles(true);
12390 if (null == users || users.size() == 0) {
12391 if (VDBG || DDBG) {
12392 log("No users currently available for setting the OEM network preference.");
12393 }
James Mattisb6b6a432021-06-01 22:30:36 -070012394 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080012395 }
James Mattis45d81842021-01-10 14:24:24 -080012396 for (final Map.Entry<String, Integer> entry :
12397 preference.getNetworkPreferences().entrySet()) {
12398 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070012399 // Add the rules for all users as this policy is device wide.
12400 for (final UserHandle user : users) {
12401 try {
12402 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
12403 if (!prefToUids.contains(pref)) {
12404 prefToUids.put(pref, new ArraySet<>());
12405 }
12406 prefToUids.get(pref).add(uid);
12407 } catch (PackageManager.NameNotFoundException e) {
12408 // Although this may seem like an error scenario, it is ok that uninstalled
12409 // packages are sent on a network preference as the system will watch for
12410 // package installations associated with this network preference and update
12411 // accordingly. This is done to minimize race conditions on app install.
12412 continue;
James Mattis45d81842021-01-10 14:24:24 -080012413 }
James Mattis45d81842021-01-10 14:24:24 -080012414 }
12415 }
James Mattisb6b6a432021-06-01 22:30:36 -070012416 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080012417 }
12418
12419 private NetworkRequestInfo createNriFromOemNetworkPreferences(
12420 @OemNetworkPreferences.OemNetworkPreference final int preference,
12421 @NonNull final Set<Integer> uids) {
12422 final List<NetworkRequest> requests = new ArrayList<>();
12423 // Requests will ultimately be evaluated by order of insertion therefore it matters.
12424 switch (preference) {
12425 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
12426 requests.add(createUnmeteredNetworkRequest());
12427 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070012428 requests.add(createDefaultInternetRequestForTransport(
12429 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080012430 break;
12431 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
12432 requests.add(createUnmeteredNetworkRequest());
12433 requests.add(createOemPaidNetworkRequest());
12434 break;
12435 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
12436 requests.add(createOemPaidNetworkRequest());
12437 break;
12438 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
12439 requests.add(createOemPrivateNetworkRequest());
12440 break;
James Mattisfa270db2021-05-31 17:11:10 -070012441 case OEM_NETWORK_PREFERENCE_TEST:
12442 requests.add(createUnmeteredNetworkRequest());
12443 requests.add(createTestNetworkRequest());
12444 requests.add(createDefaultRequest());
12445 break;
12446 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
12447 requests.add(createTestNetworkRequest());
12448 break;
James Mattis45d81842021-01-10 14:24:24 -080012449 default:
12450 // This should never happen.
12451 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
12452 + " called with invalid preference of " + preference);
12453 }
12454
James Mattisfa270db2021-05-31 17:11:10 -070012455 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090012456 for (final int uid : uids) {
12457 ranges.add(new UidRange(uid, uid));
12458 }
12459 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080012460 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080012461 }
12462
12463 private NetworkRequest createUnmeteredNetworkRequest() {
12464 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12465 .addCapability(NET_CAPABILITY_NOT_METERED)
12466 .addCapability(NET_CAPABILITY_VALIDATED);
12467 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
12468 }
12469
12470 private NetworkRequest createOemPaidNetworkRequest() {
12471 // NET_CAPABILITY_OEM_PAID is a restricted capability.
12472 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12473 .addCapability(NET_CAPABILITY_OEM_PAID)
12474 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12475 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12476 }
12477
12478 private NetworkRequest createOemPrivateNetworkRequest() {
12479 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
12480 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12481 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
12482 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12483 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12484 }
12485
12486 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070012487 final NetworkCapabilities netcap = new NetworkCapabilities();
12488 netcap.addCapability(NET_CAPABILITY_INTERNET);
12489 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
12490 return netcap;
12491 }
12492
12493 private NetworkRequest createTestNetworkRequest() {
12494 final NetworkCapabilities netcap = new NetworkCapabilities();
12495 netcap.clearAll();
12496 netcap.addTransportType(TRANSPORT_TEST);
12497 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080012498 }
James Mattis47db0582021-01-01 14:13:35 -080012499 }
markchien738ad912021-12-09 18:15:45 +080012500
12501 @Override
12502 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
12503 enforceNetworkStackOrSettingsPermission();
12504
12505 try {
12506 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012507 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012508 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012509 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012510 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012511 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012512 throw new IllegalStateException(e);
12513 }
12514 }
12515
12516 @Override
12517 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
12518 enforceNetworkStackOrSettingsPermission();
12519
12520 try {
12521 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012522 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012523 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012524 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012525 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012526 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012527 throw new IllegalStateException(e);
12528 }
12529 }
markchiene1561fa2021-12-09 22:00:56 +080012530
Chalard Jeanc8fefb32023-09-05 21:41:13 +090012531 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
12532 throws PackageManager.NameNotFoundException {
12533 final PackageManager pm = mContext.getPackageManager();
12534 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
12535 if (appId < Process.FIRST_APPLICATION_UID) {
12536 throw new RuntimeException("Can't set package firewall rule for system app "
12537 + packageName + " with appId " + appId);
12538 }
12539 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
12540 final int uid = uh.getUid(appId);
12541 setUidFirewallRule(chain, uid, rule);
12542 }
12543 return appId;
12544 }
12545
markchiene1561fa2021-12-09 22:00:56 +080012546 @Override
markchien3c04e662022-03-22 16:29:56 +080012547 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080012548 enforceNetworkStackOrSettingsPermission();
12549
markchien3c04e662022-03-22 16:29:56 +080012550 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
12551 int firewallRule = getFirewallRuleType(chain, rule);
12552
12553 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
12554 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
12555 }
12556
markchiene1561fa2021-12-09 22:00:56 +080012557 try {
markchien3c04e662022-03-22 16:29:56 +080012558 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012559 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080012560 throw new IllegalStateException(e);
12561 }
12562 }
markchien98a6f952022-01-13 23:43:53 +080012563
Chalard Jeanc8fefb32023-09-05 21:41:13 +090012564 private int getPackageFirewallRule(final int chain, final String packageName)
12565 throws PackageManager.NameNotFoundException {
12566 final PackageManager pm = mContext.getPackageManager();
12567 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
12568 return getUidFirewallRule(chain, appId);
12569 }
12570
Motomu Utsumi900b8062023-01-19 16:16:49 +090012571 @Override
12572 public int getUidFirewallRule(final int chain, final int uid) {
12573 enforceNetworkStackOrSettingsPermission();
12574 return mBpfNetMaps.getUidRule(chain, uid);
12575 }
12576
markchien3c04e662022-03-22 16:29:56 +080012577 private int getFirewallRuleType(int chain, int rule) {
12578 final int defaultRule;
12579 switch (chain) {
12580 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000012581 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
12582 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000012583 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080012584 defaultRule = FIREWALL_RULE_ALLOW;
12585 break;
12586 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
12587 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
12588 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
12589 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
12590 defaultRule = FIREWALL_RULE_DENY;
12591 break;
12592 default:
12593 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
12594 }
12595 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
12596
12597 return rule;
12598 }
12599
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012600 private void closeSocketsForFirewallChainLocked(final int chain)
12601 throws ErrnoException, SocketException, InterruptedIOException {
12602 if (mBpfNetMaps.isFirewallAllowList(chain)) {
12603 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
12604 // So, close all non-system socket owned by uids that are not explicitly allowed
12605 Set<Range<Integer>> ranges = new ArraySet<>();
12606 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
12607 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
12608 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
12609 } else {
12610 // Denylist means the firewall allows all by default, uids must be explicitly denied
12611 // So, close socket owned by uids that are explicitly denied
12612 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
12613 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
12614 }
12615 }
12616
markchien98a6f952022-01-13 23:43:53 +080012617 @Override
12618 public void setFirewallChainEnabled(final int chain, final boolean enable) {
12619 enforceNetworkStackOrSettingsPermission();
12620
12621 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012622 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012623 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080012624 throw new IllegalStateException(e);
12625 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012626
Chalard Jeandf29a852023-05-29 17:02:43 +090012627 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012628 try {
12629 closeSocketsForFirewallChainLocked(chain);
12630 } catch (ErrnoException | SocketException | InterruptedIOException e) {
12631 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
12632 }
12633 }
markchien98a6f952022-01-13 23:43:53 +080012634 }
12635
markchien00a0bed2022-01-13 23:46:13 +080012636 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012637 public boolean getFirewallChainEnabled(final int chain) {
12638 enforceNetworkStackOrSettingsPermission();
12639
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000012640 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012641 }
12642
12643 @Override
markchien00a0bed2022-01-13 23:46:13 +080012644 public void replaceFirewallChain(final int chain, final int[] uids) {
12645 enforceNetworkStackOrSettingsPermission();
12646
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000012647 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080012648 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080012649
12650 @Override
12651 public IBinder getCompanionDeviceManagerProxyService() {
12652 enforceNetworkStackPermission(mContext);
12653 return mCdmps;
12654 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070012655}