blob: 3dc56926e52bc2ee31a45a069b0521ab43b04c6f [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
Junyu Lai155760b2023-10-05 14:51:00 +0800103import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET4_BIND;
104import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET6_BIND;
105import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_EGRESS;
106import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_INGRESS;
107import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_SOCK_CREATE;
Xiao Ma60142372022-07-16 17:30:20 +0900108import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Junyu Lai4c6fe232023-04-11 11:33:46 +0800109import static com.android.net.module.util.PermissionUtils.checkAnyPermissionOf;
paulhu3ffffe72021-09-16 10:15:22 +0800110import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
111import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
112import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900113import static com.android.server.ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE;
Chalard Jeaneb663892023-10-07 15:17:07 +0900114
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800115import static java.util.Map.Entry;
116
Chalard Jean5b639762020-03-09 21:25:37 +0900117import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000118import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800119import android.annotation.Nullable;
Michael Groover73f69482023-01-27 11:01:25 -0600120import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800121import android.annotation.TargetApi;
Mark Fasheh7c999d82023-05-04 20:23:11 +0000122import android.app.ActivityManager;
123import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800124import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800125import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700126import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700127import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900128import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800129import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700130import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800131import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800132import android.content.ContentResolver;
133import android.content.Context;
134import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700135import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800136import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900137import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700138import android.database.ContentObserver;
Junyu Laie0031522023-08-29 18:32:57 +0800139import android.net.BpfNetMapsUtils;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900140import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900141import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700142import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800143import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800144import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800145import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900146import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800147import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900148import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800149import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900150import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800151import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700152import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900153import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800154import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800155import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800156import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800157import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800158import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900159import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900160import android.net.INetworkMonitor;
161import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900162import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900163import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700164import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800165import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900166import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900167import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900168import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800169import android.net.LinkProperties;
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +0900170import android.net.LocalNetworkConfig;
Charles He9369e612017-05-15 17:07:18 +0100171import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800172import android.net.NativeNetworkConfig;
173import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800174import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700175import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700176import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900177import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700178import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800179import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700180import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900181import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900182import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000183import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900184import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700185import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900186import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700187import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900188import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700189import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800190import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900191import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700192import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000193import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800194import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900195import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800196import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400197import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700198import android.net.QosCallbackException;
199import android.net.QosFilter;
200import android.net.QosSocketFilter;
201import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700202import android.net.RouteInfo;
junyulai011b1f12019-01-03 18:50:15 +0800203import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800204import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900205import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400206import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800207import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800208import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400209import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800210import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900211import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900212import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900213import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900214import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800215import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900216import android.net.networkstack.ModuleNetworkStackClient;
217import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900218import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800219import android.net.resolv.aidl.DnsHealthEventParcel;
220import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
221import android.net.resolv.aidl.Nat64PrefixEventParcel;
222import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900223import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900224import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800225import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800226import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800227import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700228import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000229import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800230import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700231import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700232import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800233import android.os.Looper;
234import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700235import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700236import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900237import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800238import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700239import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700240import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800241import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700242import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900243import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900244import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700245import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700246import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400247import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800248import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900249import android.stats.connectivity.MeteredState;
250import android.stats.connectivity.RequestType;
251import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900252import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700253import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700254import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700255import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800256import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900257import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000258import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600259import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900260import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900261import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700262import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700263import android.util.SparseIntArray;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900264import android.util.StatsEvent;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800265
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800266import androidx.annotation.RequiresApi;
267
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900268import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400269import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400270import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700271import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900272import com.android.internal.util.MessageUtils;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900273import com.android.metrics.ConnectionDurationForTransports;
274import com.android.metrics.ConnectionDurationPerTransports;
275import com.android.metrics.ConnectivitySampleMetricsHelper;
276import com.android.metrics.ConnectivityStateSample;
277import com.android.metrics.NetworkCountForTransports;
278import com.android.metrics.NetworkCountPerTransports;
279import com.android.metrics.NetworkDescription;
280import com.android.metrics.NetworkList;
281import com.android.metrics.NetworkRequestCount;
282import com.android.metrics.RequestCountForType;
Chiachang Wang62740142020-11-02 16:51:24 +0800283import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900284import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800285import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000286import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900287import com.android.net.module.util.BitUtils;
Junyu Lai155760b2023-10-05 14:51:00 +0800288import com.android.net.module.util.BpfUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900289import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900290import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100291import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900292import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
293import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900294import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800295import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800296import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100297import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000298import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800299import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
300import com.android.networkstack.apishim.ConstantsShim;
301import com.android.networkstack.apishim.common.BroadcastOptionsShim;
302import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900303import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900304import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000305import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900306import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800307import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800308import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900309import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900310import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900311import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500312import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700313import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900314import com.android.server.connectivity.FullScore;
Junyu Laif8dba342023-10-12 17:01:03 +0800315import com.android.server.connectivity.HandlerUtils;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900316import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900317import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000318import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100319import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700320import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900321import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700322import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600323import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900324import com.android.server.connectivity.NetworkNotificationManager;
325import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900326import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900327import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900328import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700329import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900330import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900331import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700332import com.android.server.connectivity.QosCallbackTracker;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900333import com.android.server.connectivity.RoutingCoordinatorService;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800334import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000335import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800336import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600337
Josh Gao461a1222020-06-16 15:58:11 -0700338import libcore.io.IoUtils;
339
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900340import org.xmlpull.v1.XmlPullParserException;
341
The Android Open Source Project28527d22009-03-03 19:31:44 -0800342import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100343import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900344import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800345import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900346import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700347import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700348import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900349import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900350import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700351import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700352import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700353import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700354import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800355import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900356import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800357import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700358import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700359import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700360import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700361import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900362import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700363import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900364import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600365import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900366import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600367import java.util.TreeSet;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900368import java.util.concurrent.TimeUnit;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900369import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800370
371/**
372 * @hide
373 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800374public class ConnectivityService extends IConnectivityManager.Stub
375 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900376 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800377
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900378 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900379 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900380 private static final String NETWORK_ARG = "networks";
381 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800382 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900383
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900384 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900385 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
386 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800387
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900388 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700389
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100390 /**
391 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
392 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800393 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100394 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
395 * (preferably via runtime resource overlays).
396 */
397 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
398 "http://connectivitycheck.gstatic.com/generate_204";
399
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700400 // TODO: create better separation between radio types and network types
401
Robert Greenwalt2034b912009-08-12 16:08:25 -0700402 // how long to wait before switching back to a radio's default network
403 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
404 // system property that can override the above value
405 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
406 "android.telephony.apn-restore";
407
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900408 // How long to wait before putting up a "This network doesn't have an Internet connection,
409 // connect anyway?" dialog after the user selects a network that doesn't validate.
410 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
411
Chalard Jean5fb43c72022-09-08 19:03:14 +0900412 // How long to wait before considering that a network is bad in the absence of any form
413 // of connectivity (valid, partial, captive portal). If none has been detected after this
414 // delay, the stack considers this network bad, which may affect how it's handled in ranking
415 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900416 // Timeout in case the "actively prefer bad wifi" feature is on
417 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
418 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900419 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900420
junyulai0ac374f2020-12-14 18:41:52 +0800421 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900422 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
423 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800424 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700425
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800426 // Delimiter used when creating the broadcast delivery group for sending
427 // CONNECTIVITY_ACTION broadcast.
428 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
429
he_won.hwang881307a2022-03-15 21:23:52 +0900430 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900431 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900432
Daniel Brightf9e945b2020-06-15 16:10:01 -0700433 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900434 @VisibleForTesting
435 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700436
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900437 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700438 @VisibleForTesting
439 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900440
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900441 @VisibleForTesting
442 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800443 @VisibleForTesting
444 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900445 // True if the cell radio of the device is capable of time-sharing.
446 @VisibleForTesting
447 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900448
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800449 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800450 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800451 private final int mReleasePendingIntentDelayMs;
452
Chalard Jean46bfbf02022-02-02 00:56:25 +0900453 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900454
Motomu Utsumif360aa62023-01-30 17:52:20 +0900455 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700456
Chalard Jean9473c982021-07-29 20:03:04 +0900457 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800458 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700459 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800460 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700461
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900462 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700463
junyulaif2c67e42018-08-07 19:50:45 +0800464 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000465 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
466 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800467 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900468 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800469
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900470 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900471 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000472 private final int mWakeUpMark;
473 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000474 // The Context is created for UserHandle.ALL.
475 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900476 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900477 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700478 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700479 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800480
Chenbo Feng15416292018-11-08 17:36:21 -0800481 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800482 protected IDnsResolver mDnsResolver;
483 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800484 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700485 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900486 private final NetworkStatsManager mStatsManager;
487 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800488 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700489
Benedict Wong493e04b2018-11-09 14:45:34 -0800490 /**
491 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
492 * instances.
493 */
494 @GuardedBy("mTNSLock")
495 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800496 private final CompanionDeviceManagerProxyService mCdmps;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900497 private final RoutingCoordinatorService mRoutingCoordinatorService;
Benedict Wong493e04b2018-11-09 14:45:34 -0800498
499 private final Object mTNSLock = new Object();
500
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700501 private String mCurrentTcpBufferSizes;
502
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900503 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000504 new Class[] {
505 ConnectivityService.class,
506 NetworkAgent.class,
507 NetworkAgentInfo.class,
508 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900509
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500510 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400511 // Tear down networks that have no chance (e.g. even if validated) of becoming
512 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500513 // all networks have been rematched against all NetworkRequests.
514 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400515 // Don't reap networks. This should be passed when some networks have not yet been
516 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500517 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900518 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500519
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900520 private enum UnneededFor {
521 LINGER, // Determine whether this network is unneeded and should be lingered.
522 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
523 }
524
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700525 /**
paulhuaa0743d2021-05-26 21:56:03 +0800526 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800527 * should have priority. The order is passed to netd which will use it together
528 * with UID ranges to generate the corresponding IP rule. This serves to
529 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800530 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800531 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000532 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800533 *
paulhu48291862021-07-14 14:53:57 +0800534 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
535 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800536 */
paulhu48291862021-07-14 14:53:57 +0800537 // Used when sending to netd to code for "no order".
538 static final int PREFERENCE_ORDER_NONE = 0;
539 // Order for requests that don't code for a per-app preference. As it is
540 // out of the valid range, the corresponding order should be
541 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800542 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800543 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800544 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800545 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
546 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800547 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800548 static final int PREFERENCE_ORDER_OEM = 10;
549 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800550 // See {@link #setProfileNetworkPreference}.
551 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800552 static final int PREFERENCE_ORDER_PROFILE = 20;
553 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800554 // better scores are connected.
555 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800556 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800557 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900558 // Preference order that signifies the network shouldn't be set as a default network for
559 // the UIDs, only give them access to it. TODO : replace this with a boolean
560 // in NativeUidRangeConfig
561 @VisibleForTesting
562 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
563 // Bound for the lowest valid preference order.
564 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800565
566 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700567 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700568 * from one net to another. Clear happens when we get a new
569 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
570 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700571 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700572 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700573
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700574 /**
575 * used internally to reload global proxy settings
576 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700577 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700578
Robert Greenwalt34848c02011-03-25 13:09:25 -0700579 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400580 * PAC manager has received new port.
581 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800582 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400583
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700584 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900585 * used internally when registering NetworkProviders
586 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700587 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900588 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700589
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700590 /**
591 * used internally when registering NetworkAgents
592 * obj = Messenger
593 */
594 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
595
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700596 /**
597 * used to add a network request
598 * includes a NetworkRequestInfo
599 */
600 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
601
602 /**
603 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900604 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700605 * cancel it.
606 * includes a NetworkRequestInfo
607 */
608 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
609
610 /**
611 * used to add a network listener - no request
612 * includes a NetworkRequestInfo
613 */
614 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
615
616 /**
617 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400618 * arg1 = UID of caller
619 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700620 */
621 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
622
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700623 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900624 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700625 * obj = Messenger
626 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900627 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700628
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700629 /**
630 * used internally to expire a wakelock when transitioning
631 * from one net to another. Expire happens when we fail to find
632 * a new network (typically after 1 minute) -
633 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
634 * a replacement network.
635 */
636 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
637
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700638 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800639 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400640 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800641 */
642 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
643
644 /**
645 * used to remove a pending intent and its associated network request.
646 * arg1 = UID of caller
647 * obj = PendingIntent
648 */
649 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
650
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900651 /**
652 * used to specify whether a network should be used even if unvalidated.
653 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
654 * arg2 = whether to remember this choice in the future (1 or 0)
655 * obj = network
656 */
657 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
658
659 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700660 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900661 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700662 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900663
Paul Jensenc8873fc2015-06-17 14:15:39 -0400664 /**
665 * used to add a network listener with a pending intent
666 * obj = NetworkRequestInfo
667 */
668 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
669
Hugo Benichid6b510a2017-04-06 17:22:18 +0900670 /**
671 * used to specify whether a network should not be penalized when it becomes unvalidated.
672 */
673 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
674
675 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700676 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900677 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700678 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900679
Erik Kline31b4a9e2018-01-11 21:07:29 +0900680 // Handle changes in Private DNS settings.
681 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
682
dalyk1720e542018-03-05 12:42:22 -0500683 // Handle private DNS validation status updates.
684 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
685
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900686 /**
687 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
688 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800689 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
690 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
691 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900692 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900693 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900694
695 /**
696 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
697 * config was resolved.
698 * obj = PrivateDnsConfig
699 * arg2 = netid
700 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900701 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900702
703 /**
704 * Request ConnectivityService display provisioning notification.
705 * arg1 = Whether to make the notification visible.
706 * arg2 = NetID.
707 * obj = Intent to be launched when notification selected by user, null if !arg1.
708 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900709 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900710
711 /**
lucaslin2240ef62019-03-12 13:08:03 +0800712 * Used to specify whether a network should be used even if connectivity is partial.
713 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
714 * false)
715 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
716 * obj = network
717 */
lucaslin444d43a2020-02-20 16:56:59 +0800718 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800719
720 /**
lucasline117e2e2019-10-22 18:27:33 +0800721 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
722 * Both of the arguments are bitmasks, and the value of bits come from
723 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900724 * arg1 = unused
725 * arg2 = netId
726 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800727 */
lucaslin444d43a2020-02-20 16:56:59 +0800728 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800729
730 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900731 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
732 * arg1 = unused
733 * arg2 = netId
734 * obj = captive portal data
735 */
lucaslin444d43a2020-02-20 16:56:59 +0800736 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900737
738 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900739 * Used by setRequireVpnForUids.
740 * arg1 = whether the specified UID ranges are required to use a VPN.
741 * obj = Array of UidRange objects.
742 */
743 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
744
745 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900746 * Used internally when setting the default networks for OemNetworkPreferences.
747 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800748 */
749 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
750
751 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800752 * Used to indicate the system default network becomes active.
753 */
754 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
755
756 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900757 * Used internally when setting a network preference for a user profile.
758 * obj = Pair<ProfileNetworkPreference, Listener>
759 */
760 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
761
762 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000763 * Event to specify that reasons for why an uid is blocked changed.
764 * arg1 = uid
765 * arg2 = blockedReasons
766 */
767 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
768
769 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900770 * Event to register a new network offer
771 * obj = NetworkOffer
772 */
773 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
774
775 /**
776 * Event to unregister an existing network offer
777 * obj = INetworkOfferCallback
778 */
779 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
780
781 /**
paulhu51f77dc2021-06-07 02:34:20 +0000782 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
783 */
784 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
785
786 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800787 * Event to set temporary allow bad wifi within a limited time to override
788 * {@code config_networkAvoidBadWifi}.
789 */
790 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
791
792 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100793 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
794 */
795 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
796
797 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900798 * The initial evaluation period is over for this network.
799 *
800 * If no form of connectivity has been found on this network (valid, partial, captive portal)
801 * then the stack will now consider it to have been determined bad.
802 */
803 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
804
805 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000806 * Used internally when the user does not want the network from captive portal app.
807 * obj = Network
808 */
809 private static final int EVENT_USER_DOES_NOT_WANT = 58;
810
811 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000812 * Event to set VPN as preferred network for specific apps.
813 * obj = VpnNetworkPreferenceInfo
814 */
815 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
816
817 /**
chiachangwange0192a72023-02-06 13:25:01 +0000818 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
819 */
820 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
821
822 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000823 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
824 */
825 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
826
827 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900828 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
829 * should be shown.
830 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900831 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900832
833 /**
834 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
835 * should be hidden.
836 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900837 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900838
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800839 /**
840 * The maximum alive time to allow bad wifi configuration for testing.
841 */
842 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
843
Patrick Rohr2857ac42022-01-21 14:58:16 +0100844 /**
chiachangwange0192a72023-02-06 13:25:01 +0000845 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
846 * testing.
847 */
848 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
849
850 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100851 * The priority of the tc police rate limiter -- smaller value is higher priority.
852 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
853 */
854 private static final short TC_PRIO_POLICE = 1;
855
856 /**
857 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
858 */
859 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700860 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100861
Hugo Benichi47011212017-03-30 10:46:05 +0900862 private static String eventName(int what) {
863 return sMagicDecoderRing.get(what, Integer.toString(what));
864 }
865
paulhua10d8212020-11-10 15:32:56 +0800866 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900867 final DnsResolverServiceManager dsm = context.getSystemService(
868 DnsResolverServiceManager.class);
869 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800870 }
871
Cody Kesting73708bf2019-12-18 10:57:50 -0800872 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900873 @VisibleForTesting
874 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700875 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700876 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700877 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700878 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800879 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
880 @VisibleForTesting
881 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
882
Erik Kline32120082017-12-13 19:40:49 +0900883 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900884 @VisibleForTesting
885 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700886
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400887 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800888 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400889
Chalard Jean46bfbf02022-02-02 00:56:25 +0900890 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800891 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700892
Chalard Jean5d70ba42018-06-07 16:44:04 +0900893 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
894 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800895 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400896
Erik Kline05f2b402015-04-30 12:58:40 +0900897 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700898
Chalard Jean46bfbf02022-02-02 00:56:25 +0900899 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400900
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700901 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900902 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700903
Valentin Iftime9fa35092019-09-24 13:32:13 +0200904 private Set<String> mWolSupportedInterfaces;
905
Roshan Pius08c94fb2020-01-16 12:17:17 -0800906 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800907 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800908 private final AppOpsManager mAppOpsManager;
909
910 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400911
chiachangwang3d60bac2023-01-17 14:38:08 +0000912 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900913 private final QosCallbackTracker mQosCallbackTracker;
914 private final NetworkNotificationManager mNotifier;
915 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900916
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700917 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800918 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700919
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900920 // Sequence number for NetworkProvider IDs.
921 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
922 NetworkProvider.FIRST_PROVIDER_ID);
923
Erik Klineedf878b2015-07-09 18:24:03 +0900924 // NetworkRequest activity String log entries.
925 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
926 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
927
Hugo Benichid159fdd2016-07-11 11:05:12 +0900928 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900929 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900930 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
931
Hugo Benichi47011212017-03-30 10:46:05 +0900932 private static final int MAX_WAKELOCK_LOGS = 20;
933 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900934 private int mTotalWakelockAcquisitions = 0;
935 private int mTotalWakelockReleases = 0;
936 private long mTotalWakelockDurationMs = 0;
937 private long mMaxWakelockDurationMs = 0;
938 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900939
Hugo Benichi208c0102016-07-28 17:53:06 +0900940 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900941
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700942 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900943 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700944
Erik Kline95ecfee2016-10-02 18:02:14 +0900945 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900946 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900947
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900948 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800949 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
950 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800951
Patrick Rohr2857ac42022-01-21 14:58:16 +0100952 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
953 // configured via {@link
954 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
955 // Only the handler thread is allowed to access this field.
956 private long mIngressRateLimit = -1;
957
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900958 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
959 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900960 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900961 @GuardedBy("mSelfCertifiedCapabilityCache")
962 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
963 mSelfCertifiedCapabilityCache = new HashMap<>();
964
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900965 // Flag to enable the feature of closing frozen app sockets.
966 private final boolean mDestroyFrozenSockets;
967
968 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
969 private final boolean mDelayDestroyFrozenSockets;
970
971 // Uids that ConnectivityService is pending to close sockets of.
972 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
973
Robert Greenwalt802c1102014-06-02 15:32:02 -0700974 /**
975 * Implements support for the legacy "one network per network type" model.
976 *
977 * We used to have a static array of NetworkStateTrackers, one for each
978 * network type, but that doesn't work any more now that we can have,
979 * for example, more that one wifi network. This class stores all the
980 * NetworkAgentInfo objects that support a given type, but the legacy
981 * API will only see the first one.
982 *
983 * It serves two main purposes:
984 *
985 * 1. Provide information about "the network for a given type" (since this
986 * API only supports one).
987 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
988 * the first network for a given type changes, or if the default network
989 * changes.
990 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900991 @VisibleForTesting
992 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900993
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900994 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900995 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900996
Robert Greenwalt802c1102014-06-02 15:32:02 -0700997 /**
998 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
999 * Each list holds references to all NetworkAgentInfos that are used to
1000 * satisfy requests for that network type.
1001 *
1002 * This array is built out at startup such that an unsupported network
1003 * doesn't get an ArrayList instance, making this a tristate:
1004 * unsupported, supported but not active and active.
1005 *
1006 * The actual lists are populated when we scan the network types that
1007 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +09001008 *
1009 * Threading model:
1010 * - addSupportedType() is only called in the constructor
1011 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1012 * They are therefore not thread-safe with respect to each other.
1013 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1014 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001015 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001016 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001017 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001018 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001019 @NonNull
1020 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001021
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001022 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1023 // an entry have no timer (equivalent to -1). Lazily loaded.
1024 @NonNull
1025 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1026
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001027 LegacyTypeTracker(@NonNull ConnectivityService service) {
1028 mService = service;
1029 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001030 }
1031
Chiachang Wang3bc52762021-11-25 14:17:57 +08001032 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1033 // addressed.
1034 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001035 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1036 final PackageManager pm = ctx.getPackageManager();
1037 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1038 addSupportedType(TYPE_WIFI);
1039 }
1040 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1041 addSupportedType(TYPE_WIFI_P2P);
1042 }
1043 if (tm.isDataCapable()) {
1044 // Telephony does not have granular support for these types: they are either all
1045 // supported, or none is supported
1046 addSupportedType(TYPE_MOBILE);
1047 addSupportedType(TYPE_MOBILE_MMS);
1048 addSupportedType(TYPE_MOBILE_SUPL);
1049 addSupportedType(TYPE_MOBILE_DUN);
1050 addSupportedType(TYPE_MOBILE_HIPRI);
1051 addSupportedType(TYPE_MOBILE_FOTA);
1052 addSupportedType(TYPE_MOBILE_IMS);
1053 addSupportedType(TYPE_MOBILE_CBS);
1054 addSupportedType(TYPE_MOBILE_IA);
1055 addSupportedType(TYPE_MOBILE_EMERGENCY);
1056 }
1057 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1058 addSupportedType(TYPE_BLUETOOTH);
1059 }
1060 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1061 // TYPE_PROXY is only used on Wear
1062 addSupportedType(TYPE_PROXY);
1063 }
1064 // Ethernet is often not specified in the configs, although many devices can use it via
1065 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001066 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001067 addSupportedType(TYPE_ETHERNET);
1068 }
1069
1070 // Always add TYPE_VPN as a supported type
1071 addSupportedType(TYPE_VPN);
1072 }
1073
1074 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001075 if (mTypeLists[type] != null) {
1076 throw new IllegalStateException(
1077 "legacy list for type " + type + "already initialized");
1078 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001079 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001080 }
1081
Robert Greenwalt802c1102014-06-02 15:32:02 -07001082 public boolean isTypeSupported(int type) {
1083 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1084 }
1085
1086 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001087 synchronized (mTypeLists) {
1088 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1089 return mTypeLists[type].get(0);
1090 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001091 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001092 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001093 }
1094
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001095 public int getRestoreTimerForType(int type) {
1096 synchronized (mTypeLists) {
1097 if (mRestoreTimers == null) {
1098 mRestoreTimers = loadRestoreTimers();
1099 }
1100 return mRestoreTimers.getOrDefault(type, -1);
1101 }
1102 }
1103
1104 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1105 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001106 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001107 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1108 for (final String config : configs) {
1109 final String[] splits = TextUtils.split(config, ",");
1110 if (splits.length != 2) {
1111 logwtf("Invalid restore timer token count: " + config);
1112 continue;
1113 }
1114 try {
1115 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1116 } catch (NumberFormatException e) {
1117 logwtf("Invalid restore timer number format: " + config, e);
1118 }
1119 }
1120 return ret;
1121 }
1122
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001123 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001124 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001125 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001126 log("Sending " + state
1127 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001128 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001129 }
1130 }
1131
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001132 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1133 // network type, to preserve previous behaviour.
1134 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1135 if (vpnNai != mService.getLegacyLockdownNai()) return;
1136
1137 if (vpnNai.declaredUnderlyingNetworks == null
1138 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1139 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1140 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1141 return;
1142 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001143 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001144 vpnNai.declaredUnderlyingNetworks[0]);
1145 if (underlyingNai == null) return;
1146
1147 final int type = underlyingNai.networkInfo.getType();
1148 final DetailedState state = DetailedState.CONNECTED;
1149 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1150 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1151 }
1152
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001153 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001154 public void add(int type, NetworkAgentInfo nai) {
1155 if (!isTypeSupported(type)) {
1156 return; // Invalid network type.
1157 }
1158 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1159
1160 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1161 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001162 return;
1163 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001164 synchronized (mTypeLists) {
1165 list.add(nai);
1166 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001167
Chalard Jean5b409c72021-02-04 13:12:59 +09001168 // Send a broadcast if this is the first network of its type or if it's the default.
1169 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001170
1171 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1172 // to preserve previous behaviour.
1173 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001174 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001175 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1176 mService.sendLegacyNetworkBroadcast(nai, state, type);
1177 }
1178
1179 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1180 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001181 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001182 }
1183
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001184 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001185 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001186 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1187 if (list == null || list.isEmpty()) {
1188 return;
1189 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001190 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001191
Hugo Benichi389633f2016-06-21 09:48:07 +09001192 synchronized (mTypeLists) {
1193 if (!list.remove(nai)) {
1194 return;
1195 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001196 }
1197
Lorenzo Colitti49767722015-05-01 00:30:10 +09001198 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001199 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1200 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001201 }
1202
1203 if (!list.isEmpty() && wasFirstNetwork) {
1204 if (DBG) log("Other network available for type " + type +
1205 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001206 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001207 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001208 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001209 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001210 }
1211 }
1212
1213 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001214 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1215 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001216 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001217 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001218 }
1219 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001220
Chalard Jean46bfbf02022-02-02 00:56:25 +09001221 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001222 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001223 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001224 final DetailedState state = nai.networkInfo.getDetailedState();
1225 for (int type = 0; type < mTypeLists.length; type++) {
1226 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001227 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001228 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001229 if (isFirst || contains && isDefault) {
1230 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001231 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001232 }
1233 }
1234 }
1235
Robert Greenwalt94e22142014-07-30 16:31:24 -07001236 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001237 pw.println("mLegacyTypeTracker:");
1238 pw.increaseIndent();
1239 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001240 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001241 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001242 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001243 pw.println();
1244 pw.println("Current state:");
1245 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001246 synchronized (mTypeLists) {
1247 for (int type = 0; type < mTypeLists.length; type++) {
1248 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1249 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001250 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001251 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001252 }
1253 }
1254 pw.decreaseIndent();
1255 pw.decreaseIndent();
1256 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001257 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001258 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001259 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001260
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001261 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001262 /**
1263 * Helper class which parses out priority arguments and dumps sections according to their
1264 * priority. If priority arguments are omitted, function calls the legacy dump command.
1265 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001266 private class LocalPriorityDump {
1267 private static final String PRIORITY_ARG = "--dump-priority";
1268 private static final String PRIORITY_ARG_HIGH = "HIGH";
1269 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
Junyu Laif8dba342023-10-12 17:01:03 +08001270 private static final int DUMPSYS_DEFAULT_TIMEOUT_MS = 10_000;
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001271
1272 LocalPriorityDump() {}
1273
1274 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
Junyu Laif8dba342023-10-12 17:01:03 +08001275 if (!HandlerUtils.runWithScissors(mHandler, () -> {
1276 doDump(fd, pw, new String[]{DIAG_ARG});
1277 doDump(fd, pw, new String[]{SHORT_ARG});
1278 }, DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1279 pw.println("dumpHigh timeout");
1280 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001281 }
1282
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001283 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
Junyu Laif8dba342023-10-12 17:01:03 +08001284 if (!HandlerUtils.runWithScissors(mHandler, () -> doDump(fd, pw, args),
1285 DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1286 pw.println("dumpNormal timeout");
1287 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001288 }
1289
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001290 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1291 if (args == null) {
1292 dumpNormal(fd, pw, args);
1293 return;
1294 }
1295
1296 String priority = null;
1297 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1298 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1299 argIndex++;
1300 priority = args[argIndex];
1301 }
1302 }
1303
1304 if (PRIORITY_ARG_HIGH.equals(priority)) {
1305 dumpHigh(fd, pw);
1306 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1307 dumpNormal(fd, pw, args);
1308 } else {
1309 // ConnectivityService publishes binder service using publishBinderService() with
1310 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001311 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1312 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001313 // TODO: Integrate into signal dump.
1314 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001315 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001316 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001317 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001318
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001319 /**
1320 * Dependencies of ConnectivityService, for injection in tests.
1321 */
1322 @VisibleForTesting
1323 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001324 public int getCallingUid() {
1325 return Binder.getCallingUid();
1326 }
1327
Chalard Jeandf29a852023-05-29 17:02:43 +09001328 public boolean isAtLeastS() {
1329 return SdkLevel.isAtLeastS();
1330 }
1331
1332 public boolean isAtLeastT() {
1333 return SdkLevel.isAtLeastT();
1334 }
1335
1336 public boolean isAtLeastU() {
1337 return SdkLevel.isAtLeastU();
1338 }
1339
Chalard Jeaneb663892023-10-07 15:17:07 +09001340 public boolean isAtLeastV() {
1341 return SdkLevel.isAtLeastV();
1342 }
1343
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001344 /**
1345 * Get system properties to use in ConnectivityService.
1346 */
1347 public MockableSystemProperties getSystemProperties() {
1348 return new MockableSystemProperties();
1349 }
1350
1351 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001352 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1353 */
1354 public ConnectivityResources getResources(@NonNull Context ctx) {
1355 return new ConnectivityResources(ctx);
1356 }
1357
1358 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001359 * Create a HandlerThread to use in ConnectivityService.
1360 */
1361 public HandlerThread makeHandlerThread() {
1362 return new HandlerThread("ConnectivityServiceThread");
1363 }
1364
1365 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001366 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001367 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001368 public NetworkStackClientBase getNetworkStack() {
1369 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001370 }
1371
1372 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001373 * @see ProxyTracker
1374 */
1375 public ProxyTracker makeProxyTracker(@NonNull Context context,
1376 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001377 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001378 }
1379
1380 /**
1381 * @see NetIdManager
1382 */
1383 public NetIdManager makeNetIdManager() {
1384 return new NetIdManager();
1385 }
1386
1387 /**
1388 * @see NetworkUtils#queryUserAccess(int, int)
1389 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001390 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1391 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001392 }
1393
1394 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001395 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1396 * requires CAP_NET_ADMIN, which the unit tests do not have.
1397 */
1398 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1399 InetSocketAddress remote) {
1400 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1401 }
1402
1403 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001404 * @see MultinetworkPolicyTracker
1405 */
1406 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1407 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1408 return new MultinetworkPolicyTracker(c, h, r);
1409 }
1410
Aaron Huang330a4c02020-10-27 03:36:19 +08001411 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001412 * @see AutomaticOnOffKeepaliveTracker
1413 */
1414 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1415 @NonNull Context c, @NonNull Handler h) {
1416 return new AutomaticOnOffKeepaliveTracker(c, h);
1417 }
1418
1419 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001420 * @see BatteryStatsManager
1421 */
1422 public void reportNetworkInterfaceForTransports(Context context, String iface,
1423 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001424 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001425 context.getSystemService(BatteryStatsManager.class);
1426 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1427 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001428
1429 public boolean getCellular464XlatEnabled() {
1430 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1431 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001432
1433 /**
1434 * @see PendingIntent#intentFilterEquals
1435 */
1436 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1437 return a.intentFilterEquals(b);
1438 }
1439
1440 /**
1441 * @see LocationPermissionChecker
1442 */
1443 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1444 return new LocationPermissionChecker(context);
1445 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001446
1447 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001448 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001449 *
1450 * This method returns null in versions before T, where carrier privilege
1451 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001452 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001453 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001454 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1455 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001456 if (isAtLeastT()) {
Chalard Jean84dfa9f2023-01-30 11:23:20 +09001457 return new CarrierPrivilegeAuthenticator(context, this, tm);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001458 } else {
1459 return null;
1460 }
1461 }
1462
1463 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001464 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001465 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001466 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001467 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001468 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001469
1470 /**
1471 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001472 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001473 * @return BpfNetMaps implementation.
1474 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001475 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1476 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001477 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001478
1479 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001480 * @see ClatCoordinator
1481 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001482 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001483 public ClatCoordinator getClatCoordinator(INetd netd) {
1484 return new ClatCoordinator(
1485 new ClatCoordinator.Dependencies() {
1486 @NonNull
1487 public INetd getNetd() {
1488 return netd;
1489 }
1490 });
1491 }
1492
1493 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001494 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1495 */
1496 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1497 final InterfaceParams params = InterfaceParams.getByName(iface);
1498 if (params == null) {
1499 // the interface might have disappeared.
1500 logw("Failed to get interface params for interface " + iface);
1501 return;
1502 }
1503 try {
1504 // converting rateInBytesPerSecond from long to int is safe here because the
1505 // setting's range is limited to INT_MAX.
1506 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001507 Log.i(TAG,
1508 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001509 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1510 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1511 } catch (IOException e) {
1512 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1513 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1514 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1515 + ") failure: ", e);
1516 }
1517 }
1518
1519 /**
1520 * Wraps {@link TcUtils#tcFilterDelDev}
1521 */
1522 public void disableIngressRateLimit(String iface) {
1523 final InterfaceParams params = InterfaceParams.getByName(iface);
1524 if (params == null) {
1525 // the interface might have disappeared.
1526 logw("Failed to get interface params for interface " + iface);
1527 return;
1528 }
1529 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001530 Log.i(TAG,
1531 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001532 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1533 } catch (IOException e) {
1534 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1535 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1536 }
1537 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001538
1539 /**
Junyu Lai155760b2023-10-05 14:51:00 +08001540 * Get BPF program Id from CGROUP. See {@link BpfUtils#getProgramId}.
1541 */
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001542 public int getBpfProgramId(final int attachType)
Junyu Lai155760b2023-10-05 14:51:00 +08001543 throws IOException {
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001544 return BpfUtils.getProgramId(attachType);
Junyu Lai155760b2023-10-05 14:51:00 +08001545 }
1546
1547 /**
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001548 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1549 */
1550 // TODO: when available in all active branches:
1551 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1552 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1553 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1554 return BroadcastOptionsShimImpl.newInstance(options);
1555 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001556
1557 /**
1558 * Wrapper method for
1559 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1560 *
1561 * @param changeId The ID of the compatibility change in question.
1562 * @param packageName The package name of the app in question.
1563 * @param user The user that the operation is done for.
1564 * @return {@code true} if the change is enabled for the specified package.
1565 */
1566 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1567 @NonNull final UserHandle user) {
1568 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1569 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001570
1571 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001572 * As above but with a UID.
1573 * @see CompatChanges#isChangeEnabled(long, int)
1574 */
1575 public boolean isChangeEnabled(final long changeId, final int uid) {
1576 return CompatChanges.isChangeEnabled(changeId, uid);
1577 }
1578
1579 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001580 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1581 *
1582 * @param ranges target uid ranges
1583 * @param exemptUids uids to skip close socket
1584 */
1585 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1586 @NonNull final Set<Integer> exemptUids)
1587 throws SocketException, InterruptedIOException, ErrnoException {
1588 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1589 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001590
1591 /**
1592 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1593 *
1594 * @param ownerUids target uids to close sockets
1595 */
1596 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1597 throws SocketException, InterruptedIOException, ErrnoException {
1598 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1599 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001600
1601 /**
1602 * Schedule the evaluation timeout.
1603 *
1604 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1605 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1606 * of these events happen, this time will run out, after which the network is considered
1607 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1608 * on this network and considers it won't provide connectivity. In particular, that means
1609 * it's when the system prefers it to cell if it's wifi and configuration says it should
1610 * prefer bad wifi to cell.
1611 */
1612 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1613 @NonNull final Network network, final long delayMs) {
1614 handler.sendMessageDelayed(
1615 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1616 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001617 }
1618
junyulaie7c7d2a2021-01-26 15:29:15 +08001619 public ConnectivityService(Context context) {
1620 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001621 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1622 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001623 }
1624
1625 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001626 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1627 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001628 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001629
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001630 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001631 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001632 mSystemProperties = mDeps.getSystemProperties();
1633 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001634 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001635 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001636 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1637 // Pass limit - 1 to maintain backward compatibility.
1638 // TODO: Remove the workaround.
1639 mNetworkRequestCounter =
1640 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1641 mSystemNetworkRequestCounter =
1642 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001643
Hugo Benichi208c0102016-07-28 17:53:06 +09001644 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001645 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1646 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001647 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001648 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001649 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001650 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1651 mDefaultNetworkRequests.add(mDefaultRequest);
1652 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001653
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001654 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001655 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001656
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001657 // The default WiFi request is a background request so that apps using WiFi are
1658 // migrated to a better network (typically ethernet) when one comes up, instead
1659 // of staying on WiFi forever.
1660 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1661 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1662
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001663 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1664 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1665 NetworkRequest.Type.BACKGROUND_REQUEST);
1666
Chalard Jean0702f982021-09-16 21:50:07 +09001667 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1668 // TODO: Consider making the timer customizable.
1669 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1670 mCellularRadioTimesharingCapable =
1671 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1672
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001673 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1674 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1675
1676 if (SdkLevel.isAtLeastU()) {
1677 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1678 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1679 final int defaultUMarkMask = 0x80000000; // u32
1680
1681 if ((mark == 0) || (mask == 0)) {
1682 // simply treat unset/disabled as the default U value
1683 mark = defaultUMarkMask;
1684 mask = defaultUMarkMask;
1685 }
1686 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1687 // invalid device overlay settings
1688 throw new IllegalArgumentException(
1689 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1690 }
1691 }
1692
1693 mWakeUpMark = mark;
1694 mWakeUpMask = mask;
1695
Paul Hu51f816b2022-08-11 14:43:47 +00001696 mNetd = netd;
1697 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001698 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001699 mPermissionMonitor =
1700 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001701 mHandlerThread.start();
1702 mHandler = new InternalHandler(mHandlerThread.getLooper());
1703 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001704 mConnectivityDiagnosticsHandler =
1705 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001706
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001707 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001708 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001709
junyulaie7c7d2a2021-01-26 15:29:15 +08001710 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001711 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001712 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001713 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001714
Wink Saville32506bc2013-06-29 21:10:57 -07001715 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001716 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001717 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001718 mCarrierPrivilegeAuthenticator =
1719 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001720
Sudheer Shanka9967d462021-03-18 19:09:25 +00001721 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001722 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1723 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001724 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001725
1726 final PowerManager powerManager = (PowerManager) context.getSystemService(
1727 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001728 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001729 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001730
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001731 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1732 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001733 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001734 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001735 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001736 mProtectedNetworks.add(p);
1737 } else {
1738 if (DBG) loge("Ignoring protectedNetwork " + p);
1739 }
1740 }
1741
soma, kawata29444ae2019-05-23 09:30:40 +09001742 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1743
James Mattis02220e22021-03-13 19:27:21 -08001744 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001745 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001746 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001747 final IntentFilter userIntentFilter = new IntentFilter();
1748 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1749 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1750 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1751 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001752
James Mattis02220e22021-03-13 19:27:21 -08001753 // Listen to package add/removes for netd
1754 final IntentFilter packageIntentFilter = new IntentFilter();
1755 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1756 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1757 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1758 packageIntentFilter.addDataScheme("package");
1759 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001760 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001761
Motomu Utsumi1e51a642023-07-18 15:11:41 +09001762 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001763
Chalard Jean46bfbf02022-02-02 00:56:25 +09001764 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001765 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001766 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001767 } catch (RemoteException | ServiceSpecificException e) {
1768 loge("Error registering event listener :" + e);
1769 }
1770
Erik Kline05f2b402015-04-30 12:58:40 +09001771 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1772 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001773
chiachangwang7c17c282023-02-02 05:58:59 +00001774 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001775 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001776 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001777
1778 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001779 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001780 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1781 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001782 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001783 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1784 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001785
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001786 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001787 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001788 mNetworkRanker =
1789 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1790
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001791 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001792
Chiachang Wangc1215d32020-10-20 15:38:58 +08001793 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001794 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001795
Chalard Jean28018572020-12-21 18:36:52 +09001796 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1797 // request that doesn't allow fallback to the default network. It should never be visible
1798 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1799 // arguments like the handler or the DnsResolver.
1800 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001801 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001802 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001803 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09001804 new LinkProperties(), new NetworkCapabilities(), null /* localNetworkConfig */,
Chalard Jean28018572020-12-21 18:36:52 +09001805 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001806 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1807 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001808
1809 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001810 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1811 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1812 // Even if it could, running on S would at least require mocking out the BPF map,
1813 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1814 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001815 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001816 mDscpPolicyTracker = new DscpPolicyTracker();
1817 }
Tyler Wear72388212021-09-09 14:49:02 -07001818 } catch (ErrnoException e) {
1819 loge("Unable to create DscpPolicyTracker");
1820 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001821
1822 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1823 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001824
Chalard Jeandf29a852023-05-29 17:02:43 +09001825 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001826 mCdmps = new CompanionDeviceManagerProxyService(context);
1827 } else {
1828 mCdmps = null;
1829 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001830
Chalard Jean2fb66f12023-08-25 12:50:37 +09001831 mRoutingCoordinatorService = new RoutingCoordinatorService(netd);
1832
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001833 mDestroyFrozenSockets = mDeps.isAtLeastU()
1834 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
1835 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1836 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
1837 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001838 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1839 new UidFrozenStateChangedCallback() {
1840 @Override
1841 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1842 if (uids.length != frozenStates.length) {
1843 Log.wtf(TAG, "uids has length " + uids.length
1844 + " but frozenStates has length " + frozenStates.length);
1845 return;
1846 }
1847
1848 final UidFrozenStateChangedArgs args =
1849 new UidFrozenStateChangedArgs(uids, frozenStates);
1850
1851 mHandler.sendMessage(
1852 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1853 }
1854 };
1855
1856 final ActivityManager activityManager =
1857 mContext.getSystemService(ActivityManager.class);
1858 activityManager.registerUidFrozenStateChangedCallback(
1859 (Runnable r) -> r.run(), frozenStateChangedCallback);
1860 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001861 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001862
Xiao Ma0a171c02022-01-23 16:14:51 +00001863 /**
1864 * Check whether or not the device supports Ethernet transport.
1865 */
1866 public static boolean deviceSupportsEthernet(final Context context) {
1867 final PackageManager pm = context.getPackageManager();
1868 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1869 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1870 }
1871
Chalard Jean46adcf32018-04-18 20:18:38 +09001872 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001873 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1874 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001875 }
1876
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001877 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1878 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001879 final NetworkCapabilities netCap = new NetworkCapabilities();
1880 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001881 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001882 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001883 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001884 return netCap;
1885 }
1886
James Mattis45d81842021-01-10 14:24:24 -08001887 private NetworkRequest createDefaultRequest() {
1888 return createDefaultInternetRequestForTransport(
1889 TYPE_NONE, NetworkRequest.Type.REQUEST);
1890 }
1891
lucaslin3ba7cc22022-12-19 02:35:33 +00001892 private NetworkRequest createVpnRequest() {
1893 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1894 .withoutDefaultCapabilities()
1895 .addTransportType(TRANSPORT_VPN)
1896 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1897 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1898 .build();
1899 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1900 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1901 }
1902
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001903 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001904 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001905 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001906 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001907 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001908 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001909 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001910 netCap.addTransportType(transportType);
1911 }
James Mattis45d81842021-01-10 14:24:24 -08001912 return createNetworkRequest(type, netCap);
1913 }
1914
1915 private NetworkRequest createNetworkRequest(
1916 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001917 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001918 }
1919
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001920 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1921 NetworkRequest.Type type) {
1922 final NetworkCapabilities netCap = new NetworkCapabilities();
1923 netCap.clearAll();
1924 netCap.addCapability(capability);
1925 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1926 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1927 }
1928
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001929 // Used only for testing.
1930 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001931 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001932 // changing ContentResolver to make registerContentObserver non-final).
1933 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1934 // by subclassing SettingsObserver.
1935 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001936 void updateAlwaysOnNetworks() {
1937 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001938 }
1939
Erik Kline9a62f012018-03-21 07:18:33 -07001940 // See FakeSettingsProvider comment above.
1941 @VisibleForTesting
1942 void updatePrivateDnsSettings() {
1943 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1944 }
1945
paulhu51f77dc2021-06-07 02:34:20 +00001946 @VisibleForTesting
1947 void updateMobileDataPreferredUids() {
1948 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1949 }
1950
Patrick Rohr2857ac42022-01-21 14:58:16 +01001951 @VisibleForTesting
1952 void updateIngressRateLimit() {
1953 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1954 }
1955
Aaron Huang40b52442021-06-08 04:34:24 +08001956 @VisibleForTesting
1957 void simulateUpdateProxyInfo(@Nullable final Network network,
1958 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001959 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08001960 new Pair<>(network, proxyInfo)).sendToTarget();
1961 }
1962
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001963 private void handleAlwaysOnNetworkRequest(
1964 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001965 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001966 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001967 handleAlwaysOnNetworkRequest(networkRequest, enable);
1968 }
1969
1970 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001971 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001972 if (enable == isEnabled) {
1973 return; // Nothing to do.
1974 }
1975
1976 if (enable) {
1977 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001978 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001979 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001980 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001981 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001982 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1983 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001984 }
1985 }
1986
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001987 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001988 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1989 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1990 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1991 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001992 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1993 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001994 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001995 }
1996
paulhu51f77dc2021-06-07 02:34:20 +00001997 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001998 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001999 private void registerSettingsCallbacks() {
2000 // Watch for global HTTP proxy changes.
2001 mSettingsObserver.observe(
2002 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
2003 EVENT_APPLY_GLOBAL_HTTP_PROXY);
2004
Chalard Jean46bfbf02022-02-02 00:56:25 +09002005 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09002006 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002007 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002008 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
2009
Chalard Jean46bfbf02022-02-02 00:56:25 +09002010 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002011 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002012 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002013 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00002014
2015 // Watch for mobile data preferred uids changes.
2016 mSettingsObserver.observe(
2017 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
2018 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002019
2020 // Watch for ingress rate limit changes.
2021 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002022 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002023 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2024 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002025 }
2026
Erik Kline31b4a9e2018-01-11 21:07:29 +09002027 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002028 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2029 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002030 }
2031 }
2032
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002033 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002034 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2035 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002036 return mNextNetworkRequestId++;
2037 }
2038
junyulai74f9a8b2018-06-13 15:00:37 +08002039 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002040 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002041 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002042 if (network == null) {
2043 return null;
2044 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002045 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002046 }
2047
2048 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002049 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002050 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002051 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002052 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002053
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002054 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002055 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002056 private NetworkAgentInfo getVpnForUid(int uid) {
2057 synchronized (mNetworkForNetId) {
2058 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2059 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002060 if (nai.isVPN() && nai.everConnected()
2061 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002062 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002063 }
2064 }
2065 }
2066 return null;
2067 }
2068
Chalard Jean46bfbf02022-02-02 00:56:25 +09002069 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002070 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002071 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002072 final NetworkAgentInfo nai = getVpnForUid(uid);
2073 if (nai != null) return nai.declaredUnderlyingNetworks;
2074 return null;
2075 }
2076
Lorenzo Colittia7574052021-01-19 01:33:05 +09002077 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002078 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002079
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002080 final Network[] networks = getVpnUnderlyingNetworks(uid);
2081 if (networks != null) {
2082 // getUnderlyingNetworks() returns:
2083 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2084 // empty array => the VPN explicitly said "no default network".
2085 // non-empty array => the VPN specified one or more default networks; we use the
2086 // first one.
2087 if (networks.length > 0) {
2088 nai = getNetworkAgentInfoForNetwork(networks[0]);
2089 } else {
2090 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002091 }
2092 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002093 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002094 }
2095
2096 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002097 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002098 */
paulhu7aeba372020-12-30 00:42:19 +08002099 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2100 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002101 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002102 if (ignoreBlocked) {
2103 return false;
2104 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002105 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002106 final long ident = Binder.clearCallingIdentity();
2107 try {
2108 final boolean metered = nc == null ? true : nc.isMetered();
2109 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2110 } finally {
2111 Binder.restoreCallingIdentity(ident);
2112 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002113 }
2114
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002115 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002116 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2117 return;
2118 }
Hugo Benichi47011212017-03-30 10:46:05 +09002119 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002120 synchronized (mBlockedAppUids) {
2121 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002122 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002123 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002124 blocked = false;
2125 } else {
2126 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002127 }
2128 }
Hugo Benichi47011212017-03-30 10:46:05 +09002129 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2130 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2131 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002132 }
2133
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002134 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002135 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2136 return;
2137 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002138 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002139 final int requestId = nri.getActiveRequest() != null
2140 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002141 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002142 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002143 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002144 }
2145
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002146 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002147 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002148 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002149 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002150 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002151 @NonNull
2152 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2153 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002154 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2155 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2156 // but only exists if an app asks about them or requests them. Ensure the requesting app
2157 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002158 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002159 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2160 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2161 null /* extraInfo */);
2162 }
2163 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002164 return filtered;
2165 }
2166
2167 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2168 boolean ignoreBlocked) {
2169 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2170 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002171 }
2172
2173 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002174 * Return NetworkInfo for the active (i.e., connected) network interface.
2175 * It is assumed that at most one network is active at a time. If more
2176 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002177 * @return the info for the active network, or {@code null} if none is
2178 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002179 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002180 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002181 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002182 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002183 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002184 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002185 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2186 if (nai == null) return null;
2187 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2188 maybeLogBlockedNetworkInfo(networkInfo, uid);
2189 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002190 }
2191
Paul Jensen1f567382015-02-13 14:18:39 -05002192 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002193 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002194 public Network getActiveNetwork() {
2195 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002196 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002197 }
2198
2199 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002200 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002201 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002202 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002203 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002204 }
2205
Chalard Jean46bfbf02022-02-02 00:56:25 +09002206 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002207 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002208 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2209 if (vpnNai != null) {
2210 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2211 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2212 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002213 }
Paul Jensen1f567382015-02-13 14:18:39 -05002214 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002215
James Mattis2516da32021-01-31 17:06:19 -08002216 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002217 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2218 ignoreBlocked)) {
2219 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002220 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002221 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002222 }
2223
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002224 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002225 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002226 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002227 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002228 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2229 if (nai == null) return null;
2230 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002231 }
2232
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002233 /** Returns a NetworkInfo object for a network that doesn't exist. */
2234 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2235 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2236 getNetworkTypeName(networkType), "" /* subtypeName */);
2237 info.setIsAvailable(true);
2238 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2239 // background data is restricted.
2240 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2241 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2242 ? DetailedState.BLOCKED
2243 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002244 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2245 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002246 return info;
2247 }
2248
Lorenzo Colittia7574052021-01-19 01:33:05 +09002249 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002250 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2251 return null;
2252 }
2253 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002254 if (nai == null) {
2255 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002256 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002257 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2258 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002259 }
2260
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002261 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002262 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002263 public NetworkInfo getNetworkInfo(int networkType) {
2264 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002265 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002266 if (getVpnUnderlyingNetworks(uid) != null) {
2267 // A VPN is active, so we may need to return one of its underlying networks. This
2268 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002269 // getNetworkAgentInfoForUid.
2270 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2271 if (nai == null) return null;
2272 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2273 if (networkInfo.getType() == networkType) {
2274 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002275 }
2276 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002277 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002278 }
2279
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002280 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002281 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002282 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002283 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002284 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002285 if (nai == null) return null;
2286 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002287 }
2288
2289 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002290 public NetworkInfo[] getAllNetworkInfo() {
2291 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002292 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002293 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2294 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002295 NetworkInfo info = getNetworkInfo(networkType);
2296 if (info != null) {
2297 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002298 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002299 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002300 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002301 }
2302
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002303 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002304 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002305 public Network getNetworkForType(int networkType) {
2306 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002307 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2308 return null;
2309 }
2310 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2311 if (nai == null) {
2312 return null;
2313 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002314 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002315 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2316 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002317 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002318 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002319 }
2320
2321 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002322 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002323 public Network[] getAllNetworks() {
2324 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002325 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002326 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002327 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002328 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002329 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002330 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002331 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002332 }
2333
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002334 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002335 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002336 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002337 // The basic principle is: if an app's traffic could possibly go over a
2338 // network, without the app doing anything multinetwork-specific,
2339 // (hence, by "default"), then include that network's capabilities in
2340 // the array.
2341 //
2342 // In the normal case, app traffic only goes over the system's default
2343 // network connection, so that's the only network returned.
2344 //
2345 // With a VPN in force, some app traffic may go into the VPN, and thus
2346 // over whatever underlying networks the VPN specifies, while other app
2347 // traffic may go over the system default network (e.g.: a split-tunnel
2348 // VPN, or an app disallowed by the VPN), so the set of networks
2349 // returned includes the VPN's underlying networks and the system
2350 // default.
2351 enforceAccessPermission();
2352
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002353 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002354
James Mattis2516da32021-01-31 17:06:19 -08002355 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2356 if (!nri.isBeingSatisfied()) {
2357 continue;
2358 }
2359 final NetworkAgentInfo nai = nri.getSatisfier();
2360 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2361 if (null != nc
2362 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2363 && !result.containsKey(nai.network)) {
2364 result.put(
2365 nai.network,
2366 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002367 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002368 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2369 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002370 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002371 }
2372
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002373 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002374 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002375 if (null != networks) {
2376 for (final Network network : networks) {
2377 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2378 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002379 result.put(
2380 network,
2381 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002382 nc,
2383 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002384 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002385 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002386 }
2387 }
2388 }
2389
2390 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2391 out = result.values().toArray(out);
2392 return out;
2393 }
2394
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002395 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2396 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2397 // can call sampleConnectivityState and make the checks on it.
2398 @NonNull
2399 private StatsEvent sampleConnectivityStateToStatsEvent() {
2400 final ConnectivityStateSample sample = sampleConnectivityState();
2401 return ConnectivityStatsLog.buildStatsEvent(
2402 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2403 sample.getNetworkCountPerTransports().toByteArray(),
2404 sample.getConnectionDurationPerTransports().toByteArray(),
2405 sample.getNetworkRequestCount().toByteArray(),
2406 sample.getNetworks().toByteArray());
2407 }
2408
2409 /**
2410 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2411 *
2412 * This is used for metrics. These snapshots will be sampled and constitute a base for
2413 * statistics about connectivity state of devices.
2414 */
2415 @VisibleForTesting
2416 @NonNull
2417 public ConnectivityStateSample sampleConnectivityState() {
2418 ensureRunningOnConnectivityServiceThread();
2419 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2420 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2421 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2422 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2423 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2424 return builder.build();
2425 }
2426
2427 private static NetworkCountPerTransports sampleNetworkCount(
2428 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2429 final SparseIntArray countPerTransports = new SparseIntArray();
2430 for (final NetworkAgentInfo nai : nais) {
2431 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2432 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2433 }
2434 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2435 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2436 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2437 c.setTransportTypes(countPerTransports.keyAt(i));
2438 c.setNetworkCount(countPerTransports.valueAt(i));
2439 builder.addNetworkCountForTransports(c);
2440 }
2441 return builder.build();
2442 }
2443
2444 private static ConnectionDurationPerTransports sampleConnectionDuration(
2445 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2446 final ConnectionDurationPerTransports.Builder builder =
2447 ConnectionDurationPerTransports.newBuilder();
2448 for (final NetworkAgentInfo nai : nais) {
2449 final ConnectionDurationForTransports.Builder c =
2450 ConnectionDurationForTransports.newBuilder();
2451 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2452 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2453 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2454 // Add millisPerSecond/2 to round up or down to the nearest value
2455 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2456 builder.addConnectionDurationForTransports(c);
2457 }
2458 return builder.build();
2459 }
2460
2461 private static NetworkRequestCount sampleNetworkRequestCount(
2462 @NonNull final Collection<NetworkRequestInfo> nris) {
2463 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2464 final SparseIntArray countPerType = new SparseIntArray();
2465 for (final NetworkRequestInfo nri : nris) {
2466 final int type;
2467 if (Process.SYSTEM_UID == nri.mAsUid) {
2468 // The request is filed "as" the system, so it's the system on its own behalf.
2469 type = RequestType.RT_SYSTEM.getNumber();
2470 } else if (Process.SYSTEM_UID == nri.mUid) {
2471 // The request is filed by the system as some other app, so it's the system on
2472 // behalf of an app.
2473 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2474 } else {
2475 // Not the system, so it's an app requesting on its own behalf.
2476 type = RequestType.RT_APP.getNumber();
2477 }
2478 countPerType.put(type, countPerType.get(type, 0));
2479 }
2480 for (int i = countPerType.size() - 1; i >= 0; --i) {
2481 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2482 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2483 r.setRequestCount(countPerType.valueAt(i));
2484 builder.addRequestCountForType(r);
2485 }
2486 return builder.build();
2487 }
2488
2489 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2490 final NetworkList.Builder builder = NetworkList.newBuilder();
2491 for (final NetworkAgentInfo nai : nais) {
2492 final NetworkCapabilities nc = nai.networkCapabilities;
2493 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2494 d.setTransportTypes((int) nc.getTransportTypesInternal());
2495 final MeteredState meteredState;
2496 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2497 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2498 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2499 meteredState = MeteredState.METERED_NO;
2500 } else {
2501 meteredState = MeteredState.METERED_YES;
2502 }
2503 d.setMeteredState(meteredState);
2504 final ValidatedState validatedState;
2505 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2506 validatedState = ValidatedState.VS_PORTAL;
2507 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2508 validatedState = ValidatedState.VS_PARTIAL;
2509 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2510 validatedState = ValidatedState.VS_VALID;
2511 } else {
2512 validatedState = ValidatedState.VS_INVALID;
2513 }
2514 d.setValidatedState(validatedState);
2515 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2516 d.setCapabilities(nc.getCapabilitiesInternal());
2517 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2518 builder.addNetworkDescription(d);
2519 }
2520 return builder.build();
2521 }
2522
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002523 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002524 public boolean isNetworkSupported(int networkType) {
2525 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002526 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002527 }
2528
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002529 /**
2530 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002531 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002532 * @return the ip properties for the active network, or {@code null} if
2533 * none is active
2534 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002535 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002536 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002537 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002538 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002539 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2540 if (nai == null) return null;
2541 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002542 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002543 }
2544
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002545 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002546 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002547 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002548 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002549 final LinkProperties lp = getLinkProperties(nai);
2550 if (lp == null) return null;
2551 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002552 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002553 }
2554
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002555 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002556 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002557 public LinkProperties getLinkProperties(Network network) {
2558 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002559 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2560 if (lp == null) return null;
2561 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002562 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002563 }
2564
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002565 @Nullable
2566 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002567 if (nai == null) {
2568 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002569 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002570 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002571 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002572 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002573 }
2574
lucaslinc582d502022-01-27 09:07:00 +08002575 @Override
2576 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002577 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002578 @NonNull String packageName, @Nullable String callingAttributionTag) {
2579 Objects.requireNonNull(packageName);
2580 Objects.requireNonNull(lp);
2581 enforceNetworkStackOrSettingsPermission();
2582 if (!checkAccessPermission(-1 /* pid */, uid)) {
2583 return null;
2584 }
2585 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2586 }
2587
Qingxi Lib2748102020-01-08 12:51:49 -08002588 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2589 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2590 }
2591
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002592 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002593 if (nai == null) return null;
2594 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002595 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002596 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002597 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002598 }
2599
2600 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002601 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2602 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002603 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002604 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002605 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002606 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002607 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002608 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002609 }
2610
lucaslinc582d502022-01-27 09:07:00 +08002611 @Override
lucaslind2b06132022-03-02 10:56:57 +08002612 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2613 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2614 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002615 Objects.requireNonNull(nc);
2616 Objects.requireNonNull(packageName);
2617 enforceNetworkStackOrSettingsPermission();
2618 if (!checkAccessPermission(-1 /* pid */, uid)) {
2619 return null;
2620 }
2621 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2622 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2623 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2624 callingAttributionTag);
2625 }
2626
lucaslin69e1aa92022-03-22 18:15:09 +08002627 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2628 if (nc.getUnderlyingNetworks() != null
2629 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2630 nc.setUnderlyingNetworks(null);
2631 }
2632 }
2633
Qingxi Libb8da982020-01-17 17:54:27 -08002634 @VisibleForTesting
2635 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002636 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002637 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2638 // this would be expensive (one more permission check every time any NC callback is
2639 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2640 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2641 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002642 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002643 if (!checkSettingsPermission(callerPid, callerUid)) {
2644 newNc.setUids(null);
2645 newNc.setSSID(null);
2646 }
Etan Cohen107ae952018-12-30 17:59:59 -08002647 if (newNc.getNetworkSpecifier() != null) {
2648 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2649 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002650 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2651 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002652 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2653 newNc.setAdministratorUids(new int[0]);
2654 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002655 if (!checkAnyPermissionOf(mContext,
Benedict Wong53de25f2021-03-24 14:01:51 -07002656 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002657 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002658 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002659 }
lucaslin69e1aa92022-03-22 18:15:09 +08002660 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002661
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002662 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002663 }
2664
Roshan Pius98f59ec2021-02-23 08:47:39 -08002665 /**
2666 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002667 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002668 * NetworkCapabilities.
2669 * Note: This wrapper does not support any sort of invalidation and thus must not be
2670 * persistent or long-lived. It may only be used for the time necessary to
2671 * compute the redactions required by one particular NetworkCallback or
2672 * synchronous call.
2673 */
2674 private class RedactionPermissionChecker {
2675 private final int mCallingPid;
2676 private final int mCallingUid;
2677 @NonNull private final String mCallingPackageName;
2678 @Nullable private final String mCallingAttributionTag;
2679
2680 private Boolean mHasLocationPermission = null;
2681 private Boolean mHasLocalMacAddressPermission = null;
2682 private Boolean mHasSettingsPermission = null;
2683
2684 RedactionPermissionChecker(int callingPid, int callingUid,
2685 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2686 mCallingPid = callingPid;
2687 mCallingUid = callingUid;
2688 mCallingPackageName = callingPackageName;
2689 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002690 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002691
2692 private boolean hasLocationPermissionInternal() {
2693 final long token = Binder.clearCallingIdentity();
2694 try {
2695 return mLocationPermissionChecker.checkLocationPermission(
2696 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2697 null /* message */);
2698 } finally {
2699 Binder.restoreCallingIdentity(token);
2700 }
2701 }
2702
2703 /**
2704 * Returns whether the app holds location permission or not (might return cached result
2705 * if the permission was already checked before).
2706 */
2707 public boolean hasLocationPermission() {
2708 if (mHasLocationPermission == null) {
2709 // If there is no cached result, perform the check now.
2710 mHasLocationPermission = hasLocationPermissionInternal();
2711 }
2712 return mHasLocationPermission;
2713 }
2714
2715 /**
2716 * Returns whether the app holds local mac address permission or not (might return cached
2717 * result if the permission was already checked before).
2718 */
2719 public boolean hasLocalMacAddressPermission() {
2720 if (mHasLocalMacAddressPermission == null) {
2721 // If there is no cached result, perform the check now.
2722 mHasLocalMacAddressPermission =
2723 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2724 }
2725 return mHasLocalMacAddressPermission;
2726 }
2727
2728 /**
2729 * Returns whether the app holds settings permission or not (might return cached
2730 * result if the permission was already checked before).
2731 */
2732 public boolean hasSettingsPermission() {
2733 if (mHasSettingsPermission == null) {
2734 // If there is no cached result, perform the check now.
2735 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2736 }
2737 return mHasSettingsPermission;
2738 }
2739 }
2740
2741 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2742 @NetworkCapabilities.NetCapability long redaction) {
2743 return (redactions & redaction) != 0;
2744 }
2745
2746 /**
2747 * Use the provided |applicableRedactions| to check the receiving app's
2748 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2749 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2750 * before being sent to the corresponding app.
2751 */
2752 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2753 @NetworkCapabilities.RedactionType long applicableRedactions,
2754 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2755 boolean includeLocationSensitiveInfo) {
2756 long redactions = applicableRedactions;
2757 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2758 if (includeLocationSensitiveInfo
2759 && redactionPermissionChecker.hasLocationPermission()) {
2760 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2761 }
2762 }
2763 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2764 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2765 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2766 }
2767 }
2768 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2769 if (redactionPermissionChecker.hasSettingsPermission()) {
2770 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2771 }
2772 }
2773 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002774 }
2775
Qingxi Lib2748102020-01-08 12:51:49 -08002776 @VisibleForTesting
2777 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002778 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002779 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002780 int callingPid, int callingUid, @NonNull String callingPkgName,
2781 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002782 if (nc == null) {
2783 return null;
2784 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002785 // Avoid doing location permission check if the transport info has no location sensitive
2786 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002787 final RedactionPermissionChecker redactionPermissionChecker =
2788 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2789 callingAttributionTag);
2790 final long redactions = retrieveRequiredRedactions(
2791 nc.getApplicableRedactions(), redactionPermissionChecker,
2792 includeLocationSensitiveInfo);
2793 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002794 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002795 // TODO : calling UID is redacted because apps should generally not know what UID is
2796 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002797 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002798 newNc.setOwnerUid(INVALID_UID);
2799 return newNc;
2800 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002801 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2802 if (nc.hasTransport(TRANSPORT_VPN)) {
2803 // Owner UIDs already checked above. No need to re-check.
2804 return newNc;
2805 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002806 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2807 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002808 // compatibility for older apps.
2809 if (!includeLocationSensitiveInfo
2810 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002811 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002812 newNc.setOwnerUid(INVALID_UID);
2813 return newNc;
2814 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002815 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002816 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002817 newNc.setOwnerUid(INVALID_UID);
2818 }
Qingxi Lib2748102020-01-08 12:51:49 -08002819 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002820 }
2821
lucaslinc582d502022-01-27 09:07:00 +08002822 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002823 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2824 LinkProperties lp, int callerPid, int callerUid) {
2825 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002826 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2827 // this would be expensive (one more permission check every time any LP callback is
2828 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2829 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2830 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002831
2832 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2833 final boolean needsSanitization =
2834 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2835 if (!needsSanitization) {
2836 return new LinkProperties(lp);
2837 }
2838
2839 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002840 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002841 }
2842
2843 final LinkProperties newLp = new LinkProperties(lp);
2844 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2845 // object gets parceled.
2846 newLp.setCaptivePortalApiUrl(null);
2847 newLp.setCaptivePortalData(null);
2848 return newLp;
2849 }
2850
Roshan Pius08c94fb2020-01-16 12:17:17 -08002851 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2852 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002853 // There is no need to track the effective UID of the request here. If the caller
2854 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002855 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002856 // Unprivileged apps can only pass in null or their own UID.
2857 if (nc.getUids() == null) {
2858 // If the caller passes in null, the callback will also match networks that do not
2859 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2860 // In this case, redact everything in the request immediately. This ensures that the
2861 // app is not able to get any redacted information by filing an unredacted request
2862 // and observing whether the request matches something.
2863 if (nc.getNetworkSpecifier() != null) {
2864 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2865 }
2866 } else {
2867 nc.setSingleUid(callerUid);
2868 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002869 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002870 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002871 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002872
2873 // Clear owner UID; this can never come from an app.
2874 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002875 }
2876
Chalard Jean38354d12018-03-20 19:13:57 +09002877 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002878 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002879 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2880 }
2881 }
2882
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002883 @Override
2884 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2885 enforceAccessPermission();
2886 final int callerUid = Binder.getCallingUid();
2887 final long token = Binder.clearCallingIdentity();
2888 try {
2889 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2890 } finally {
2891 Binder.restoreCallingIdentity(token);
2892 }
2893 }
2894
junyulaiebd15162021-03-03 12:09:05 +08002895 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002896 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002897 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002898 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002899 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002900
Serik Beketayev05130302021-01-15 16:47:25 -08002901 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002902 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002903 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2904 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002905 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002906 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002907 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002908 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2909 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002910 }
2911 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002912 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002913 }
2914
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002915 @Override
junyulaiebd15162021-03-03 12:09:05 +08002916 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002917 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002918 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002919 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002920
2921 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2922 for (Network network : getAllNetworks()) {
2923 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09002924 final boolean includeNetwork = (nai != null) && nai.isCreated();
2925 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002926 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2927 // NetworkCapabilities, which may contain UIDs of apps to which the
2928 // network applies. Should the UIDs be cleared so as not to leak or
2929 // interfere ?
2930 result.add(nai.getNetworkStateSnapshot());
2931 }
2932 }
2933 return result;
2934 }
2935
2936 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002937 public boolean isActiveNetworkMetered() {
2938 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002939
Qingxi Lib2748102020-01-08 12:51:49 -08002940 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002941 if (caps != null) {
2942 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2943 } else {
2944 // Always return the most conservative value
2945 return true;
2946 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002947 }
2948
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002949 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002950 * Ensures that the system cannot call a particular method.
2951 */
2952 private boolean disallowedBecauseSystemCaller() {
2953 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002954 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2955 // for devices launched with Q and above. However, existing devices upgrading to Q and
2956 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002957 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002958 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002959 log("This method exists only for app backwards compatibility"
2960 + " and must not be called by system services.");
2961 return true;
2962 }
2963 return false;
2964 }
2965
paulhub2c28682021-08-18 18:35:54 +08002966 private int getAppUid(final String app, final UserHandle user) {
2967 final PackageManager pm =
2968 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2969 final long token = Binder.clearCallingIdentity();
2970 try {
2971 return pm.getPackageUid(app, 0 /* flags */);
2972 } catch (PackageManager.NameNotFoundException e) {
2973 return -1;
2974 } finally {
2975 Binder.restoreCallingIdentity(token);
2976 }
2977 }
2978
2979 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2980 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2981 if (getAppUid(packageName, user) != callingUid) {
2982 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2983 }
2984 }
2985
Lorenzo Colitti23862912018-09-28 11:31:55 +09002986 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002987 * Ensure that a network route exists to deliver traffic to the specified
2988 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002989 * @param networkType the type of the network over which traffic to the
2990 * specified host is to be routed
2991 * @param hostAddress the IP address of the host to which the route is
2992 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002993 * @return {@code true} on success, {@code false} on failure
2994 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002995 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002996 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2997 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002998 if (disallowedBecauseSystemCaller()) {
2999 return false;
3000 }
paulhub2c28682021-08-18 18:35:54 +08003001 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003002 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003003 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003004 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003005 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003006
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003007 InetAddress addr;
3008 try {
3009 addr = InetAddress.getByAddress(hostAddress);
3010 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003011 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003012 return false;
3013 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003014
The Android Open Source Project28527d22009-03-03 19:31:44 -08003015 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003016 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003017 return false;
3018 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003019
3020 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3021 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003022 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003023 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3024 } else {
3025 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3026 }
3027 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003028 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003029
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003030 DetailedState netState;
3031 synchronized (nai) {
3032 netState = nai.networkInfo.getDetailedState();
3033 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003034
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003035 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003036 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003037 log("requestRouteToHostAddress on down network "
3038 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003039 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003040 }
3041 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003042 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003043
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003044 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003045 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003046 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003047 LinkProperties lp;
3048 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003049 synchronized (nai) {
3050 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003051 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003052 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003053 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003054 if (DBG) {
3055 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3056 }
Wink Saville32506bc2013-06-29 21:10:57 -07003057 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003058 } finally {
3059 Binder.restoreCallingIdentity(token);
3060 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003061 }
3062
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003063 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003064 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003065 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003066 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003067 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003068 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003069 if (bestRoute.getGateway().equals(addr)) {
3070 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003071 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003072 } else {
3073 // if we will connect to this through another route, add a direct route
3074 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003075 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003076 }
3077 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003078 if (DBG) log("Adding legacy route " + bestRoute +
3079 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003080
3081 final String dst = bestRoute.getDestinationLinkAddress().toString();
3082 final String nextHop = bestRoute.hasGateway()
3083 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003084 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003085 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3086 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003087 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003088 return false;
3089 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003090 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003091 }
3092
paulhu7c0a2e62021-01-08 00:51:49 +08003093 class DnsResolverUnsolicitedEventCallback extends
3094 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003095 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003096 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003097 try {
3098 mHandler.sendMessage(mHandler.obtainMessage(
3099 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003100 new PrivateDnsValidationUpdate(event.netId,
3101 InetAddresses.parseNumericAddress(event.ipAddress),
3102 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003103 } catch (IllegalArgumentException e) {
3104 loge("Error parsing ip address in validation event");
3105 }
3106 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003107
3108 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003109 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3110 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003111 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3112 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3113 // event callback for certain nai. e.g. cellular. Register here to pass to
3114 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003115 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003116 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3117 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003118 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003119 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003120 }
3121 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003122
3123 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003124 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3125 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3126 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003127 }
dalyk1720e542018-03-05 12:42:22 -05003128
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003129 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003130 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003131 return this.VERSION;
3132 }
3133
3134 @Override
3135 public String getInterfaceHash() {
3136 return this.HASH;
3137 }
paulhu7c0a2e62021-01-08 00:51:49 +08003138 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003139
3140 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003141 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3142 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003143
paulhu7c0a2e62021-01-08 00:51:49 +08003144 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003145 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003146 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003147 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003148 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003149 }
3150 }
3151
Sudheer Shanka9967d462021-03-18 19:09:25 +00003152 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003153 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003154 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003155 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3156 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003157 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003158 };
3159
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003160 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003161 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003162 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003163 }
3164
Mark Fasheh7c999d82023-05-04 20:23:11 +00003165 static final class UidFrozenStateChangedArgs {
3166 final int[] mUids;
3167 final int[] mFrozenStates;
3168
3169 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3170 mUids = uids;
3171 mFrozenStates = frozenStates;
3172 }
3173 }
3174
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003175 /**
3176 * Check if the cell network is idle.
3177 * @return true if the cell network state is idle
3178 * false if the cell network state is active or unknown
3179 */
3180 private boolean isCellNetworkIdle() {
3181 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3182 if (defaultNai == null
3183 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3184 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3185 // cell network is not the default network, cell network state is unknown.
3186 // TODO(b/279380356): Track cell network state when the cell is not the default network
3187 return false;
3188 }
3189
3190 return !mNetworkActivityTracker.isDefaultNetworkActive();
3191 }
3192
Mark Fasheh7c999d82023-05-04 20:23:11 +00003193 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003194 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003195
3196 for (int i = 0; i < uids.length; i++) {
3197 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003198 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003199 } else {
3200 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003201 }
3202 }
3203
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003204 if (ownerUids.isEmpty()) {
3205 return;
3206 }
3207
3208 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3209 // Delay closing sockets to avoid waking the cell modem up.
3210 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3211 // than waking cell modem up.
3212 mPendingFrozenUids.addAll(ownerUids);
3213 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003214 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003215 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003216 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003217 loge("Exception in socket destroy: " + e);
3218 }
3219 }
3220 }
3221
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003222 private void closePendingFrozenSockets() {
3223 ensureRunningOnConnectivityServiceThread();
3224
3225 try {
3226 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3227 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3228 loge("Failed to close pending frozen app sockets: " + e);
3229 }
3230 mPendingFrozenUids.clear();
3231 }
3232
3233 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3234 mNetworkActivityTracker.handleReportNetworkActivity(params);
3235
3236 if (mDelayDestroyFrozenSockets
3237 && params.isActive
3238 && params.label == TRANSPORT_CELLULAR
3239 && !mPendingFrozenUids.isEmpty()) {
3240 closePendingFrozenSockets();
3241 }
3242 }
3243
3244 /**
3245 * If the cellular network is no longer the default network, close pending frozen sockets.
3246 *
3247 * @param newNetwork new default network
3248 * @param oldNetwork old default network
3249 */
3250 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3251 NetworkAgentInfo oldNetwork) {
3252 final boolean isOldNetworkCellular = oldNetwork != null
3253 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3254 final boolean isNewNetworkCellular = newNetwork != null
3255 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3256
3257 if (isOldNetworkCellular
3258 && !isNewNetworkCellular
3259 && !mPendingFrozenUids.isEmpty()) {
3260 closePendingFrozenSockets();
3261 }
3262 }
3263
3264 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3265 pw.println("CloseFrozenAppSockets:");
3266 pw.increaseIndent();
3267 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3268 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3269 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3270 pw.decreaseIndent();
3271 }
3272
Junyu Lai155760b2023-10-05 14:51:00 +08003273 private void dumpBpfProgramStatus(IndentingPrintWriter pw) {
3274 pw.println("Bpf Program Status:");
3275 pw.increaseIndent();
3276 try {
3277 pw.print("CGROUP_INET_INGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003278 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_INGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003279 pw.print("CGROUP_INET_EGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003280 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_EGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003281 pw.print("CGROUP_INET_SOCK_CREATE: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003282 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_CREATE));
Junyu Lai155760b2023-10-05 14:51:00 +08003283 pw.print("CGROUP_INET4_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003284 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003285 pw.print("CGROUP_INET6_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003286 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003287 } catch (IOException e) {
3288 pw.println(" IOException");
3289 }
3290 pw.decreaseIndent();
3291 }
3292
Mark Fasheh7c999d82023-05-04 20:23:11 +00003293 @VisibleForTesting
3294 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003295 @VisibleForTesting
3296 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3297 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003298
Paul Jensen83f5d572014-08-29 09:54:01 -04003299 private void enforceInternetPermission() {
3300 mContext.enforceCallingOrSelfPermission(
3301 android.Manifest.permission.INTERNET,
3302 "ConnectivityService");
3303 }
3304
The Android Open Source Project28527d22009-03-03 19:31:44 -08003305 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003306 mContext.enforceCallingOrSelfPermission(
3307 android.Manifest.permission.ACCESS_NETWORK_STATE,
3308 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003309 }
3310
lucaslinc582d502022-01-27 09:07:00 +08003311 private boolean checkAccessPermission(int pid, int uid) {
3312 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3313 == PERMISSION_GRANTED;
3314 }
3315
paulhua6ee2122021-02-22 15:40:43 +08003316 /**
3317 * Performs a strict and comprehensive check of whether a calling package is allowed to
3318 * change the state of network, as the condition differs for pre-M, M+, and
3319 * privileged/preinstalled apps. The caller is expected to have either the
3320 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3321 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3322 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3323 * permission and cannot be revoked. See http://b/23597341
3324 *
3325 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3326 * of this app will be updated to the current time.
3327 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003328 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003329 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3330 == PackageManager.PERMISSION_GRANTED) {
3331 return;
3332 }
3333
3334 if (callingPkg == null) {
3335 throw new SecurityException("Calling package name is null.");
3336 }
3337
3338 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3339 final int uid = mDeps.getCallingUid();
3340 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3341 callingPkg, callingAttributionTag, null /* message */);
3342
3343 if (mode == AppOpsManager.MODE_ALLOWED) {
3344 return;
3345 }
3346
3347 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3348 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3349 return;
3350 }
3351
3352 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3353 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3354 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003355 }
3356
Charles He9369e612017-05-15 17:07:18 +01003357 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003358 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003359 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003360 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003361 }
3362
Quang Luong98858d62023-02-11 00:25:24 +00003363 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003364 enforceAnyPermissionOf(mContext,
3365 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003366 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003367 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3368 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3369 }
3370
paulhu8e96a752019-08-12 16:25:11 +08003371 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003372 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003373 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003374 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003375 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003376 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003377 }
3378
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003379 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003380 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003381 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003382 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003383 android.Manifest.permission.NETWORK_SETTINGS,
3384 android.Manifest.permission.NETWORK_FACTORY,
3385 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3386 }
3387
3388 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003389 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003390 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003391 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003392 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3393 android.Manifest.permission.NETWORK_FACTORY,
3394 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3395 }
3396
lucaslin69e1aa92022-03-22 18:15:09 +08003397 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3398 return PERMISSION_GRANTED == mContext.checkPermission(
3399 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3400 || PERMISSION_GRANTED == mContext.checkPermission(
3401 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3402 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003403 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003404 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003405 }
3406
Chalard Jean9a396cc2018-02-21 18:43:54 +09003407 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003408 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003409 android.Manifest.permission.NETWORK_SETTINGS,
3410 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003411 }
3412
3413 private boolean checkSettingsPermission(int pid, int uid) {
3414 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003415 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3416 || PERMISSION_GRANTED == mContext.checkPermission(
3417 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003418 }
3419
paulhu8e96a752019-08-12 16:25:11 +08003420 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003421 enforceNetworkStackPermissionOr(mContext,
3422 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003423 }
3424
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003425 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003426 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003427 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003428 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003429 }
3430
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003431 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003432 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003433 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3434 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003435 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003436 }
3437
James Mattis8378aec2021-01-26 14:05:36 -08003438 private void enforceOemNetworkPreferencesPermission() {
3439 mContext.enforceCallingOrSelfPermission(
3440 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3441 "ConnectivityService");
3442 }
3443
James Mattisfa270db2021-05-31 17:11:10 -07003444 private void enforceManageTestNetworksPermission() {
3445 mContext.enforceCallingOrSelfPermission(
3446 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3447 "ConnectivityService");
3448 }
3449
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003450 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003451 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003452 android.Manifest.permission.NETWORK_STACK,
3453 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003454 }
3455
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003456 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003457 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003458 android.Manifest.permission.NETWORK_STACK,
3459 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3460 }
3461
paulhu1a407652019-03-22 16:35:06 +08003462 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003463 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003464 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003465 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3466 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003467 }
3468
Paul Hu8fc2a552022-05-04 18:44:42 +08003469 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3470 boolean checkUidsAllowedList) {
3471 if (PermissionUtils.checkAnyPermissionOf(mContext,
3472 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3473 return true;
3474 }
3475
3476 // fallback to ConnectivityInternalPermission
3477 // TODO: Remove this fallback check after all apps have declared
3478 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3479 if (PermissionUtils.checkAnyPermissionOf(mContext,
3480 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3481 return true;
3482 }
3483
3484 // Check whether uid is in allowed on restricted networks list.
3485 if (checkUidsAllowedList
3486 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3487 return true;
3488 }
3489 return false;
3490 }
3491
3492 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3493 final int callingUid = mDeps.getCallingUid();
3494 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3495 throw new SecurityException("ConnectivityService: user " + callingUid
3496 + " has no permission to access restricted network.");
3497 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003498 }
3499
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003500 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003501 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003502 }
3503
Roshan Pius98f59ec2021-02-23 08:47:39 -08003504 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3505 return PERMISSION_GRANTED == mContext.checkPermission(
3506 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3507 }
3508
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003509 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003510 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003511 }
3512
3513 private void sendInetConditionBroadcast(NetworkInfo info) {
3514 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3515 }
3516
Wink Saville4f0de1e2011-08-04 15:01:58 -07003517 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003518 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003519 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003520 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003521 if (info.isFailover()) {
3522 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3523 info.setFailover(false);
3524 }
3525 if (info.getReason() != null) {
3526 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3527 }
3528 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003529 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3530 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003531 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003532 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003533 return intent;
3534 }
3535
3536 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3537 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3538 }
3539
Michael Groover73f69482023-01-27 11:01:25 -06003540 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3541 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003542 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3543 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003544 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003545 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003546 if (!mSystemReady
3547 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003548 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003549 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003550 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003551 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003552 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003553 }
3554
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003555 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003556 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003557 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003558 final NetworkInfo ni = intent.getParcelableExtra(
3559 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003560 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3561 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003562 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003563 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003564 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003565 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003566 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003567 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003568 } finally {
3569 Binder.restoreCallingIdentity(ident);
3570 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003571 }
3572 }
3573
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003574 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3575 NetworkInfo info) {
3576 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003577 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003578
3579 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3580 try {
3581 // This allows us to discard older broadcasts still waiting to be delivered
3582 // which have the same namespace and key.
3583 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3584 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3585 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003586 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003587 } catch (UnsupportedApiLevelException e) {
3588 Log.wtf(TAG, "Using unsupported API" + e);
3589 }
3590 }
3591
3592 @VisibleForTesting
3593 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3594 final StringBuilder sb = new StringBuilder();
3595 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3596 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3597 sb.append(info.getExtraInfo());
3598 return sb.toString();
3599 }
3600
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003601 /**
Aaron Huang96011892020-06-27 07:18:23 +08003602 * Called by SystemServer through ConnectivityManager when the system is ready.
3603 */
3604 @Override
3605 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003606 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003607 throw new SecurityException("Calling Uid is not system uid.");
3608 }
3609 systemReadyInternal();
3610 }
3611
3612 /**
3613 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003614 */
3615 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003616 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003617 // Load flags after PackageManager is ready to query module version
3618 mFlags.loadFlags(mDeps, mContext);
3619
Aaron Huang9a57acf2020-12-08 10:03:29 +08003620 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3621 // listening network request which is sent by MultipathPolicyTracker won't be added
3622 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3623 // be called after PermissionMonitor#startMonitoring().
3624 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3625 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3626 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003627 final ConditionVariable startMonitoringDone = new ConditionVariable();
3628 mHandler.post(() -> {
3629 mPermissionMonitor.startMonitoring();
3630 startMonitoringDone.open();
3631 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003632 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003633 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003634
Hugo Benichie5220992017-04-26 14:53:28 +09003635 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003636 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003637 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003638 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003639 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003640 }
3641 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003642
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003643 // Create network requests for always-on networks.
3644 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003645
3646 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003647 // Note that updating can be skipped here if the list is empty only because no uid
3648 // rules are applied before system ready. Normally, the empty uid list means to clear
3649 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003650 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3651 updateMobileDataPreferredUids();
3652 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003653
3654 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003655 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003656 mBpfNetMaps.setPullAtomCallback(mContext);
3657 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003658 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3659 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003660 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3661 // have permission problem. While CV#block() is unbounded in time and can in principle block
3662 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3663 // could have blocked forever too.
3664 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003665 }
3666
The Android Open Source Project28527d22009-03-03 19:31:44 -08003667 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003668 * Start listening for default data network activity state changes.
3669 */
3670 @Override
3671 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003672 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003673 }
3674
3675 /**
3676 * Stop listening for default data network activity state changes.
3677 */
3678 @Override
3679 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003680 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003681 }
3682
3683 /**
3684 * Check whether the default network radio is currently active.
3685 */
3686 @Override
3687 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003688 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003689 }
3690
3691 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003692 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003693 * and set it on it's iface.
3694 */
Junyu Lai970963e2022-10-25 15:46:47 +08003695 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003696 final String iface = newLp.getInterfaceName();
3697 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003698 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003699 // Silently ignore unset MTU value.
3700 return;
3701 }
Hansen Kurli04252032022-12-07 11:21:49 +00003702 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3703 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3704 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003705 return;
3706 }
Hansen Kurli04252032022-12-07 11:21:49 +00003707 // Cannot set MTU without interface name
3708 if (TextUtils.isEmpty(iface)) {
3709 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003710 return;
3711 }
sy.yun4aa73922013-09-02 05:24:09 +09003712
Hansen Kurli04252032022-12-07 11:21:49 +00003713 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3714 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003715 return;
3716 }
3717
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003718 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003719 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003720 mNetd.interfaceSetMtu(iface, mtu);
3721 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003722 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003723 }
3724 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003725
Chenbo Feng15416292018-11-08 17:36:21 -08003726 @VisibleForTesting
3727 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003728
Junyu Lai970963e2022-10-25 15:46:47 +08003729 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003730 String[] values = null;
3731 if (tcpBufferSizes != null) {
3732 values = tcpBufferSizes.split(",");
3733 }
3734
3735 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003736 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003737 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3738 values = tcpBufferSizes.split(",");
3739 }
3740
3741 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3742
3743 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003744 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003745
Chenbo Feng15416292018-11-08 17:36:21 -08003746 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3747 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3748 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003749 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003750 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003751 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003752 }
3753 }
3754
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003755 @Override
3756 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003757 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003758 NETWORK_RESTORE_DELAY_PROP_NAME);
3759 if(restoreDefaultNetworkDelayStr != null &&
3760 restoreDefaultNetworkDelayStr.length() != 0) {
3761 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003762 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003763 } catch (NumberFormatException e) {
3764 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003765 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003766 // if the system property isn't set, use the value for the apn type
3767 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3768
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003769 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3770 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003771 }
3772 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003773 }
3774
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003775 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003776 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003777 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003778 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003779 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003780 // Start gathering diagnostic information.
3781 netDiags.add(new NetworkDiagnostics(
3782 nai.network,
3783 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003784 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003785 DIAG_TIME_MS));
3786 }
3787
3788 for (NetworkDiagnostics netDiag : netDiags) {
3789 pw.println();
3790 netDiag.waitForMeasurements();
3791 netDiag.dump(pw);
3792 }
3793 }
3794
The Android Open Source Project28527d22009-03-03 19:31:44 -08003795 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003796 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3797 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003798 if (!checkDumpPermission(mContext, TAG, writer)) return;
3799
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003800 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003801 }
3802
lucaslin99473f62020-12-10 15:10:54 +08003803 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3804 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3805 != PackageManager.PERMISSION_GRANTED) {
3806 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003807 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003808 + " due to missing android.permission.DUMP permission");
3809 return false;
3810 } else {
3811 return true;
3812 }
3813 }
3814
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003815 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003816 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003817
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003818 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003819 dumpNetworkDiagnostics(pw);
3820 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003821 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003822 dumpNetworks(pw);
3823 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003824 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003825 dumpNetworkRequests(pw);
3826 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003827 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3828 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3829 dumpTrafficController(pw, fd, verbose);
3830 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003831 }
Erik Kline9647f382015-06-05 17:47:34 +09003832
Junyu Lai0da479b2022-04-20 15:06:29 +08003833 pw.println("NetworkProviders for:");
3834 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003835 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003836 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003837 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003838 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003839 pw.println();
3840
Chalard Jean5b409c72021-02-04 13:12:59 +09003841 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003842 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003843 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003844 pw.println("none");
3845 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003846 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003847 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003848 pw.println();
3849
James Mattis8b298a02021-06-01 22:34:04 -07003850 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003851 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003852 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003853 pw.decreaseIndent();
3854 pw.println();
3855
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003856 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003857 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003858 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003859 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003860 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003861
junyulaif2c67e42018-08-07 19:50:45 +08003862 pw.println("Status for known UIDs:");
3863 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003864 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003865 for (int i = 0; i < size; i++) {
3866 // Don't crash if the array is modified while dumping in bugreports.
3867 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003868 final int uid = mUidBlockedReasons.keyAt(i);
3869 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3870 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003871 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003872 } catch (ArrayIndexOutOfBoundsException e) {
3873 pw.println(" ArrayIndexOutOfBoundsException");
3874 } catch (ConcurrentModificationException e) {
3875 pw.println(" ConcurrentModificationException");
3876 }
3877 }
3878 pw.println();
3879 pw.decreaseIndent();
3880
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003881 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003882 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003883 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003884 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003885 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003886
Junyu Lai0da479b2022-04-20 15:06:29 +08003887 pw.println("Network Offers:");
3888 pw.increaseIndent();
3889 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3890 pw.println(offerInfo.offer);
3891 }
3892 pw.decreaseIndent();
3893 pw.println();
3894
Robert Greenwalt94e22142014-07-30 16:31:24 -07003895 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003896
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003897 pw.println();
markchien5e866652019-09-30 14:40:57 +08003898 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003899
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003900 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003901 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003902
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003903 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003904 dumpCloseFrozenAppSockets(pw);
3905
3906 pw.println();
Junyu Lai155760b2023-10-05 14:51:00 +08003907 dumpBpfProgramStatus(pw);
3908
3909 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003910
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003911 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003912 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003913 pw.println("mNetworkRequestInfoLogs (most recent first):");
3914 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003915 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003916 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003917
3918 pw.println();
3919 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3920 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003921 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003922 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003923
3924 pw.println();
3925 pw.println("NetTransition WakeLock activity (most recent first):");
3926 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003927 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3928 pw.println("total releases: " + mTotalWakelockReleases);
3929 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3930 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3931 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3932 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3933 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3934 }
James Mattiscb1e0362021-04-06 17:07:42 -07003935 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003936
3937 pw.println();
3938 pw.println("bandwidth update requests (by uid):");
3939 pw.increaseIndent();
3940 synchronized (mBandwidthRequests) {
3941 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3942 pw.println("[" + mBandwidthRequests.keyAt(i)
3943 + "]: " + mBandwidthRequests.valueAt(i));
3944 }
3945 }
3946 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003947 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003948
James Mattiscb1e0362021-04-06 17:07:42 -07003949 pw.println();
3950 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3951 pw.increaseIndent();
3952 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003953 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003954 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003955
3956 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003957
3958 pw.println();
3959 pw.println("Permission Monitor:");
3960 pw.increaseIndent();
3961 mPermissionMonitor.dump(pw);
3962 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003963
3964 pw.println();
3965 pw.println("Legacy network activity:");
3966 pw.increaseIndent();
3967 mNetworkActivityTracker.dump(pw);
3968 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003969 }
3970
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003971 private void dumpNetworks(IndentingPrintWriter pw) {
3972 for (NetworkAgentInfo nai : networksSortedById()) {
3973 pw.println(nai.toString());
3974 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003975 pw.println("Nat464Xlat:");
3976 pw.increaseIndent();
3977 nai.dumpNat464Xlat(pw);
3978 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003979 pw.println(String.format(
3980 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3981 nai.numForegroundNetworkRequests(),
3982 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3983 nai.numBackgroundNetworkRequests(),
3984 nai.numNetworkRequests()));
3985 pw.increaseIndent();
3986 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3987 pw.println(nai.requestAt(i).toString());
3988 }
3989 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003990 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003991 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003992 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003993 pw.decreaseIndent();
3994 pw.decreaseIndent();
3995 }
3996 }
3997
James Mattis8b298a02021-06-01 22:34:04 -07003998 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3999 if (!mProfileNetworkPreferences.isEmpty()) {
4000 pw.println("Profile preferences:");
4001 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09004002 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07004003 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08004004 }
James Mattis8b298a02021-06-01 22:34:04 -07004005 if (!mOemNetworkPreferences.isEmpty()) {
4006 pw.println("OEM preferences:");
4007 pw.increaseIndent();
4008 pw.println(mOemNetworkPreferences);
4009 pw.decreaseIndent();
4010 }
4011 if (!mMobileDataPreferredUids.isEmpty()) {
4012 pw.println("Mobile data preferred UIDs:");
4013 pw.increaseIndent();
4014 pw.println(mMobileDataPreferredUids);
4015 pw.decreaseIndent();
4016 }
James Mattis45d81842021-01-10 14:24:24 -08004017
James Mattis8b298a02021-06-01 22:34:04 -07004018 pw.println("Default requests:");
4019 pw.increaseIndent();
4020 dumpPerAppDefaultRequests(pw);
4021 pw.decreaseIndent();
4022 }
4023
4024 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08004025 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
4026 if (mDefaultRequest == defaultRequest) {
4027 continue;
4028 }
4029
James Mattis8b298a02021-06-01 22:34:04 -07004030 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
4031 final String networkOutput;
4032 if (null == satisfier) {
4033 networkOutput = "null";
4034 } else if (mNoServiceNetwork.equals(satisfier)) {
4035 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08004036 } else {
James Mattis8b298a02021-06-01 22:34:04 -07004037 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08004038 }
James Mattis8b298a02021-06-01 22:34:04 -07004039 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
4040 ? "" : " asUid: " + defaultRequest.mAsUid;
4041 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
4042 + defaultRequest.mPid + asUidString + "]";
4043 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4044 + " Preference order: " + defaultRequest.mPreferenceOrder
4045 + " Tracked UIDs: " + defaultRequest.getUids();
4046 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004047 }
4048 }
4049
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004050 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004051 NetworkRequestInfo[] infos = null;
4052 while (infos == null) {
4053 try {
4054 infos = requestsSortedById();
4055 } catch (ConcurrentModificationException e) {
4056 // mNetworkRequests should only be accessed from handler thread, except dump().
4057 // As dump() is never called in normal usage, it would be needlessly expensive
4058 // to lock the collection only for its benefit. Instead, retry getting the
4059 // requests if ConcurrentModificationException is thrown during dump().
4060 }
4061 }
4062 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004063 pw.println(nri.toString());
4064 }
4065 }
4066
Ken Chene6d511f2022-01-25 11:10:42 +08004067 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4068 boolean verbose) {
4069 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004070 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004071 } catch (ServiceSpecificException e) {
4072 pw.println(e.getMessage());
4073 } catch (IOException e) {
4074 loge("Dump BPF maps failed, " + e);
4075 }
4076 }
4077
Chalard Jean524f0b12021-10-25 21:11:56 +09004078 private void dumpAllRequestInfoLogsToLogcat() {
4079 try (PrintWriter logPw = new PrintWriter(new Writer() {
4080 @Override
4081 public void write(final char[] cbuf, final int off, final int len) {
4082 // This method is called with 0-length and 1-length arrays for empty strings
4083 // or strings containing only the DEL character.
4084 if (len <= 1) return;
4085 Log.e(TAG, new String(cbuf, off, len));
4086 }
4087 @Override public void flush() {}
4088 @Override public void close() {}
4089 })) {
4090 mNetworkRequestInfoLogs.dump(logPw);
4091 }
4092 }
4093
Hugo Benichia480ba52018-09-03 08:19:02 +09004094 /**
4095 * Return an array of all current NetworkAgentInfos sorted by network id.
4096 */
4097 private NetworkAgentInfo[] networksSortedById() {
4098 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004099 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004100 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004101 return networks;
4102 }
4103
4104 /**
4105 * Return an array of all current NetworkRequest sorted by request id.
4106 */
James Mattis258ea3c2020-11-15 15:04:40 -08004107 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004108 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004109 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004110 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004111 // Sort the array based off the NRI containing the min requestId in its requests.
4112 Arrays.sort(requests,
4113 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4114 Comparator.comparingInt(req -> req.requestId)).requestId
4115 )
4116 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004117 return requests;
4118 }
4119
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004120 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004121 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004122 if (officialNai != null && officialNai.equals(nai)) return true;
4123 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004124 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004125 " - " + nai);
4126 }
4127 return false;
4128 }
4129
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004130 private boolean isDisconnectRequest(Message msg) {
4131 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4132 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4133 return info.getState() == NetworkInfo.State.DISCONNECTED;
4134 }
4135
Robert Greenwalt2034b912009-08-12 16:08:25 -07004136 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004137 private class NetworkStateTrackerHandler extends Handler {
4138 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004139 super(looper);
4140 }
4141
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004142 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004143 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4144 final NetworkAgentInfo nai = arg.first;
4145 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004146 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004147 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004148 }
4149 return;
4150 }
4151
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004152 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004153 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004154 return;
4155 }
4156
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004157 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004158 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean78c9a382023-10-26 19:53:33 +09004159 final NetworkCapabilities proposed = (NetworkCapabilities) arg.second;
4160 if (!nai.respectsNcStructuralConstraints(proposed)) {
4161 Log.wtf(TAG, "Agent " + nai + " violates nc structural constraints : "
4162 + nai.networkCapabilities + " -> " + proposed);
4163 disconnectAndDestroyNetwork(nai);
4164 return;
4165 }
4166 nai.setDeclaredCapabilities(proposed);
Chalard Jean39b12d42022-02-27 12:08:49 +09004167 final NetworkCapabilities sanitized =
4168 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004169 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004170 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004171 break;
4172 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004173 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004174 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004175 processLinkPropertiesFromAgent(nai, newLp);
4176 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004177 break;
4178 }
4179 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004180 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004181 updateNetworkInfo(nai, info);
4182 break;
4183 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004184 case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
4185 final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
4186 updateLocalNetworkConfig(nai, config);
4187 break;
4188 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004189 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004190 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004191 break;
4192 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004193 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004194 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004195 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004196 // Note that if the NAI had been connected, this would affect the
4197 // score, and therefore would require re-mixing the score and performing
4198 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004199 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004200 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4201 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004202 // Mark the network as temporarily accepting partial connectivity so that it
4203 // will be validated (and possibly become default) even if it only provides
4204 // partial internet access. Note that if user connects to partial connectivity
4205 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4206 // out of wifi coverage) and if the same wifi is available again, the device
4207 // will auto connect to this wifi even though the wifi has "no internet".
4208 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004209 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004210 break;
4211 }
junyulai011b1f12019-01-03 18:50:15 +08004212 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004213 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004214 break;
4215 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004216 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004217 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004218 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004219
4220 if (isLegacyLockdownNai(nai)
4221 && (underlying == null || underlying.size() != 1)) {
4222 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4223 + " must have exactly one underlying network: " + underlying);
4224 }
4225
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004226 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4227 nai.declaredUnderlyingNetworks = (underlying != null)
4228 ? underlying.toArray(new Network[0]) : null;
4229
4230 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4231 if (DBG) {
4232 log(nai.toShortString() + " changed underlying networks to "
4233 + Arrays.toString(nai.declaredUnderlyingNetworks));
4234 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004235 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004236 notifyIfacesChangedForNetworkStats();
4237 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004238 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004239 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004240 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4241 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4242 nai.teardownDelayMs = msg.arg1;
4243 } else {
4244 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4245 }
Chalard Jean550b5212021-03-05 23:07:53 +09004246 break;
4247 }
4248 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4249 nai.setLingerDuration((int) arg.second);
4250 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004251 }
Tyler Wear72388212021-09-09 14:49:02 -07004252 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4253 DscpPolicy policy = (DscpPolicy) arg.second;
4254 if (mDscpPolicyTracker != null) {
4255 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4256 }
4257 break;
4258 }
4259 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4260 if (mDscpPolicyTracker != null) {
4261 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4262 }
4263 break;
4264 }
4265 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4266 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004267 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004268 }
4269 break;
4270 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004271 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004272 if (!nai.everConnected()) {
4273 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4274 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004275 teardownUnneededNetwork(nai);
4276 break;
4277 }
4278
4279 if (nai.isDestroyed()) {
4280 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4281 + ", ignoring");
4282 break;
4283 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004284
4285 final int timeoutMs = (int) arg.second;
4286 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4287 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4288 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4289 }
4290
4291 // Marking a network awaiting replacement is used to ensure that any requests
4292 // satisfied by the network do not switch to another network until a
4293 // replacement is available or the wait for a replacement times out.
4294 // If the network is inactive (i.e., nascent or lingering), then there are no
4295 // such requests, and there is no point keeping it. Just tear it down.
4296 // Note that setLingerDuration(0) cannot be used to do this because the network
4297 // could be nascent.
4298 nai.clearInactivityState();
4299 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4300 Log.d(TAG, nai.toShortString()
4301 + " marked awaiting replacement is unneeded, tearing down instead");
4302 teardownUnneededNetwork(nai);
4303 break;
4304 }
4305
4306 Log.d(TAG, "Marking " + nai.toShortString()
4307 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4308 destroyNativeNetwork(nai);
4309
4310 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4311 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4312 // consider the fact that the network could already have disconnected or been
4313 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4314 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4315 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4316 mKeepaliveTracker.handleStopAllKeepalives(nai,
4317 SocketKeepalive.ERROR_INVALID_NETWORK);
4318
4319 nai.updateScoreForNetworkAgentUpdate();
4320 // This rematch is almost certainly not going to result in any changes, because
4321 // the destroyed flag is only just above the "current satisfier wins"
4322 // tie-breaker. But technically anything that affects scoring should rematch.
4323 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004324 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004325 break;
4326 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004327 }
4328 }
4329
4330 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004331 final int netId = msg.arg2;
4332 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004333 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004334 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004335 switch (msg.what) {
4336 default:
4337 return false;
lucasline117e2e2019-10-22 18:27:33 +08004338 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004339 if (nai == null) {
4340 break;
4341 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004342 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4343 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004344 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004345 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004346 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004347 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004348 if (probePrivateDnsCompleted) {
4349 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4350 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004351 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004352 }
4353 // Only show the notification when the private DNS is broken and the
4354 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004355 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004356 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4357 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004358 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004359 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4360 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4361 // private DNS is broken, it means this network is being reevaluated.
4362 // Either probing private DNS is not necessary any more or it hasn't been
4363 // done yet. In either case, the networkCapabilities should be updated to
4364 // reflect the new status.
4365 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004366 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004367 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004368 }
4369 break;
4370 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004371 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004372 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4373
Erik Kline31b4a9e2018-01-11 21:07:29 +09004374 if (nai == null) break;
4375
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004376 handleNetworkTested(nai, results.mTestResult,
4377 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004378 break;
4379 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004380 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004381 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004382 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004383 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004384 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004385 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004386 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4387 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004388 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004389 if (nai == null) {
4390 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4391 break;
4392 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004393 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004394 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004395 (PendingIntent) msg.obj,
4396 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004397 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004398 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004399 break;
4400 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004401 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004402 if (nai == null) break;
4403
Erik Kline9a62f012018-03-21 07:18:33 -07004404 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004405 break;
4406 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004407 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004408 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004409 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004410 break;
4411 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004412 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004413 return true;
4414 }
4415
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004416 private void handleNetworkTested(
4417 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004418 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4419 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004420 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004421
4422 // If there is any kind of working networking, then the NAI has been evaluated
4423 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4424 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004425 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004426 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004427 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4428 // any callback that receives onAvailable for that rematch receives an extra caps
4429 // callback. To prevent that, update the score in the agent so the updates below won't
4430 // see an update to both caps and score at the same time.
4431 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004432 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4433
he_won.hwang881307a2022-03-15 21:23:52 +09004434 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4435 // Assume the validation failure is due to a temporary failure after roaming
4436 // and ignore it. NetworkMonitor will continue to retry validation. If it
4437 // continues to fail after the block timeout expires, the network will be
4438 // marked unvalidated. If it succeeds, then validation state will not change.
4439 return;
4440 }
4441
Chalard Jean254bd162022-08-25 13:04:51 +09004442 final boolean wasValidated = nai.isValidated();
4443 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004444 final boolean wasPortal = nai.captivePortalDetected();
4445 nai.setPartialConnectivity(partial);
4446 nai.setCaptivePortalDetected(portal);
4447 nai.updateScoreForNetworkAgentUpdate();
4448 final boolean partialConnectivityChanged = (wasPartial != partial);
4449 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004450
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004451 if (DBG) {
4452 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4453 ? " with redirect to " + redirectUrl
4454 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004455 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004456 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004457 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004458 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004459 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004460 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004461 if (valid) {
4462 handleFreshlyValidatedNetwork(nai);
4463 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4464 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004465 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004466 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004467 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004468 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004469 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004470 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004471 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004472 NotificationType.PRIVATE_DNS_BROKEN);
4473 // If network becomes valid, the hasShownBroken should be reset for
4474 // that network so that the notification will be fired when the private
4475 // DNS is broken again.
4476 nai.networkAgentConfig.hasShownBroken = false;
4477 }
4478 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004479 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004480 } else if (portalChanged) {
4481 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004482 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004483 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4484 nai.onPreventAutomaticReconnect();
4485 teardownUnneededNetwork(nai);
4486 return;
4487 } else {
4488 updateCapabilitiesForNetwork(nai);
4489 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004490 } else if (becameEvaluated) {
4491 // If valid or partial connectivity changed, updateCapabilities* has
4492 // done the rematch.
4493 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004494 }
4495 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004496
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004497 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004498 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004499 nai.onValidationStatusChanged(
4500 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4501 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004502
4503 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004504 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004505 // immediately. Re-notify partial connectivity silently if no internet
4506 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004507 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004508 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004509 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4510 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004511 }
4512
Chalard Jean254bd162022-08-25 13:04:51 +09004513 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004514 handleNetworkUnvalidated(nai);
4515 }
4516 }
4517
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004518 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4519 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4520 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4521 // Do not avoid captive portal when network is wear proxy.
4522 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4523 }
4524
Calvin Ondada1452016-10-11 15:10:46 -07004525 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004526 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4527 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004528 }
4529
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004530 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4531 switch (msg.what) {
4532 default:
4533 return false;
4534 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4535 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4536 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4537 handleLingerComplete(nai);
4538 }
4539 break;
4540 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004541 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4542 handleNetworkAgentRegistered(msg);
4543 break;
4544 }
4545 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4546 handleNetworkAgentDisconnected(msg);
4547 break;
4548 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004549 }
4550 return true;
4551 }
4552
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004553 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004554 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004555 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004556 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004557 maybeHandleNetworkAgentMessage(msg);
4558 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004559 }
4560 }
4561
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004562 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004563 private final int mNetId;
4564 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004565
4566 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004567 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004568 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004569 }
4570
4571 @Override
4572 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4573 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004574 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004575 }
4576
4577 @Override
4578 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004579 // Legacy version of notifyNetworkTestedWithExtras.
4580 // Would only be called if the system has a NetworkStack module older than the
4581 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004582 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004583 }
4584
4585 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004586 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004587 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4588 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004589 final Message msg = mTrackerHandler.obtainMessage(
4590 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004591 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004592 new NetworkTestedResults(
4593 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004594 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004595
4596 // Invoke ConnectivityReport generation for this Network test event.
4597 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4598 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004599
Cody Kestingf1120be2020-08-03 18:01:40 -07004600 // NetworkMonitor reports the network validation result as a bitmask while
4601 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4602 // logical value for ConnectivityDiagnostics.
4603 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4604 p.result);
4605
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004606 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004607 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004608 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4609 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4610
Aaron Huang959d3642021-01-21 15:47:41 +08004611 ConnectivityReportEvent reportEvent =
4612 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4613 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004614 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004615 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004616 }
4617
4618 @Override
4619 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4620 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4621 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004622 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004623 }
4624
4625 @Override
lucasline117e2e2019-10-22 18:27:33 +08004626 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4627 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4628 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004629 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004630 }
4631
4632 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004633 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4634 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4635 EVENT_CAPPORT_DATA_CHANGED,
4636 0, mNetId, data));
4637 }
4638
4639 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004640 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004641 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004642 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004643
4644 final PendingIntent pendingIntent;
4645 // Only the system server can register notifications with package "android"
4646 final long token = Binder.clearCallingIdentity();
4647 try {
paulhu7746e4e2020-06-09 19:07:03 +08004648 pendingIntent = PendingIntent.getBroadcast(
4649 mContext,
4650 0 /* requestCode */,
4651 intent,
4652 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004653 } finally {
4654 Binder.restoreCallingIdentity(token);
4655 }
4656 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4657 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004658 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004659 }
4660
4661 @Override
4662 public void hideProvisioningNotification() {
4663 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004664 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004665 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004666
4667 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004668 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004669 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004670 }
4671
4672 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004673 public int getInterfaceVersion() {
4674 return this.VERSION;
4675 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004676
4677 @Override
4678 public String getInterfaceHash() {
4679 return this.HASH;
4680 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004681 }
4682
Cody Kestingf1120be2020-08-03 18:01:40 -07004683 /**
4684 * Converts the given NetworkMonitor-specific validation result bitmask to a
4685 * ConnectivityDiagnostics-specific validation result int.
4686 */
4687 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4688 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4689 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4690 }
4691 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4692 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4693 }
4694 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4695 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4696 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4697 }
4698
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004699 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004700 log("Data stall detected with methods: " + p.detectionMethod);
4701
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004702 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004703 int detectionMethod = 0;
4704 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4705 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4706 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4707 }
4708 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4709 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4710 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4711 p.tcpMetricsCollectionPeriodMillis);
4712 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004713 }
4714
Cody Kestingf53a0752020-04-15 12:33:28 -07004715 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004716 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004717 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004718
4719 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4720 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4721 // the cost of going through two handlers.
4722 mConnectivityDiagnosticsHandler.sendMessage(msg);
4723 }
4724
Cody Kestingb37958e2020-05-15 10:36:01 -07004725 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4726 return (p.detectionMethod & detectionMethod) != 0;
4727 }
4728
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004729 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4730 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004731 }
4732
Erik Klinea73af002018-06-26 18:53:43 +09004733 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4734 if (nai == null) return;
4735 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4736 // in order to restart a validation pass from within netd.
4737 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4738 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004739 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004740 }
4741 }
4742
Erik Kline31b4a9e2018-01-11 21:07:29 +09004743 private void handlePrivateDnsSettingsChanged() {
4744 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4745
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004746 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004747 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004748 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004749 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4750 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004751 }
4752 }
4753
Erik Kline9a62f012018-03-21 07:18:33 -07004754 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4755 // Private DNS only ever applies to networks that might provide
4756 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004757 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004758
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004759 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004760 // schedule DNS resolutions. If a DNS resolution is required the
4761 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004762 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004763
4764 // With Private DNS bypass support, we can proceed to update the
4765 // Private DNS config immediately, even if we're in strict mode
4766 // and have not yet resolved the provider name into a set of IPs.
4767 updatePrivateDns(nai, cfg);
4768 }
4769
4770 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4771 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004772 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004773 }
4774
dalyk1720e542018-03-05 12:42:22 -05004775 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4776 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4777 if (nai == null) {
4778 return;
4779 }
4780 mDnsManager.updatePrivateDnsValidation(update);
4781 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4782 }
4783
paulhu7c0a2e62021-01-08 00:51:49 +08004784 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004785 int prefixLength) {
4786 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4787 if (nai == null) return;
4788
paulhu7c0a2e62021-01-08 00:51:49 +08004789 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4790 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004791
4792 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004793 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004794 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004795 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004796 prefixLength);
4797 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004798 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004799 return;
4800 }
4801 }
4802
Lorenzo Colittid523d142020-04-01 20:16:30 +09004803 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004804 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4805 }
4806
Hai Shalome58bdc62021-01-11 18:45:34 -08004807 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004808 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004809 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004810 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4811 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4812 }
4813
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004814 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004815 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004816 * @param nai the agent info to update
4817 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004818 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004819 */
junyulai2b6f0c22021-02-03 20:15:30 +08004820 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4821 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4822 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004823 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004824 // one lingered request, set inactive.
4825 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004826 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004827 if (DBG) log("Unsetting inactive " + nai.toShortString());
4828 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004829 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004830 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004831 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004832 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4833 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004834 }
junyulai2b6f0c22021-02-03 20:15:30 +08004835 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004836 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004837 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004838 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004839 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004840 }
4841
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004842 private void handleNetworkAgentRegistered(Message msg) {
4843 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4844 if (!mNetworkAgentInfos.contains(nai)) {
4845 return;
4846 }
4847
4848 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4849 if (VDBG) log("NetworkAgent registered");
4850 } else {
4851 loge("Error connecting NetworkAgent");
4852 mNetworkAgentInfos.remove(nai);
4853 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004854 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004855 synchronized (mNetworkForNetId) {
4856 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004857 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004858 mNetIdManager.releaseNetId(nai.network.getNetId());
4859 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004860 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004861 }
4862 }
4863 }
Paul Jensend5f53392014-11-25 15:26:53 -05004864
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004865 @VisibleForTesting
4866 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09004867 // The feature of creating the networks immediately was slated for U, but race conditions
4868 // detected late required this was flagged off.
4869 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
4870 // in NetworkAgentTest.
4871 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004872 }
4873
4874 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4875 @NonNull NetworkInfo.State state) {
4876 if (nai.isCreated()) return false;
4877 if (state == NetworkInfo.State.CONNECTED) return true;
4878 if (state != NetworkInfo.State.CONNECTING) {
4879 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09004880 if (shouldCreateNetworksImmediately()) {
4881 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4882 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004883 return false;
4884 }
4885 return nai.isVPN() || shouldCreateNetworksImmediately();
4886 }
4887
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004888 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004889 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004890 }
4891
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004892 @VisibleForTesting
4893 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004894 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09004895 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004896
4897 // If the network never roamed, return false. The check below is not sufficient if time
4898 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4899 if (nai.lastRoamTime == 0) return false;
4900
he_won.hwang881307a2022-03-15 21:23:52 +09004901 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4902 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004903 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004904 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004905 final long currentTimeMs = SystemClock.elapsedRealtime();
4906 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004907 if (timeSinceLastRoam <= blockTimeOut) {
4908 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4909 return true;
4910 }
4911 }
4912 return false;
4913 }
4914
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004915 private void handleNetworkAgentDisconnected(Message msg) {
4916 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004917 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004918 }
4919
Chalard Jeand9fffc32018-05-11 20:19:20 +09004920 // Destroys a network, remove references to it from the internal state managed by
4921 // ConnectivityService, free its interfaces and clean up.
4922 // Must be called on the Handler thread.
4923 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004924 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004925
4926 if (!mNetworkAgentInfos.contains(nai)) return;
4927
Chalard Jeand9fffc32018-05-11 20:19:20 +09004928 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004929 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004930 }
lucaslinb25c9a62019-02-12 15:30:13 +08004931 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004932 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004933 // A network agent has disconnected.
4934 // TODO - if we move the logic to the network agent (have them disconnect
4935 // because they lost all their requests or because their score isn't good)
4936 // then they would disconnect organically, report their new state and then
4937 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08004938 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004939 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4940 null, null);
4941 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004942 final boolean wasDefault = isDefaultNetwork(nai);
4943 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004944 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004945 }
4946 notifyIfacesChangedForNetworkStats();
4947 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4948 // by other networks that are already connected. Perhaps that can be done by
4949 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4950 // of rematchAllNetworksAndRequests
4951 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004952 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004953
4954 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004955 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4956 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08004957 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004958 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004959 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004960 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004961 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004962 synchronized (mNetworkForNetId) {
4963 // Remove the NetworkAgent, but don't mark the netId as
4964 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004965 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004966 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004967 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08004968 // Update allowed network lists in netd. This should be called after removing nai
4969 // from mNetworkAgentInfos.
4970 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004971 // Remove all previously satisfied requests.
4972 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004973 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004974 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004975 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004976 if (currentNetwork != null
4977 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004978 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004979 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4980 // rematch not to keep disconnected agents instead of setting it here ; this
4981 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004982 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004983 for (final NetworkOfferInfo noi : mNetworkOffers) {
4984 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004985 }
James Mattise3ef1912020-12-20 11:09:58 -08004986
Chalard Jean5b409c72021-02-04 13:12:59 +09004987 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004988 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004989 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004990 // network, because while incorrect this is the closest to the old (also
4991 // incorrect) behavior.
4992 mNetworkActivityTracker.updateDataActivityTracking(
4993 null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004994 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004995 ensureNetworkTransitionWakelock(nai.toShortString());
4996 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004997 }
4998 }
junyulai2b6f0c22021-02-03 20:15:30 +08004999 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08005000 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09005001 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08005002 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09005003 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005004 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005005 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005006
Aaron Huang9fe47be2021-06-08 13:11:45 +08005007 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
5008 // The obvious place to do this would be in makeDefault(), however makeDefault() is
5009 // not called by the rematch in this case. This is because the code above unset
5010 // this network from the default request's satisfier, and that is what the rematch
5011 // is using as its source data to know what the old satisfier was. So as far as the
5012 // rematch above is concerned, the old default network was null.
5013 // Therefore if there is no new default, the default network was null and is still
5014 // null, thus there was no change so makeDefault() is not called. So if the old
5015 // network had a proxy and there is no new default, the proxy tracker should be told
5016 // that there is no longer a default proxy.
5017 // Strictly speaking this is not essential because having a proxy setting when
5018 // there is no network is harmless, but it's still counter-intuitive so reset to null.
5019 mProxyTracker.setDefaultProxy(null);
5020 }
5021
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005022 // Immediate teardown.
5023 if (nai.teardownDelayMs == 0) {
5024 destroyNetwork(nai);
5025 return;
5026 }
5027
5028 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09005029 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05305030 try {
5031 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
5032 } catch (RemoteException e) {
5033 Log.d(TAG, "Error marking network restricted during teardown: ", e);
5034 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005035 }
5036 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
5037 }
5038
5039 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005040 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005041 // Tell netd to clean up the configuration for this network
5042 // (routing rules, DNS, etc).
5043 // This may be slow as it requires a lot of netd shelling out to ip and
5044 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09005045 // after we've rematched networks with requests (which might change the default
5046 // network or service a new request from an app), so network traffic isn't interrupted
5047 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08005048 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005049 }
Chalard Jeandf29a852023-05-29 17:02:43 +09005050 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005051 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
5052 // This can never run if the code above runs because shouldDestroyNativeNetwork is
5053 // false if the network was never created.
5054 // TODO: delete when S is no longer supported.
5055 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005056 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08005057 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005058 }
5059
Ken Chen6df7a902021-04-09 15:08:42 +08005060 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08005061 try {
5062 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005063 final NativeNetworkConfig config;
5064 if (nai.isVPN()) {
5065 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005066 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005067 return false;
5068 }
5069 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5070 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005071 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005072 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005073 } else {
Chalard Jeane0aaca52023-10-17 13:23:07 +09005074 final boolean hasLocalCap =
5075 nai.networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
5076 config = new NativeNetworkConfig(nai.network.getNetId(),
5077 hasLocalCap ? NativeNetworkType.PHYSICAL_LOCAL : NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005078 getNetworkPermission(nai.networkCapabilities),
5079 false /* secure */,
5080 VpnManager.TYPE_VPN_NONE,
5081 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005082 }
Ken Chen6df7a902021-04-09 15:08:42 +08005083 mNetd.networkCreate(config);
5084 mDnsResolver.createNetworkCache(nai.network.getNetId());
Ken Chen6b134f12023-10-07 07:46:47 +08005085 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(),
5086 nai.networkCapabilities);
Luke Huangfdd11f82019-04-09 18:41:49 +08005087 return true;
5088 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005089 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005090 return false;
5091 }
5092 }
5093
Ken Chen6df7a902021-04-09 15:08:42 +08005094 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005095 if (mDscpPolicyTracker != null) {
5096 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5097 }
Luke Huangfdd11f82019-04-09 18:41:49 +08005098 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005099 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005100 } catch (RemoteException | ServiceSpecificException e) {
5101 loge("Exception destroying network(networkDestroy): " + e);
5102 }
5103 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005104 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005105 } catch (RemoteException | ServiceSpecificException e) {
5106 loge("Exception destroying network: " + e);
5107 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005108 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5109 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5110 // gets created, could add data to DnsManager data structures that will never get deleted.
5111 mDnsManager.removeNetwork(nai.network);
5112
5113 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005114 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005115 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5116 }
5117
Chalard Jean254bd162022-08-25 13:04:51 +09005118 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005119 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005120 }
5121
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005122 // If this method proves to be too slow then we can maintain a separate
5123 // pendingIntent => NetworkRequestInfo map.
5124 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5125 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005126 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5127 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5128 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005129 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005130 return entry.getValue();
5131 }
5132 }
5133 return null;
5134 }
5135
Chalard Jean524f0b12021-10-25 21:11:56 +09005136 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005137 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005138 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5139 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5140 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5141 // bug is fixed.
5142 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005143 throw new IllegalStateException("This NRI is already registered. New : " + nri
5144 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005145 }
5146 }
5147 }
5148 }
5149
Chalard Jeanac9ace02022-01-26 16:54:05 +09005150 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5151 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005152 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09005153 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
5154 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005155 }
5156 return false;
5157 }
5158
James Mattisf7027322020-12-13 16:28:14 -08005159 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005160 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005161 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5162 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5163 final NetworkRequestInfo existingRequest =
5164 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005165 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005166 if (DBG) {
5167 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5168 + nri.mRequests.get(0) + " because their intents matched.");
5169 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005170 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005171 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005172 }
Erik Kline05f2b402015-04-30 12:58:40 +09005173 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005174 }
5175
James Mattisf7027322020-12-13 16:28:14 -08005176 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005177 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005178 }
5179
James Mattis3ce3d3c2021-02-09 18:18:28 -08005180 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005181 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005182 for (final NetworkRequestInfo nri : nris) {
5183 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005184 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005185 for (final NetworkRequest req : nri.mRequests) {
5186 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005187 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005188 if (req.isListen()) {
5189 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5190 if (req.networkCapabilities.hasSignalStrength()
5191 && network.satisfiesImmutableCapabilitiesOf(req)) {
5192 updateSignalStrengthThresholds(network, "REGISTER", req);
5193 }
James Mattisf7027322020-12-13 16:28:14 -08005194 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005195 }
5196 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005197
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005198 // If this NRI has a satisfier already, it is replacing an older request that
5199 // has been removed. Track it.
5200 final NetworkRequest activeRequest = nri.getActiveRequest();
5201 if (null != activeRequest) {
5202 // If there is an active request, then for sure there is a satisfier.
5203 nri.getSatisfier().addRequest(activeRequest);
5204 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005205 }
James Mattisf7027322020-12-13 16:28:14 -08005206
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005207 if (mFlags.noRematchAllRequestsOnRegister()) {
5208 rematchNetworksAndRequests(nris);
5209 } else {
5210 rematchAllNetworksAndRequests();
5211 }
James Mattis45d81842021-01-10 14:24:24 -08005212
Chalard Jean0354d8c2021-01-12 10:58:56 +09005213 // Requests that have not been matched to a network will not have been sent to the
5214 // providers, because the old satisfier and the new satisfier are the same (null in this
5215 // case). Send these requests to the providers.
5216 for (final NetworkRequestInfo nri : nris) {
5217 for (final NetworkOfferInfo noi : mNetworkOffers) {
5218 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005219 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005220 }
5221 }
5222
James Mattisf7027322020-12-13 16:28:14 -08005223 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5224 final int callingUid) {
5225 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005226 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005227 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5228 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5229 handleReleaseNetworkRequest(
5230 nri.mRequests.get(0),
5231 callingUid,
5232 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005233 }
5234 }
5235
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005236 // Determines whether the network is the best (or could become the best, if it validated), for
5237 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5238 // on the value of reason:
5239 //
5240 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5241 // then it should be torn down.
5242 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5243 // then it should be lingered.
5244 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005245 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005246
Chalard Jean254bd162022-08-25 13:04:51 +09005247 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005248 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5249 return false;
5250 }
5251
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005252 final int numRequests;
5253 switch (reason) {
5254 case TEARDOWN:
5255 numRequests = nai.numRequestNetworkRequests();
5256 break;
5257 case LINGER:
5258 numRequests = nai.numForegroundNetworkRequests();
5259 break;
5260 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005261 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005262 return true;
5263 }
5264
Chalard Jean947acd42021-03-08 22:29:27 +09005265 if (numRequests > 0) return false;
5266
Paul Jensende49eb12015-06-25 15:30:08 -04005267 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005268 if (reason == UnneededFor.LINGER
5269 && !nri.isMultilayerRequest()
5270 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005271 // Background requests don't affect lingering.
5272 continue;
5273 }
5274
James Mattis3d229892020-11-16 16:46:28 -08005275 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005276 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005277 }
5278 }
Paul Jensende49eb12015-06-25 15:30:08 -04005279 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005280 }
5281
James Mattis3d229892020-11-16 16:46:28 -08005282 private boolean isNetworkPotentialSatisfier(
5283 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
Chalard Jean80685f42023-10-30 18:31:27 +09005284 // While destroyed network sometimes satisfy requests (including occasionally newly
5285 // satisfying requests), *potential* satisfiers are networks that might beat a current
5286 // champion if they validate. As such, a destroyed network is never a potential satisfier,
5287 // because it's never a good idea to keep a destroyed network in case it validates.
5288 // For example, declaring it a potential satisfier would keep an unvalidated destroyed
5289 // candidate after it's been replaced by another unvalidated network.
5290 if (candidate.isDestroyed()) return false;
5291 // Listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005292 // request, return immediately. For multilayer requests, check to see if any of the
5293 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005294 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5295 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005296 return false;
5297 }
5298 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005299 // This multilayer listen request is satisfied therefore no further requests need to be
5300 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005301 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005302 return false;
5303 }
James Mattis3d229892020-11-16 16:46:28 -08005304 // As non-multilayer listen requests have already returned, the below would only happen
5305 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005306 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005307 continue;
5308 }
Chalard Jean80685f42023-10-30 18:31:27 +09005309 // If there is hope for this network might validate and subsequently become the best
5310 // network for that request, then it is needed. Note that this network can't already
5311 // be the best for this request, or it would be the current satisfier, and therefore
5312 // there would be no need to call this method to find out if it is a *potential*
5313 // satisfier ("unneeded", the only caller, only calls this if this network currently
5314 // satisfies no request).
James Mattis3d229892020-11-16 16:46:28 -08005315 if (candidate.satisfies(req)) {
5316 // As soon as a network is found that satisfies a request, return. Specifically for
5317 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5318 // is important so as to not evaluate lower priority requests further in
5319 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005320 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5321 ? nri.getSatisfier() : null;
5322 // Note that this catches two important cases:
5323 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5324 // is currently satisfying the request. This is desirable when
5325 // cellular ends up validating but WiFi does not.
5326 // 2. Unvalidated WiFi will not be reaped when validated cellular
5327 // is currently satisfying the request. This is desirable when
5328 // WiFi ends up validating and out scoring cellular.
5329 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005330 }
5331 }
5332
5333 return false;
5334 }
5335
Erik Kline0c04b742016-07-07 16:50:58 +09005336 private NetworkRequestInfo getNriForAppRequest(
5337 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005338 // Looking up the app passed param request in mRequests isn't possible since it may return
5339 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5340 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005341 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5342 // to avoid potential race conditions when validating a package->uid mapping when sending
5343 // the callback on the very low-chance that an application shuts down prior to the callback
5344 // being sent.
5345 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5346 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005347
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005348 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005349 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005350 log(String.format("UID %d attempted to %s for unowned request %s",
5351 callingUid, requestedOperation, nri));
5352 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005353 }
Erik Kline0c04b742016-07-07 16:50:58 +09005354 }
5355
5356 return nri;
5357 }
5358
James Mattisf7027322020-12-13 16:28:14 -08005359 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5360 final String callingMethod) {
5361 if (nri.isMultilayerRequest()) {
5362 throw new IllegalStateException(
5363 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005364 }
5365 }
5366
James Mattisf7027322020-12-13 16:28:14 -08005367 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005368 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005369 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5370 // single NetworkRequest and thus does not apply to multilayer requests.
5371 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5372 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005373 return;
5374 }
James Mattis2516da32021-01-31 17:06:19 -08005375 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005376 return;
5377 }
James Mattisf7027322020-12-13 16:28:14 -08005378 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5379 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005380 }
5381 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005382 callCallbackForRequest(
5383 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005384 }
5385
James Mattisf7027322020-12-13 16:28:14 -08005386 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5387 final int callingUid,
5388 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005389 final NetworkRequestInfo nri =
5390 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5391 if (nri == null) {
5392 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005393 }
James Mattisf7027322020-12-13 16:28:14 -08005394 if (VDBG || (DBG && request.isRequest())) {
5395 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005396 }
5397 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005398 if (callOnUnavailable) {
5399 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5400 }
Erik Kline155a59a2015-11-25 12:49:38 +09005401 }
Erik Kline0c04b742016-07-07 16:50:58 +09005402
James Mattisa076c532020-12-02 14:12:41 -08005403 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005404 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005405 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005406 if (null == mNetworkRequests.remove(req)) {
5407 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5408 continue;
5409 }
James Mattisa076c532020-12-02 14:12:41 -08005410 if (req.isListen()) {
5411 removeListenRequestFromNetworks(req);
5412 }
5413 }
James Mattis8f036802021-06-20 16:26:01 -07005414 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005415 if (mDefaultNetworkRequests.remove(nri)) {
5416 // If this request was one of the defaults, then the UID rules need to be updated
5417 // WARNING : if the app(s) for which this network request is the default are doing
5418 // traffic, this will kill their connected sockets, even if an equivalent request
5419 // is going to be reinstated right away ; unconnected traffic will go on the default
5420 // until the new default is set, which will happen very soon.
5421 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5422 // remove ranges for those requests that won't have a replacement
5423 final NetworkAgentInfo satisfier = nri.getSatisfier();
5424 if (null != satisfier) {
5425 try {
paulhu0e79d952021-06-09 16:11:35 +08005426 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5427 satisfier.network.getNetId(),
5428 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005429 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005430 } catch (RemoteException e) {
5431 loge("Exception setting network preference default network", e);
5432 }
5433 }
5434 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005435
Junyu Lai00d92df2022-07-05 11:01:52 +08005436 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005437 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005438 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005439
5440 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005441 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005442 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005443 }
5444 }
5445
Chalard Jean0354d8c2021-01-12 10:58:56 +09005446 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5447 // needed for this offer.
5448 for (final NetworkOfferInfo noi : mNetworkOffers) {
5449 for (final NetworkRequest req : nri.mRequests) {
5450 if (req.isRequest() && noi.offer.neededFor(req)) {
5451 noi.offer.onNetworkUnneeded(req);
5452 }
5453 }
5454 }
James Mattisa076c532020-12-02 14:12:41 -08005455 }
5456
James Mattis3ce3d3c2021-02-09 18:18:28 -08005457 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5458 for (final NetworkRequestInfo nri : nris) {
5459 if (mDefaultRequest == nri) {
5460 // Make sure we never remove the default request.
5461 continue;
5462 }
5463 handleRemoveNetworkRequest(nri);
5464 }
5465 }
5466
James Mattisa076c532020-12-02 14:12:41 -08005467 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5468 // listens don't have a singular affected Network. Check all networks to see
5469 // if this listen request applies and remove it.
5470 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5471 nai.removeRequest(req.requestId);
5472 if (req.networkCapabilities.hasSignalStrength()
5473 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5474 updateSignalStrengthThresholds(nai, "RELEASE", req);
5475 }
5476 }
5477 }
5478
5479 /**
5480 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5481 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5482 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5483 */
5484 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5485 boolean wasKept = false;
5486 final NetworkAgentInfo nai = nri.getSatisfier();
5487 if (nai != null) {
5488 final int requestLegacyType = nri.getActiveRequest().legacyType;
5489 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5490 nai.removeRequest(nri.getActiveRequest().requestId);
5491 if (VDBG || DDBG) {
5492 log(" Removing from current network " + nai.toShortString()
5493 + ", leaving " + nai.numNetworkRequests() + " requests.");
5494 }
5495 // If there are still lingered requests on this network, don't tear it down,
5496 // but resume lingering instead.
5497 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005498 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005499 notifyNetworkLosing(nai, now);
5500 }
5501 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5502 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5503 teardownUnneededNetwork(nai);
5504 } else {
5505 wasKept = true;
5506 }
James Mattisa076c532020-12-02 14:12:41 -08005507 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5508 // Went from foreground to background.
5509 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005510 }
5511
Erik Kline0c04b742016-07-07 16:50:58 +09005512 // Maintain the illusion. When this request arrived, we might have pretended
5513 // that a network connected to serve it, even though the network was already
5514 // connected. Now that this request has gone away, we might have to pretend
5515 // that the network disconnected. LegacyTypeTracker will generate that
5516 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005517 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005518 boolean doRemove = true;
5519 if (wasKept) {
5520 // check if any of the remaining requests for this network are for the
5521 // same legacy type - if so, don't remove the nai
5522 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5523 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005524 if (otherRequest.legacyType == requestLegacyType
5525 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005526 if (DBG) log(" still have other legacy request - leaving");
5527 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005528 }
5529 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005530 }
5531
Erik Kline0c04b742016-07-07 16:50:58 +09005532 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005533 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005534 }
5535 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005536 }
5537 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005538
Junyu Lai00d92df2022-07-05 11:01:52 +08005539 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005540 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005541 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5542 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5543 }
5544
Lorenzo Colittid6459092016-07-04 12:55:44 +09005545 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005546 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005547 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005548 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005549 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005550 }
5551
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005552 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005553 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5554 enforceNetworkStackSettingsOrSetup();
5555 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5556 encodeBool(accept), encodeBool(always), network));
5557 }
5558
5559 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005560 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005561 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005562 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5563 }
5564
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005565 @Override
5566 public void setTestAllowBadWifiUntil(long timeMs) {
5567 enforceSettingsPermission();
5568 if (!Build.isDebuggable()) {
5569 throw new IllegalStateException("Does not support in non-debuggable build");
5570 }
5571
5572 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5573 throw new IllegalArgumentException("It should not exceed "
5574 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5575 }
5576
5577 mHandler.sendMessage(
5578 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5579 }
5580
chiachangwange0192a72023-02-06 13:25:01 +00005581 @Override
5582 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5583 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005584
5585 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5586 throw new IllegalArgumentException("Argument should not exceed "
5587 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5588 }
5589
5590 mHandler.sendMessage(
5591 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5592 }
5593
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005594 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5595 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5596 " accept=" + accept + " always=" + always);
5597
5598 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5599 if (nai == null) {
5600 // Nothing to do.
5601 return;
5602 }
5603
Chalard Jean254bd162022-08-25 13:04:51 +09005604 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005605 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005606 return;
5607 }
5608
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005609 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005610 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005611 }
5612
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005613 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5614 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005615 // If network becomes partial connectivity and user already accepted to use this
5616 // network, we should respect the user's option and don't need to popup the
5617 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005618 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005619 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005620 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005621 }
5622
5623 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005624 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005625 }
5626
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005627 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005628 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005629 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005630 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005631 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005632 }
5633
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005634 }
5635
lucaslin2240ef62019-03-12 13:08:03 +08005636 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5637 boolean always) {
5638 if (DBG) {
5639 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5640 + " always=" + always);
5641 }
5642
5643 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5644 if (nai == null) {
5645 // Nothing to do.
5646 return;
5647 }
5648
Chalard Jean254bd162022-08-25 13:04:51 +09005649 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005650 // The network validated while the dialog box was up. Take no action.
5651 return;
5652 }
5653
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005654 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5655 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005656 }
5657
5658 // TODO: Use the current design or save the user choice into IpMemoryStore.
5659 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005660 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005661 }
5662
5663 if (!accept) {
5664 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005665 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005666 // Tear down the network.
5667 teardownUnneededNetwork(nai);
5668 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005669 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5670 // result in a partial connectivity result which will be processed by
5671 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005672 //
5673 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5674 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005675 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005676 }
5677 }
5678
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005679 private void handleSetAvoidUnvalidated(Network network) {
5680 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005681 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005682 // Nothing to do. The network either disconnected or revalidated.
5683 return;
5684 }
Chalard Jean254bd162022-08-25 13:04:51 +09005685 if (0L == nai.getAvoidUnvalidated()) {
5686 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005687 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005688 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005689 }
5690 }
5691
Chalard Jean5fb43c72022-09-08 19:03:14 +09005692 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005693 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005694 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005695 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005696 }
5697
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005698 @Override
5699 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005700 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005701 mHandler.post(() -> {
5702 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5703 if (nai == null) return;
5704 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005705 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005706 });
5707 }
5708
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005709 /**
5710 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5711 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005712 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005713 * @param appExtras Bundle to use as intent extras for the captive portal application.
5714 * Must be treated as opaque to avoid preventing the captive portal app to
5715 * update its arguments.
5716 */
5717 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005718 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005719 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5720 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005721
5722 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5723 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005724 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5725 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005726 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5727
lucaslin75ff7022020-12-17 04:14:35 +08005728 final long token = Binder.clearCallingIdentity();
5729 try {
5730 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5731 } finally {
5732 Binder.restoreCallingIdentity(token);
5733 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005734 }
5735
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005736 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5737 private final Network mNetwork;
5738
5739 private CaptivePortalImpl(Network network) {
5740 mNetwork = network;
5741 }
5742
5743 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005744 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005745 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5746 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005747 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5748 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5749 // Since the network will be disconnected, skip notifying NetworkMonitor
5750 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005751 }
5752
Chiachang Wang938bfba2020-01-09 13:50:55 +08005753 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005754 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005755 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005756 }
5757
5758 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005759 public void appRequest(final int request) {
5760 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5761 if (nm == null) return;
5762
5763 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005764 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005765 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005766 }
5767 }
5768
5769 @Nullable
5770 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5771 // getNetworkAgentInfoForNetwork is thread-safe
5772 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5773 if (nai == null) return null;
5774
5775 // nai.networkMonitor() is thread-safe
5776 return nai.networkMonitor();
5777 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005778 }
5779
Hugo Benichic9048bc2016-09-14 23:23:08 +00005780 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005781 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005782 }
5783
Chalard Jean020b93a2022-09-01 13:20:14 +09005784 private boolean activelyPreferBadWifi() {
5785 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5786 }
5787
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005788 /**
5789 * Return whether the device should maintain continuous, working connectivity by switching away
5790 * from WiFi networks having no connectivity.
5791 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5792 */
5793 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005794 if (!checkNetworkStackPermission()) {
5795 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5796 }
5797 return avoidBadWifi();
5798 }
5799
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005800 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005801 ensureRunningOnConnectivityServiceThread();
5802 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005803 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005804 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005805 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005806 if (avoidBadWifi) {
5807 // If the device is now avoiding bad wifi, remove notifications that might have
5808 // been put up when the device didn't.
5809 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5810 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005811 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005812 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5813 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5814 for (final NetworkOfferInfo noi : offersToUpdate) {
5815 updateOfferScore(noi.offer);
5816 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005817 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005818 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005819 }
5820
Erik Kline95ecfee2016-10-02 18:02:14 +09005821 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005822 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005823 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005824 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005825 if (!configRestrict) {
5826 pw.println("Bad Wi-Fi avoidance: unrestricted");
5827 return;
5828 }
5829
5830 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5831 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005832 pw.println("Config restrict: " + configRestrict);
5833 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005834
Chalard Jeane0fdea32022-09-14 21:44:22 +09005835 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005836 String description;
5837 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005838 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005839 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005840 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005841 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005842 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005843 description = "avoid";
5844 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005845 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005846 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005847 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005848
5849 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5850 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005851 if (null == configValue) {
5852 description = "unset";
5853 } else if (configValue) {
5854 description = "force true";
5855 } else {
5856 description = "force false";
5857 }
5858 pw.println("Actively prefer bad wifi conf: " + description);
5859 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005860 pw.println("Network overrides:");
5861 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005862 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005863 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005864 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005865 }
5866 }
5867 pw.decreaseIndent();
5868 pw.decreaseIndent();
5869 }
5870
paulhu7746e4e2020-06-09 19:07:03 +08005871 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5872 // unify the method.
5873 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5874 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5875 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5876 return settingsComponent != null
5877 ? settingsComponent.getPackageName() : "com.android.settings";
5878 }
5879
lucaslinb1e8e382019-01-24 15:55:30 +08005880 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005881 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005882 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005883 switch (type) {
5884 case NO_INTERNET:
5885 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005886 // High priority because it is only displayed for explicitly selected networks.
5887 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005888 break;
lucasline117e2e2019-10-22 18:27:33 +08005889 case PRIVATE_DNS_BROKEN:
5890 action = Settings.ACTION_WIRELESS_SETTINGS;
5891 // High priority because we should let user know why there is no internet.
5892 highPriority = true;
5893 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005894 case LOST_INTERNET:
5895 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005896 // High priority because it could help the user avoid unexpected data usage.
5897 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005898 break;
lucaslin2240ef62019-03-12 13:08:03 +08005899 case PARTIAL_CONNECTIVITY:
5900 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005901 // Don't bother the user with a high-priority notification if the network was not
5902 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005903 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005904 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005905 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005906 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005907 return;
5908 }
5909
5910 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005911 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005912 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005913 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005914 // Some OEMs have their own Settings package. Thus, need to get the current using
5915 // Settings package name instead of just use default name "com.android.settings".
5916 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5917 intent.setClassName(settingsPkgName,
5918 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005919 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005920
paulhu2af50222020-10-11 22:52:27 +08005921 PendingIntent pendingIntent = PendingIntent.getActivity(
5922 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005923 0 /* requestCode */,
5924 intent,
paulhu2af50222020-10-11 22:52:27 +08005925 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005926
Serik Beketayevec8ad212020-12-07 22:43:07 -08005927 mNotifier.showNotification(
5928 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005929 }
5930
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005931 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5932 // Don't prompt if the network is validated, and don't prompt on captive portals
5933 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005934 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005935 return false;
5936 }
5937
5938 // If a network has partial connectivity, always prompt unless the user has already accepted
5939 // partial connectivity and selected don't ask again. This ensures that if the device
5940 // automatically connects to a network that has partial Internet access, the user will
5941 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005942 // because we have prompted them.
5943 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005944 return true;
5945 }
5946
5947 // If a network has no Internet access, only prompt if the network was explicitly selected
5948 // and if the user has not already told us to use the network regardless of whether it
5949 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005950 if (nai.networkAgentConfig.explicitlySelected
5951 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005952 return true;
5953 }
5954
5955 return false;
5956 }
5957
Chalard Jean5fb43c72022-09-08 19:03:14 +09005958 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5959 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005960
Chalard Jean5fb43c72022-09-08 19:03:14 +09005961 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5962 if (null == nai) return;
5963
5964 if (nai.setEvaluated()) {
5965 // If setEvaluated() returned true, the network never had any form of connectivity.
5966 // This may have an impact on request matching if bad WiFi avoidance is off and the
5967 // network was found not to have Internet access.
5968 nai.updateScoreForNetworkAgentUpdate();
5969 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005970
5971 // Also, if this is WiFi and it should be preferred actively, now is the time to
5972 // prompt the user that they walked past and connected to a bad WiFi.
5973 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5974 && !avoidBadWifi()
5975 && activelyPreferBadWifi()) {
5976 // The notification will be removed if the network validates or disconnects.
5977 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5978 return;
5979 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005980 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005981
Chalard Jean5fb43c72022-09-08 19:03:14 +09005982 if (!shouldPromptUnvalidated(nai)) return;
5983
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005984 // Stop automatically reconnecting to this network in the future. Automatically connecting
5985 // to a network that provides no or limited connectivity is not useful, because the user
5986 // cannot use that network except through the notification shown by this method, and the
5987 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005988 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005989
Chalard Jean254bd162022-08-25 13:04:51 +09005990 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005991 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005992 } else {
5993 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5994 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005995 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005996
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005997 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5998 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005999 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07006000
lucaslin2240ef62019-03-12 13:08:03 +08006001 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6002 return;
6003 }
6004
6005 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08006006 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006007 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006008 }
6009
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006010 @Override
6011 public int getMultipathPreference(Network network) {
6012 enforceAccessPermission();
6013
6014 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06006015 if (nai != null && nai.networkCapabilities
6016 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006017 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
6018 }
6019
Aaron Huang9a57acf2020-12-08 10:03:29 +08006020 final NetworkPolicyManager netPolicyManager =
6021 mContext.getSystemService(NetworkPolicyManager.class);
6022
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09006023 final long token = Binder.clearCallingIdentity();
6024 final int networkPreference;
6025 try {
6026 networkPreference = netPolicyManager.getMultipathPreference(network);
6027 } finally {
6028 Binder.restoreCallingIdentity(token);
6029 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08006030 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09006031 return networkPreference;
6032 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006033 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
6034 }
6035
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006036 @Override
6037 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09006038 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006039 }
6040
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006041 private class InternalHandler extends Handler {
6042 public InternalHandler(Looper looper) {
6043 super(looper);
6044 }
6045
6046 @Override
6047 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006048 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07006049 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006050 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006051 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07006052 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006053 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006054 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09006055 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07006056 break;
6057 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08006058 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08006059 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08006060 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04006061 break;
6062 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006063 case EVENT_REGISTER_NETWORK_PROVIDER: {
6064 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006065 break;
6066 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006067 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
6068 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006069 break;
6070 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006071 case EVENT_REGISTER_NETWORK_OFFER: {
6072 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
6073 break;
6074 }
6075 case EVENT_UNREGISTER_NETWORK_OFFER: {
6076 final NetworkOfferInfo offer =
6077 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6078 if (null != offer) {
6079 handleUnregisterNetworkOffer(offer);
6080 }
6081 break;
6082 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006083 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006084 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6085 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6086 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006087 break;
6088 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006089 case EVENT_REGISTER_NETWORK_REQUEST:
6090 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006091 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006092 break;
6093 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006094 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6095 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006096 handleRegisterNetworkRequestWithIntent(msg);
6097 break;
6098 }
Erik Kline155a59a2015-11-25 12:49:38 +09006099 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6100 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6101 handleTimedOutNetworkRequest(nri);
6102 break;
6103 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006104 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6105 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6106 break;
6107 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006108 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006109 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6110 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006111 break;
6112 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006113 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006114 Network network = (Network) msg.obj;
6115 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006116 break;
6117 }
lucaslin2240ef62019-03-12 13:08:03 +08006118 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6119 Network network = (Network) msg.obj;
6120 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6121 toBool(msg.arg2));
6122 break;
6123 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006124 case EVENT_SET_AVOID_UNVALIDATED: {
6125 handleSetAvoidUnvalidated((Network) msg.obj);
6126 break;
6127 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006128 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6129 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006130 break;
6131 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006132 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6133 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006134 break;
6135 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006136 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6137 // handler thread.
6138 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006139 mKeepaliveTracker.handleStartKeepalive(msg);
6140 break;
6141 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006142 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006143 final AutomaticOnOffKeepalive ki =
6144 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6145 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006146
chiachangwang676c84e2023-02-14 09:22:05 +00006147 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006148 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006149 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006150 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006151 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6152 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006153 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6154 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006155 }
6156 }
6157
6158 // If the network no longer exists, then the keepalive should have been
6159 // cleaned up already. There is no point trying to resume keepalives.
6160 if (!networkFound) return;
6161
chiachangwang676c84e2023-02-14 09:22:05 +00006162 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006163 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang676c84e2023-02-14 09:22:05 +00006164 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006165 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006166 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006167 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006168 }
6169 break;
6170 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006171 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006172 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006173 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6174 (IBinder) msg.obj);
6175 if (ki == null) {
6176 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006177 return;
6178 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006179 final int reason = msg.arg2;
6180 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006181 break;
6182 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006183 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6184 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6185 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006186 break;
6187 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006188 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6189 handlePrivateDnsSettingsChanged();
6190 break;
dalyk1720e542018-03-05 12:42:22 -05006191 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6192 handlePrivateDnsValidationUpdate(
6193 (PrivateDnsValidationUpdate) msg.obj);
6194 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006195 case EVENT_UID_BLOCKED_REASON_CHANGED:
6196 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006197 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006198 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6199 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6200 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006201 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006202 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6203 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006204 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006205 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006206 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006207 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006208 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6209 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006210 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006211 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006212 }
lucaslin1193a5d2021-01-21 02:04:15 +08006213 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006214 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006215 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006216 break;
paulhu51f77dc2021-06-07 02:34:20 +00006217 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6218 handleMobileDataPreferredUidsChanged();
6219 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006220 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6221 final long timeMs = ((Long) msg.obj).longValue();
6222 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6223 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006224 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6225 handleIngressRateLimitChanged();
6226 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006227 case EVENT_USER_DOES_NOT_WANT:
6228 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6229 if (nai == null) break;
6230 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006231 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006232 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006233 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6234 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6235 break;
chiachangwange0192a72023-02-06 13:25:01 +00006236 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6237 final long time = ((Long) msg.obj).longValue();
6238 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6239 break;
6240 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006241 case EVENT_UID_FROZEN_STATE_CHANGED:
6242 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6243 handleFrozenUids(args.mUids, args.mFrozenStates);
6244 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006245 }
6246 }
6247 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006248
Lorenzo Colittid6459092016-07-04 12:55:44 +09006249 @Override
markchien5776f962019-12-16 20:15:20 +08006250 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006251 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006252 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006253 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6254 Context.TETHERING_SERVICE);
6255 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006256 }
6257
Lorenzo Colittid6459092016-07-04 12:55:44 +09006258 @Override
markchien5776f962019-12-16 20:15:20 +08006259 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006260 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006261 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006262 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6263 Context.TETHERING_SERVICE);
6264 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006265 }
6266
Lorenzo Colittid6459092016-07-04 12:55:44 +09006267 @Override
markchien5776f962019-12-16 20:15:20 +08006268 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006269 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006270 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006271 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6272 Context.TETHERING_SERVICE);
6273 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006274 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006275
markchien5776f962019-12-16 20:15:20 +08006276
Lorenzo Colittid6459092016-07-04 12:55:44 +09006277 @Override
markchien5776f962019-12-16 20:15:20 +08006278 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006279 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006280 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006281 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6282 Context.TETHERING_SERVICE);
6283
6284 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006285 }
6286
Lorenzo Colittid6459092016-07-04 12:55:44 +09006287 @Override
markchien5776f962019-12-16 20:15:20 +08006288 @Deprecated
6289 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006290 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006291 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6292 Context.TETHERING_SERVICE);
6293
6294 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006295 }
6296
Udam Saini8f7d6a72017-06-07 12:06:28 -07006297 @Override
markchien5776f962019-12-16 20:15:20 +08006298 @Deprecated
6299 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006300 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006301 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6302 Context.TETHERING_SERVICE);
6303 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006304 }
6305
Robert Greenwalte0b00512014-07-02 09:59:16 -07006306 // Called when we lose the default network and have no replacement yet.
6307 // This will automatically be cleared after X seconds or a new default network
6308 // becomes CONNECTED, whichever happens first. The timer is started by the
6309 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006310 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006311 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006312 if (mNetTransitionWakeLock.isHeld()) {
6313 return;
6314 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006315 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006316 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6317 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006318 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006319 mWakelockLogs.log("ACQUIRE for " + forWhom);
6320 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006321 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006322 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006323 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006324 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006325
Hugo Benichi471b62a2017-03-30 23:18:10 +09006326 // Called when we gain a new default network to release the network transition wakelock in a
6327 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6328 // message is cancelled.
6329 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006330 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006331 if (!mNetTransitionWakeLock.isHeld()) {
6332 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006333 }
6334 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006335 // Cancel self timeout on wakelock hold.
6336 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6337 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6338 mHandler.sendMessageDelayed(msg, 1000);
6339 }
6340
6341 // Called when either message of ensureNetworkTransitionWakelock or
6342 // scheduleReleaseNetworkTransitionWakelock is processed.
6343 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6344 String event = eventName(eventId);
6345 synchronized (this) {
6346 if (!mNetTransitionWakeLock.isHeld()) {
6347 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006348 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006349 return;
6350 }
6351 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006352 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6353 mTotalWakelockDurationMs += lockDuration;
6354 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6355 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006356 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006357 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006358 }
6359
Robert Greenwalt986c7412010-09-08 15:24:47 -07006360 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006361 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006362 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006363 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006364 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006365 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006366 }
6367
Lorenzo Colittid6459092016-07-04 12:55:44 +09006368 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006369 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006370 enforceAccessPermission();
6371 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006372 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006373 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006374
6375 final NetworkAgentInfo nai;
6376 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006377 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006378 } else {
6379 nai = getNetworkAgentInfoForNetwork(network);
6380 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006381
6382 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006383 mHandler.obtainMessage(
6384 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006385 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006386
Hugo Benichid6b510a2017-04-06 17:22:18 +09006387 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006388 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006389 if (nai == null
6390 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006391 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006392 return;
6393 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006394 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006395 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006396 mConnectivityDiagnosticsHandler.sendMessage(
6397 mConnectivityDiagnosticsHandler.obtainMessage(
6398 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6399 new ReportedNetworkConnectivityInfo(
6400 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006401 return;
6402 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006403 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006404 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006405 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006406 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006407 // Validating a network that has not yet connected could result in a call to
6408 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006409 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006410 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006411 }
paulhu7aeba372020-12-30 00:42:19 +08006412 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6413 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006414 return;
6415 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006416
6417 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6418 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6419 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6420 // completed.
6421 mConnectivityDiagnosticsHandler.sendMessage(
6422 mConnectivityDiagnosticsHandler.obtainMessage(
6423 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6424 new ReportedNetworkConnectivityInfo(
6425 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006426 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006427 }
6428
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006429 // TODO: call into netd.
6430 private boolean queryUserAccess(int uid, Network network) {
6431 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6432 if (nai == null) return false;
6433
6434 // Any UID can use its default network.
6435 if (nai == getDefaultNetworkForUid(uid)) return true;
6436
6437 // Privileged apps can use any network.
6438 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6439 return true;
6440 }
6441
6442 // An unprivileged UID can use a VPN iff the VPN applies to it.
6443 if (nai.isVPN()) {
6444 return nai.networkCapabilities.appliesToUid(uid);
6445 }
6446
6447 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6448 // sockets, i.e., if it is the owner.
6449 final NetworkAgentInfo vpn = getVpnForUid(uid);
6450 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6451 && uid != vpn.networkCapabilities.getOwnerUid()) {
6452 return false;
6453 }
6454
6455 // The UID's permission must be at least sufficient for the network. Since the restricted
6456 // permission was already checked above, that just leaves background networks.
6457 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6458 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6459 }
6460
6461 // Unrestricted network. Anyone gets to use it.
6462 return true;
6463 }
6464
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006465 /**
6466 * Returns information about the proxy a certain network is using. If given a null network, it
6467 * it will return the proxy for the bound network for the caller app or the default proxy if
6468 * none.
6469 *
6470 * @param network the network we want to get the proxy information for.
6471 * @return Proxy information if a network has a proxy configured, or otherwise null.
6472 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006473 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006474 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006475 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006476 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006477 if (network == null) {
6478 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006479 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006480 true);
6481 if (activeNetwork == null) {
6482 return null;
6483 }
6484 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006485 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006486 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6487 // caller may not have.
6488 return getLinkPropertiesProxyInfo(network);
6489 }
6490 // No proxy info available if the calling UID does not have network access.
6491 return null;
6492 }
6493
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006494
6495 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006496 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6497 if (nai == null) return null;
6498 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006499 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6500 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006501 }
6502 }
6503
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006504 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006505 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006506 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006507 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006508 }
6509
Chalard Jean777e2e52018-06-07 18:02:37 +09006510 @Override
6511 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006512 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006513 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006514 }
6515
Aaron Huang9fe47be2021-06-08 13:11:45 +08006516 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006517 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006518 final NetworkAgentInfo nai = getDefaultNetwork();
6519 // TODO : this method should check that net == nai.network, unfortunately at this point
6520 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6521 // is only ever installed on the default network so in practice this is okay.
6522 if (null == nai) return;
6523 // PAC proxies only work on the default network. Therefore, only the default network
6524 // should have its link properties fixed up for PAC proxies.
6525 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6526 if (nai.everConnected()) {
6527 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6528 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006529 }
6530
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006531 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6532 // when any network changes proxy.
6533 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6534 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006535 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6536 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006537 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6538
Chalard Jean7d97afc2018-06-07 17:41:29 +09006539 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006540 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006541 }
6542 }
6543
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006544 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006545 final private HashMap<Uri, Integer> mUriEventMap;
6546 final private Context mContext;
6547 final private Handler mHandler;
6548
6549 SettingsObserver(Context context, Handler handler) {
6550 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006551 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006552 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006553 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006554 }
6555
Erik Kline05f2b402015-04-30 12:58:40 +09006556 void observe(Uri uri, int what) {
6557 mUriEventMap.put(uri, what);
6558 final ContentResolver resolver = mContext.getContentResolver();
6559 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006560 }
6561
6562 @Override
6563 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006564 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006565 }
6566
6567 @Override
6568 public void onChange(boolean selfChange, Uri uri) {
6569 final Integer what = mUriEventMap.get(uri);
6570 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006571 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006572 } else {
6573 loge("No matching event to send for URI=" + uri);
6574 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006575 }
6576 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006577
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006578 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006579 Log.d(TAG, s);
6580 }
6581
6582 private static void logw(String s) {
6583 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006584 }
6585
Daniel Brightf9e945b2020-06-15 16:10:01 -07006586 private static void logwtf(String s) {
6587 Log.wtf(TAG, s);
6588 }
6589
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006590 private static void logwtf(String s, Throwable t) {
6591 Log.wtf(TAG, s, t);
6592 }
6593
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006594 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006595 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006596 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006597
Hugo Benichi39621362017-02-11 17:04:43 +09006598 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006599 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006600 }
6601
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006602 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006603 * Return the information of all ongoing VPNs.
6604 *
6605 * <p>This method is used to update NetworkStatsService.
6606 *
6607 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006608 */
junyulai2050bed2021-01-23 09:46:34 +08006609 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006610 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006611 if (mLockdownEnabled) {
6612 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006613 }
junyulai2050bed2021-01-23 09:46:34 +08006614 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006615 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006616 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006617 if (info != null) {
6618 infoList.add(info);
6619 }
6620 }
junyulai2050bed2021-01-23 09:46:34 +08006621 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006622 }
6623
6624 /**
6625 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006626 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006627 */
junyulai2050bed2021-01-23 09:46:34 +08006628 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006629 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006630 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6631 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006632 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6633 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6634 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006635 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6636 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006637 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006638 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006639 }
6640 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006641
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006642 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006643
6644 List<String> interfaces = new ArrayList<>();
6645 for (Network network : underlyingNetworks) {
6646 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6647 if (underlyingNai == null) continue;
6648 LinkProperties lp = underlyingNai.linkProperties;
6649 for (String iface : lp.getAllInterfaceNames()) {
6650 if (!TextUtils.isEmpty(iface)) {
6651 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006652 }
6653 }
Benedict Wong34857f82019-06-12 17:46:15 +00006654 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006655
6656 if (interfaces.isEmpty()) return null;
6657
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006658 // Must be non-null or NetworkStatsService will crash.
6659 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6660 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006661 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006662 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006663
junyulai2050bed2021-01-23 09:46:34 +08006664 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6665 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006666 }
6667
James Mattisd31bdfa2020-12-23 16:37:26 -08006668 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006669 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6670 Network[] underlyingNetworks) {
6671 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006672 if (underlyingNetworks == null && defaultNetwork != null) {
6673 // null underlying networks means to track the default.
6674 underlyingNetworks = new Network[] { defaultNetwork };
6675 }
6676 return underlyingNetworks;
6677 }
6678
6679 // Returns true iff |network| is an underlying network of |nai|.
6680 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6681 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6682 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006683 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006684 final Network[] underlying = underlyingNetworksOrDefault(
6685 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006686 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006687 }
6688
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006689 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006690 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006691 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006692 * When underlying networks change, such networks may have to update capabilities to reflect
6693 * things like the metered bit, their transports, and so on. The capabilities are calculated
6694 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006695 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006696 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006697 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006698 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006699 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006700 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006701 }
6702 }
6703 }
6704
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006705 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6706 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6707 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6708 // a VPN is not up.
6709 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6710 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6711 for (UidRange range : blockedUidRanges) {
6712 if (range.contains(uid)) return true;
6713 }
6714 return false;
6715 }
6716
6717 @Override
6718 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006719 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006720 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6721 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6722 }
6723
6724 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6725 if (DBG) {
6726 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6727 + Arrays.toString(ranges));
6728 }
6729 // Cannot use a Set since the list of UID ranges might contain duplicates.
6730 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6731 for (int i = 0; i < ranges.length; i++) {
6732 if (requireVpn) {
6733 newVpnBlockedUidRanges.add(ranges[i]);
6734 } else {
6735 newVpnBlockedUidRanges.remove(ranges[i]);
6736 }
6737 }
6738
6739 try {
6740 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6741 } catch (RemoteException | ServiceSpecificException e) {
6742 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6743 + Arrays.toString(ranges) + "): netd command failed: " + e);
6744 }
6745
Chalard Jeandf29a852023-05-29 17:02:43 +09006746 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006747 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6748 }
6749
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006750 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6751 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006752 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6753 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006754 }
6755
6756 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6757 }
6758
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006759 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006760 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006761 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006762 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006763 }
6764
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006765 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6766 return mLockdownEnabled
6767 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6768 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006769 }
6770
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006771 private NetworkAgentInfo getLegacyLockdownNai() {
6772 if (!mLockdownEnabled) {
6773 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006774 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006775 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006776 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6777 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006778
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006779 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006780 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6781 // a local variable. There is no need to make a copy because its contents cannot change.
6782 final Network[] underlying = nai.declaredUnderlyingNetworks;
6783 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006784 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006785 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006786
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006787 // The legacy lockdown VPN always uses the default network.
6788 // If the VPN's underlying network is no longer the current default network, it means that
6789 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006790 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6791 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006792 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006793 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006794 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006795 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006796
6797 return nai;
6798 };
6799
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006800 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6801 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6802 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006803 private DetailedState getLegacyLockdownState(DetailedState origState) {
6804 if (origState != DetailedState.CONNECTED) {
6805 return origState;
6806 }
6807 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6808 ? DetailedState.CONNECTING
6809 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006810 }
6811
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006812 private void filterForLegacyLockdown(NetworkInfo ni) {
6813 if (!mLockdownEnabled || !ni.isConnected()) return;
6814 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6815 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6816 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6817 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6818 // network, this time with a state of CONNECTED.
6819 //
6820 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6821 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6822 // is not too far off the truth, since an always-on VPN, when not connected, is always
6823 // trying to reconnect.
6824 if (getLegacyLockdownNai() == null) {
6825 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6826 }
6827 }
6828
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006829 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006830 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006831 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006832 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006833 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6834 return;
6835 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006836 final long ident = Binder.clearCallingIdentity();
6837 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006838 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006839 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006840 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006841 } finally {
6842 Binder.restoreCallingIdentity(ident);
6843 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006844 }
Wink Savillecb117d32013-08-29 14:57:08 -07006845
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006846 @Override
6847 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006848 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006849 final long ident = Binder.clearCallingIdentity();
6850 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006851 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006852 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006853 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6854 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006855 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006856 } finally {
6857 Binder.restoreCallingIdentity(ident);
6858 }
6859 }
6860
James Mattis02220e22021-03-13 19:27:21 -08006861 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006862 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6863 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6864 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006865 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006866 }
6867
James Mattis02220e22021-03-13 19:27:21 -08006868 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006869 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006870 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006871 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6872 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006873 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006874 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6875 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6876 }
junyulaid91e7052020-08-28 13:44:33 +08006877 }
6878
James Mattis02220e22021-03-13 19:27:21 -08006879 private void onPackageChanged(@NonNull final String packageName) {
6880 // This is necessary in case a package is added or removed, but also when it's replaced to
6881 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6882 // as one in the preferences, then it should follow the same routing as that other package,
6883 // which means updating the rules is never to be needed in this case (whether it joins or
6884 // leaves a UID with a preference).
6885 if (isMappedInOemNetworkPreference(packageName)) {
6886 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6887 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006888
6889 // Invalidates cache entry when the package is updated.
6890 synchronized (mSelfCertifiedCapabilityCache) {
6891 mSelfCertifiedCapabilityCache.remove(packageName);
6892 }
James Mattis02220e22021-03-13 19:27:21 -08006893 }
6894
6895 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006896 @Override
6897 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006898 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006899 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006900 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006901
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006902 // User should be filled for below intents, check the existence.
6903 if (user == null) {
6904 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6905 return;
6906 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006907
Lorenzo Colitticd675292021-02-04 17:32:07 +09006908 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006909 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006910 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006911 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006912 } else {
junyulaid91e7052020-08-28 13:44:33 +08006913 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006914 }
6915 }
6916 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006917
James Mattis02220e22021-03-13 19:27:21 -08006918 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6919 @Override
6920 public void onReceive(Context context, Intent intent) {
6921 ensureRunningOnConnectivityServiceThread();
6922 switch (intent.getAction()) {
6923 case Intent.ACTION_PACKAGE_ADDED:
6924 case Intent.ACTION_PACKAGE_REMOVED:
6925 case Intent.ACTION_PACKAGE_REPLACED:
6926 onPackageChanged(intent.getData().getSchemeSpecificPart());
6927 break;
6928 default:
6929 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6930 }
6931 }
6932 };
6933
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006934 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006935 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006936
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006937 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006938 public final String name;
6939 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006940 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006941 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006942
lifraf3a3492021-03-10 13:58:14 +08006943 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6944 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006945 this.name = name;
6946 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006947 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006948 mDeathRecipient = deathRecipient;
6949
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006950 if (mDeathRecipient == null) {
6951 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006952 }
6953 }
6954
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006955 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006956 try {
6957 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6958 } catch (RemoteException e) {
6959 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006960 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006961 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006962 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006963
James Mattis4fce5d12020-11-12 15:53:42 -08006964 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6965 for (int i = 0; i < requests.size(); i++) {
6966 ensureNetworkRequestHasType(requests.get(i));
6967 }
6968 }
6969
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006970 private void ensureNetworkRequestHasType(NetworkRequest request) {
6971 if (request.type == NetworkRequest.Type.NONE) {
6972 throw new IllegalArgumentException(
6973 "All NetworkRequests in ConnectivityService must have a type");
6974 }
6975 }
6976
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006977 /**
6978 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006979 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006980 */
James Mattis258ea3c2020-11-15 15:04:40 -08006981 @VisibleForTesting
6982 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006983 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6984 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006985 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006986
James Mattisa076c532020-12-02 14:12:41 -08006987 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6988 void setSatisfier(
6989 @Nullable final NetworkAgentInfo satisfier,
6990 @Nullable final NetworkRequest activeRequest) {
6991 mSatisfier = satisfier;
6992 mActiveRequest = activeRequest;
6993 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006994
James Mattisd31bdfa2020-12-23 16:37:26 -08006995 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006996 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006997 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006998 private NetworkAgentInfo mSatisfier;
6999 NetworkAgentInfo getSatisfier() {
7000 return mSatisfier;
7001 }
7002
7003 // The request in mRequests assigned to a network agent. This is null if none of the
7004 // requests in mRequests can be satisfied. This member has the constraint of only being
7005 // accessible on the handler thread.
7006 @Nullable
7007 private NetworkRequest mActiveRequest;
7008 NetworkRequest getActiveRequest() {
7009 return mActiveRequest;
7010 }
7011
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007012 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007013 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08007014 @Nullable
7015 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007016
7017 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08007018 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007019 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007020 final int mPid;
7021 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08007022 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007023 @Nullable
7024 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007025
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007026 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08007027 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007028
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007029 // Effective UID of this request. This is different from mUid when a privileged process
7030 // files a request on behalf of another UID. This UID is used to determine blocked status,
7031 // UID matching, and so on. mUid above is used for permission checks and to enforce the
7032 // maximum limit of registered callbacks per UID.
7033 final int mAsUid;
7034
paulhu48291862021-07-14 14:53:57 +08007035 // Preference order of this request.
7036 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08007037
James Mattis3ce3d3c2021-02-09 18:18:28 -08007038 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
7039 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
7040 // maintained for keying off of. This is only a concern when the original nri
7041 // mNetworkRequests changes which happens currently for apps that register callbacks to
7042 // track the default network. In those cases, the nri is updated to have mNetworkRequests
7043 // that match the per-app default nri that currently tracks the calling app's uid so that
7044 // callbacks are fired at the appropriate time. When the callbacks fire,
7045 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
7046 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
7047 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7048 @NonNull
7049 private final NetworkRequest mNetworkRequestForCallback;
7050 NetworkRequest getNetworkRequestForCallback() {
7051 return mNetworkRequestForCallback;
7052 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007053
James Mattisd31bdfa2020-12-23 16:37:26 -08007054 /**
7055 * Get the list of UIDs this nri applies to.
7056 */
7057 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00007058 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08007059 // networkCapabilities.getUids() returns a defensive copy.
7060 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007061 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
7062 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08007063 }
7064
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007065 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
7066 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08007067 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08007068 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007069 }
7070
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007071 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007072 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007073 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007074 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007075 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007076 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007077 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007078 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007079 mBinder = null;
7080 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007081 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007082 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007083 mPerUidCounter = getRequestCounter(this);
7084 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007085 /**
7086 * Location sensitive data not included in pending intent. Only included in
7087 * {@link NetworkCallback}.
7088 */
7089 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007090 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007091 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007092 }
7093
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007094 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007095 @Nullable final IBinder binder,
7096 @NetworkCallback.Flag int callbackFlags,
7097 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007098 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7099 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007100 }
7101
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007102 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007103 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007104 @Nullable final IBinder binder,
7105 @NetworkCallback.Flag int callbackFlags,
7106 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007107 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007108 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007109 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007110 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007111 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007112 mBinder = binder;
7113 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007114 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007115 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007116 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007117 mPerUidCounter = getRequestCounter(this);
7118 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007119 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007120 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007121 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007122 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007123 }
7124
James Mattis3ce3d3c2021-02-09 18:18:28 -08007125 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7126 @NonNull final List<NetworkRequest> r) {
7127 super();
7128 ensureAllNetworkRequestsHaveType(r);
7129 mRequests = initializeRequests(r);
7130 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007131 final NetworkAgentInfo satisfier = nri.getSatisfier();
7132 if (null != satisfier) {
7133 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7134 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007135 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007136 // As this code creates a new NRI with a new set of requests, figure out which of
7137 // the list of requests should be the active request. It is always the first
7138 // request of the list that can be satisfied by the satisfier since the order of
7139 // requests is a priority order.
7140 // Note even in the presence of a satisfier there may not be an active request,
7141 // when the satisfier is the no-service network.
7142 NetworkRequest activeRequest = null;
7143 for (final NetworkRequest candidate : r) {
7144 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7145 activeRequest = candidate;
7146 break;
7147 }
7148 }
7149 setSatisfier(satisfier, activeRequest);
7150 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007151 mMessenger = nri.mMessenger;
7152 mBinder = nri.mBinder;
7153 mPid = nri.mPid;
7154 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007155 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007156 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007157 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007158 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007159 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007160 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007161 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007162 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007163 }
7164
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007165 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007166 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007167 }
7168
paulhue9913722021-05-26 15:19:20 +08007169 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007170 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007171 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007172 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007173 }
7174
James Mattis2516da32021-01-31 17:06:19 -08007175 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7176 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7177 // false.
7178 boolean isBeingSatisfied() {
7179 return (null != mSatisfier && null != mActiveRequest);
7180 }
7181
James Mattis3d229892020-11-16 16:46:28 -08007182 boolean isMultilayerRequest() {
7183 return mRequests.size() > 1;
7184 }
7185
James Mattis45d81842021-01-10 14:24:24 -08007186 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7187 // Creating a defensive copy to prevent the sender from modifying the list being
7188 // reflected in the return value of this method.
7189 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007190 return Collections.unmodifiableList(tempRequests);
7191 }
7192
James Mattisb1392002021-03-31 13:57:52 -07007193 void linkDeathRecipient() {
7194 if (null != mBinder) {
7195 try {
7196 mBinder.linkToDeath(this, 0);
7197 } catch (RemoteException e) {
7198 binderDied();
7199 }
7200 }
7201 }
7202
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007203 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007204 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007205 try {
7206 mBinder.unlinkToDeath(this, 0);
7207 } catch (NoSuchElementException e) {
7208 // Temporary workaround for b/194394697 pending analysis of additional logs
7209 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7210 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007211 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007212 }
7213
paulhu48291862021-07-14 14:53:57 +08007214 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7215 // Compare two preference orders.
7216 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007217 }
7218
paulhu48291862021-07-14 14:53:57 +08007219 int getPreferenceOrderForNetd() {
7220 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7221 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7222 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007223 }
paulhu48291862021-07-14 14:53:57 +08007224 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007225 }
7226
James Mattis4fce5d12020-11-12 15:53:42 -08007227 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007228 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007229 // As an immutable collection, mRequests cannot change by the time the
7230 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7231 // is acceptable. Use handleReleaseNetworkRequest and not directly
7232 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7233 // the app already unregistered the request.
7234 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7235 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007236 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007237
James Mattis4fce5d12020-11-12 15:53:42 -08007238 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007239 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007240 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7241 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007242 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007243 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007244 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007245 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007246 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007247 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007248 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007249 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007250 }
7251
Junyu Lai00d92df2022-07-05 11:01:52 +08007252 // Keep backward compatibility since the ServiceSpecificException is used by
7253 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7254 public static class RequestInfoPerUidCounter extends PerUidCounter {
7255 RequestInfoPerUidCounter(int maxCountPerUid) {
7256 super(maxCountPerUid);
7257 }
7258
7259 @Override
7260 public synchronized void incrementCountOrThrow(int uid) {
7261 try {
7262 super.incrementCountOrThrow(uid);
7263 } catch (IllegalStateException e) {
7264 throw new ServiceSpecificException(
7265 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7266 "Uid " + uid + " exceeded its allotted requests limit");
7267 }
7268 }
7269
7270 @Override
7271 public synchronized void decrementCountOrThrow(int uid) {
7272 throw new UnsupportedOperationException("Use decrementCount instead.");
7273 }
7274
7275 public synchronized void decrementCount(int uid) {
7276 try {
7277 super.decrementCountOrThrow(uid);
7278 } catch (IllegalStateException e) {
7279 logwtf("Exception when decrement per uid request count: ", e);
7280 }
7281 }
7282 }
7283
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007284 // This checks that the passed capabilities either do not request a
7285 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007286 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007287 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007288 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007289 throw new SecurityException("Insufficient permissions to request a specific SSID");
7290 }
paulhu1a407652019-03-22 16:35:06 +08007291
7292 if (nc.hasSignalStrength()
7293 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7294 throw new SecurityException(
7295 "Insufficient permissions to request a specific signal strength");
7296 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007297 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007298
junyulai2217bec2021-04-14 23:33:31 +08007299 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007300 enforceNetworkFactoryPermission();
7301 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007302 }
7303
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007304 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007305 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007306 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007307 // mNetworkRequests may contain the same value multiple times in case of
7308 // multilayer requests. It won't matter in this case because the thresholds
7309 // will then be the same and be deduplicated as they enter the `thresholds` set.
7310 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007311 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7312 for (final NetworkRequest req : nri.mRequests) {
7313 if (req.networkCapabilities.hasSignalStrength()
7314 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7315 thresholds.add(req.networkCapabilities.getSignalStrength());
7316 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007317 }
7318 }
7319 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007320 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007321 }
7322
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007323 private void updateSignalStrengthThresholds(
7324 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007325 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007326
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007327 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007328 String detail;
7329 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7330 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7331 } else {
7332 detail = reason;
7333 }
7334 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007335 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007336 }
7337
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007338 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007339 }
7340
Chalard Jeandd421992021-12-16 23:16:02 +09007341 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007342 if (nc == null) {
7343 return;
7344 }
7345 NetworkSpecifier ns = nc.getNetworkSpecifier();
7346 if (ns == null) {
7347 return;
7348 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007349 if (ns instanceof MatchAllNetworkSpecifier) {
7350 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7351 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007352 }
7353
Chalard Jeandd421992021-12-16 23:16:02 +09007354 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007355 ensureValidNetworkSpecifier(nc);
7356 if (nc.isPrivateDnsBroken()) {
7357 throw new IllegalArgumentException("Can't request broken private DNS");
7358 }
Chalard Jeande665262022-02-25 16:12:12 +09007359 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007360 throw new IllegalArgumentException("Can't request access UIDs");
7361 }
lucasline117e2e2019-10-22 18:27:33 +08007362 }
7363
Chalard Jeandd421992021-12-16 23:16:02 +09007364 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7365 ensureListenableCapabilities(nc);
7366 final String badCapability = nc.describeFirstNonRequestableCapability();
7367 if (badCapability != null) {
7368 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7369 }
7370 }
7371
Chiachang Wang3bc52762021-11-25 14:17:57 +08007372 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7373 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007374 private boolean isTargetSdkAtleast(int version, int callingUid,
7375 @NonNull String callingPackageName) {
7376 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007377 final PackageManager pm =
7378 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007379 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007380 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007381 if (callingVersion < version) return false;
7382 } catch (PackageManager.NameNotFoundException e) { }
7383 return true;
7384 }
7385
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007386 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007387 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007388 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007389 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007390 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007391 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007392 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7393 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007394 throw new SecurityException("Insufficient permissions to specify legacy type");
7395 }
markchienfac84a22020-03-18 21:16:15 +08007396 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007397 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007398 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007399 // Privileged callers can track the default network of another UID by passing in a UID.
7400 if (asUid != Process.INVALID_UID) {
7401 enforceSettingsPermission();
7402 } else {
7403 asUid = callingUid;
7404 }
junyulaiad010792021-01-11 16:53:38 +08007405 final NetworkRequest.Type reqType;
7406 try {
7407 reqType = NetworkRequest.Type.values()[reqTypeInt];
7408 } catch (ArrayIndexOutOfBoundsException e) {
7409 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7410 }
7411 switch (reqType) {
7412 case TRACK_DEFAULT:
7413 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007414 // is unused and will be replaced by ones appropriate for the UID (usually, the
7415 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007416 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007417 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007418 enforceAccessPermission();
7419 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007420 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007421 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007422 networkCapabilities = new NetworkCapabilities(defaultNc);
7423 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007424 case BACKGROUND_REQUEST:
7425 enforceNetworkStackOrSettingsPermission();
7426 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007427 case REQUEST:
7428 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7429 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007430 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007431 // TODO: this is incorrect. We mark the request as metered or not depending on
7432 // the state of the app when the request is filed, but we never change the
7433 // request if the app changes network state. http://b/29964605
7434 enforceMeteredApnPolicy(networkCapabilities);
7435 break;
junyulai1b1c8742021-03-12 20:05:08 +08007436 case LISTEN_FOR_BEST:
7437 enforceAccessPermission();
7438 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7439 break;
junyulaiad010792021-01-11 16:53:38 +08007440 default:
7441 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007442 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007443 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007444 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007445 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007446
junyulai1b1c8742021-03-12 20:05:08 +08007447 // Enforce FOREGROUND if the caller does not have permission to use background network.
7448 if (reqType == LISTEN_FOR_BEST) {
7449 restrictBackgroundRequestForCaller(networkCapabilities);
7450 }
7451
7452 // Set the UID range for this request to the single UID of the requester, unless the
7453 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007454 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7455 // are no visible methods to set the UIDs, an app could use reflection to try and get
7456 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007457 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007458 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7459 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007460
Etan Cohen85000162017-02-05 10:42:27 -08007461 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007462 throw new IllegalArgumentException("Bad timeout specified");
7463 }
Etan Cohen9786d922015-11-18 10:56:15 -08007464
James Mattis3ce3d3c2021-02-09 18:18:28 -08007465 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007466 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007467 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007468 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007469 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007470 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007471
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007472 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7473 // copied from the default request above. (This is necessary to ensure, for example, that
7474 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7475 // changes don't alter request matching.
7476 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7477 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007478 throw new IllegalStateException(
7479 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007480 + networkCapabilities + " vs. " + defaultNc);
7481 }
7482
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007483 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007484 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007485 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007486 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007487 }
7488 return networkRequest;
7489 }
7490
James Mattis3ce3d3c2021-02-09 18:18:28 -08007491 /**
7492 * Return the nri to be used when registering a network request. Specifically, this is used with
7493 * requests registered to track the default request. If there is currently a per-app default
7494 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7495 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007496 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7497 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007498 * @param nr the network request for the nri.
7499 * @param msgr the messenger for the nri.
7500 * @param binder the binder for the nri.
7501 * @param callingAttributionTag the calling attribution tag for the nri.
7502 * @return the nri to register.
7503 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007504 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007505 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007506 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007507 @Nullable String callingAttributionTag) {
7508 final List<NetworkRequest> requests;
7509 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7510 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007511 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007512 } else {
7513 requests = Collections.singletonList(nr);
7514 }
Roshan Pius951c0032020-12-22 15:10:42 -08007515 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007516 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007517 }
7518
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007519 private boolean shouldCheckCapabilitiesDeclaration(
7520 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7521 @NonNull final String callingPackageName) {
7522 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7523 // Only run the check if the change is enabled.
7524 if (!mDeps.isChangeEnabled(
7525 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7526 callingPackageName, user)) {
7527 return false;
7528 }
7529
7530 return networkCapabilities.hasCapability(
7531 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7532 || networkCapabilities.hasCapability(
7533 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7534 }
7535
7536 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
7537 @NonNull final NetworkCapabilities networkCapabilities) {
7538 // This check is added to fix the linter error for "current min is 30", which is not going
7539 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007540 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007541 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7542 return;
7543 }
7544 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007545 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007546 try {
7547 synchronized (mSelfCertifiedCapabilityCache) {
7548 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7549 callerPackageName);
7550 if (applicationNetworkCapabilities == null) {
7551 final PackageManager packageManager = mContext.getPackageManager();
7552 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7553 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7554 callerPackageName
7555 );
7556 final XmlResourceParser parser = packageManager
7557 .getResourcesForApplication(callerPackageName)
7558 .getXml(networkSliceProperty.getResourceId());
7559 applicationNetworkCapabilities =
7560 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7561 mSelfCertifiedCapabilityCache.put(callerPackageName,
7562 applicationNetworkCapabilities);
7563 }
7564
7565 }
7566 } catch (PackageManager.NameNotFoundException ne) {
7567 throw new SecurityException(
7568 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7569 + " property");
7570 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7571 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007572 } finally {
7573 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007574 }
7575
7576 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7577 networkCapabilities);
7578 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007579 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007580 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007581 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7582 callingPackageName)) {
7583 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7584 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007585 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007586 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7587 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7588 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7589 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007590 }
junyulai96bd9fe2022-03-08 17:36:42 +08007591 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007592 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007593 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007594 }
7595 }
7596
fenglu3f357402015-03-20 11:29:56 -07007597 @Override
fenglub00f4882015-04-21 17:12:05 -07007598 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007599 enforceAccessPermission();
7600 NetworkAgentInfo nai = null;
7601 if (network == null) {
7602 return false;
7603 }
7604 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007605 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007606 }
7607 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007608 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007609 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007610 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007611 Integer uidReqs = mBandwidthRequests.get(uid);
7612 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007613 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007614 }
7615 mBandwidthRequests.put(uid, ++uidReqs);
7616 }
fenglu3f357402015-03-20 11:29:56 -07007617 return true;
7618 }
7619 return false;
7620 }
7621
Felipe Leme0a5ae422016-06-20 16:36:29 -07007622 private boolean isSystem(int uid) {
7623 return uid < Process.FIRST_APPLICATION_UID;
7624 }
fenglu3f357402015-03-20 11:29:56 -07007625
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007626 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007627 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007628 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007629 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007630 return;
7631 }
Hugo Benichi39621362017-02-11 17:04:43 +09007632 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7633 // Policy already enforced.
7634 return;
7635 }
paulhuaf50d7d2020-12-24 19:47:34 +08007636 final long ident = Binder.clearCallingIdentity();
7637 try {
7638 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7639 // If UID is restricted, don't allow them to bring up metered APNs.
7640 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7641 }
7642 } finally {
7643 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007644 }
7645 }
7646
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007647 @Override
7648 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007649 PendingIntent operation, @NonNull String callingPackageName,
7650 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007651 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007652 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007653 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007654 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007655 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007656 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007657 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007658 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007659 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007660 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7661 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007662
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007663 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007664 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007665 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7666 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007667 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007668 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7669 nri));
7670 return networkRequest;
7671 }
7672
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007673 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7674 mHandler.sendMessageDelayed(
7675 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007676 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007677 }
7678
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007679 @Override
7680 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007681 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007682 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007683 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007684 }
7685
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007686 // In order to implement the compatibility measure for pre-M apps that call
7687 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7688 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7689 // This ensures it has permission to do so.
7690 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7691 if (nc == null) {
7692 return false;
7693 }
7694 int[] transportTypes = nc.getTransportTypes();
7695 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7696 return false;
7697 }
7698 try {
7699 mContext.enforceCallingOrSelfPermission(
7700 android.Manifest.permission.ACCESS_WIFI_STATE,
7701 "ConnectivityService");
7702 } catch (SecurityException e) {
7703 return false;
7704 }
7705 return true;
7706 }
7707
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007708 @Override
7709 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007710 Messenger messenger, IBinder binder,
7711 @NetworkCallback.Flag int callbackFlags,
7712 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007713 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007714 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7715 enforceAccessPermission();
7716 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007717
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007718 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007719 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007720 Binder.getCallingPid(), callingUid, callingPackageName);
7721 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007722 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7723 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7724 // onLost and onAvailable callbacks when networks move in and out of the background.
7725 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7726 // can't request networks.
7727 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007728 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007729
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007730 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007731 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007732 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007733 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007734 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007735 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007736
7737 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7738 return networkRequest;
7739 }
7740
7741 @Override
7742 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007743 PendingIntent operation, @NonNull String callingPackageName,
7744 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007745 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007746 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007747 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7748 enforceAccessPermission();
7749 }
Chalard Jeandd421992021-12-16 23:16:02 +09007750 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007751 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007752 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007753 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007754 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007755
7756 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007757 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007758 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7759 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007760 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007761
WeiZhang1cc3f172021-06-03 19:02:04 -05007762 mHandler.sendMessage(mHandler.obtainMessage(
7763 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007764 }
7765
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007766 /** Returns the next Network provider ID. */
7767 public final int nextNetworkProviderId() {
7768 return mNextNetworkProviderId.getAndIncrement();
7769 }
7770
Erik Kline0c04b742016-07-07 16:50:58 +09007771 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007772 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007773 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007774 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007775 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007776 }
7777
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007778 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7779 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007780 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7781 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7782 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007783 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007784 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007785 return;
7786 }
7787
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007788 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7789 mNetworkProviderInfos.put(npi.messenger, npi);
7790 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007791 }
7792
7793 @Override
7794 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007795 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007796 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007797 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007798 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007799 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7800 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007801 }
7802
7803 @Override
7804 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007805 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007806 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007807 }
7808
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007809 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007810 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007811 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7812 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007813 Objects.requireNonNull(score);
7814 Objects.requireNonNull(caps);
7815 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007816 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007817 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007818 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7819 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007820 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7821 }
7822
Chalard Jeanbb902a52021-08-18 01:35:19 +09007823 private void updateOfferScore(final NetworkOffer offer) {
7824 final boolean yieldToBadWiFi =
7825 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7826 final NetworkOffer newOffer = new NetworkOffer(
7827 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7828 offer.caps, offer.callback, offer.providerId);
7829 if (offer.equals(newOffer)) return;
7830 handleRegisterNetworkOffer(newOffer);
7831 }
7832
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007833 @Override
7834 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007835 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007836 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7837 }
7838
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007839 private void handleUnregisterNetworkProvider(Messenger messenger) {
7840 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7841 if (npi == null) {
7842 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007843 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007844 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007845 // Unregister all the offers from this provider
7846 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7847 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007848 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007849 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7850 toRemove.add(noi);
7851 }
7852 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007853 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007854 handleUnregisterNetworkOffer(noi);
7855 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007856 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007857 }
7858
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007859 @Override
James Mattisf7027322020-12-13 16:28:14 -08007860 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007861 if (request.hasTransport(TRANSPORT_TEST)) {
7862 enforceNetworkFactoryOrTestNetworksPermission();
7863 } else {
7864 enforceNetworkFactoryPermission();
7865 }
James Mattisf7027322020-12-13 16:28:14 -08007866 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7867 if (nri != null) {
7868 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7869 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7870 mHandler.post(() -> handleReleaseNetworkRequest(
7871 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7872 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007873 }
7874
Paul Jensen1f567382015-02-13 14:18:39 -05007875 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7876 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007877 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007878 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007879 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007880 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007881 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007882
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007883 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007884 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007885 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007886
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007887 // UID ranges for users that are currently blocked by VPNs.
7888 // This array is accessed and iterated on multiple threads without holding locks, so its
7889 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7890 // (on the handler thread).
7891 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7892
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007893 // Must only be accessed on the handler thread
7894 @NonNull
7895 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7896
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007897 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007898 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007899
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007900 // Current OEM network preferences. This object must only be written to on the handler thread.
7901 // Since it is immutable and always non-null, other threads may read it if they only care
7902 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007903 @NonNull
7904 private OemNetworkPreferences mOemNetworkPreferences =
7905 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007906 // Current per-profile network preferences. This object follows the same threading rules as
7907 // the OEM network preferences above.
7908 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007909 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7910 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007911
lucaslin3ba7cc22022-12-19 02:35:33 +00007912 // Current VPN network preferences. This object follows the same threading rules as the OEM
7913 // network preferences above.
7914 @NonNull
7915 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7916 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7917
paulhu51f77dc2021-06-07 02:34:20 +00007918 // A set of UIDs that should use mobile data preferentially if available. This object follows
7919 // the same threading rules as the OEM network preferences above.
7920 @NonNull
7921 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7922
James Mattiscb1e0362021-04-06 17:07:42 -07007923 // OemNetworkPreferences activity String log entries.
7924 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7925 @NonNull
7926 private final LocalLog mOemNetworkPreferencesLogs =
7927 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7928
James Mattis02220e22021-03-13 19:27:21 -08007929 /**
7930 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7931 * @param packageName the package name to check existence of a mapping for.
7932 * @return true if a mapping exists, false otherwise
7933 */
7934 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7935 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7936 }
7937
James Mattise3ef1912020-12-20 11:09:58 -08007938 // The always-on request for an Internet-capable network that apps without a specific default
7939 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007940 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007941 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007942 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007943 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007944 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007945 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007946 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007947
James Mattisd31bdfa2020-12-23 16:37:26 -08007948 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7949 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7950 }
7951
7952 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007953 * Return the default network request currently tracking the given uid.
7954 * @param uid the uid to check.
7955 * @return the NetworkRequestInfo tracking the given uid.
7956 */
7957 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007958 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007959 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007960 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007961 // Checking the first request is sufficient as only multilayer requests will have more
7962 // than one request and for multilayer, all requests will track the same uids.
7963 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007964 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007965 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007966 highestPriorityNri = nri;
7967 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007968 }
7969 }
paulhuaa0743d2021-05-26 21:56:03 +08007970 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007971 }
7972
7973 /**
7974 * Get a copy of the network requests of the default request that is currently tracking the
7975 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007976 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7977 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007978 * @param requestorUid the uid to check the default for.
7979 * @param requestorPackageName the requestor's package name.
7980 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7981 */
7982 @NonNull
7983 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007984 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007985 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007986 getDefaultRequestTrackingUid(asUid).mRequests,
7987 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007988 }
7989
7990 /**
7991 * Copy the given nri's NetworkRequest collection.
7992 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007993 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7994 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007995 * @param requestorUid the uid to set on the copied collection.
7996 * @param requestorPackageName the package name to set on the copied collection.
7997 * @return the copied NetworkRequest collection.
7998 */
7999 @NonNull
8000 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008001 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
8002 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008003 final List<NetworkRequest> requests = new ArrayList<>();
8004 for (final NetworkRequest nr : requestsToCopy) {
8005 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008006 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08008007 nr.legacyType, nextNetworkRequestId(), nr.type));
8008 }
8009 return requests;
8010 }
8011
8012 @NonNull
8013 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008014 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
8015 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09008016 // These capabilities are for a TRACK_DEFAULT callback, so:
8017 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
8018 // mDefaultRequest and a per-UID default request.
8019 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008020 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09008021 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008022 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
8023 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008024 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008025 restrictRequestUidsForCallerAndSetRequestorInfo(
8026 netCap, requestorUid, requestorPackageName);
8027 return netCap;
8028 }
8029
8030 /**
8031 * Get the nri that is currently being tracked for callbacks by per-app defaults.
8032 * @param nr the network request to check for equality against.
8033 * @return the nri if one exists, null otherwise.
8034 */
8035 @Nullable
8036 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
8037 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8038 if (nri.getNetworkRequestForCallback().equals(nr)) {
8039 return nri;
8040 }
8041 }
8042 return null;
8043 }
8044
8045 /**
8046 * Check if an nri is currently being managed by per-app default networking.
8047 * @param nri the nri to check.
8048 * @return true if this nri is currently being managed by per-app default networking.
8049 */
8050 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
8051 // nri.mRequests.get(0) is only different from the original request filed in
8052 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
8053 // functionality therefore if these two don't match, it means this particular nri is
8054 // currently being managed by a per-app default.
8055 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
8056 }
8057
8058 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008059 * Determine if an nri is a managed default request that disallows default networking.
8060 * @param nri the request to evaluate
8061 * @return true if device-default networking is disallowed
8062 */
8063 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
8064 // Check if this nri is a managed default that supports the default network at its
8065 // lowest priority request.
8066 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
8067 final NetworkCapabilities lowestPriorityNetCap =
8068 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
8069 return isPerAppDefaultRequest(nri)
8070 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8071 lowestPriorityNetCap));
8072 }
8073
Erik Kline05f2b402015-04-30 12:58:40 +09008074 // Request used to optionally keep mobile data active even when higher
8075 // priority networks like Wi-Fi are active.
8076 private final NetworkRequest mDefaultMobileDataRequest;
8077
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008078 // Request used to optionally keep wifi data active even when higher
8079 // priority networks like ethernet are active.
8080 private final NetworkRequest mDefaultWifiRequest;
8081
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008082 // Request used to optionally keep vehicle internal network always active
8083 private final NetworkRequest mDefaultVehicleRequest;
8084
James Mattisd31bdfa2020-12-23 16:37:26 -08008085 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8086 // network with no service. This NAI should never be matched against, nor should any public API
8087 // ever return the associated network. For this reason, this NAI is not in the list of available
8088 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8089 // default requests that don't support using the device default network which will ultimately
8090 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8091 @VisibleForTesting
8092 final NetworkAgentInfo mNoServiceNetwork;
8093
Chalard Jean5b409c72021-02-04 13:12:59 +09008094 // The NetworkAgentInfo currently satisfying the default request, if any.
8095 private NetworkAgentInfo getDefaultNetwork() {
8096 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008097 }
8098
James Mattis2516da32021-01-31 17:06:19 -08008099 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008100 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008101 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8102 // Currently, all network requests will have the same uids therefore checking the first
8103 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008104 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008105 if (null == uids) {
8106 continue;
8107 }
8108 for (final UidRange range : uids) {
8109 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008110 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008111 highestPriorityNri = nri;
8112 }
James Mattis2516da32021-01-31 17:06:19 -08008113 }
8114 }
8115 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008116 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008117 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008118 }
8119
Varun Ananddf569952019-02-06 10:13:38 -08008120 @Nullable
8121 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8122 return nai != null ? nai.network : null;
8123 }
8124
8125 private void ensureRunningOnConnectivityServiceThread() {
8126 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8127 throw new IllegalStateException(
8128 "Not running on ConnectivityService thread: "
8129 + Thread.currentThread().getName());
8130 }
8131 }
8132
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008133 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008134 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8135 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008136 }
8137
Chalard Jean29d06db2018-05-02 21:14:54 +09008138 /**
Chalard Jeane0aaca52023-10-17 13:23:07 +09008139 * Returns whether local agents are supported on this device.
8140 *
8141 * Local agents are supported from U on TVs, and from V on all devices.
8142 */
8143 @VisibleForTesting
8144 public boolean areLocalAgentsSupported() {
8145 final PackageManager pm = mContext.getPackageManager();
8146 // Local agents are supported starting on U on TVs and on V on everything else.
8147 return mDeps.isAtLeastV() || (mDeps.isAtLeastU() && pm.hasSystemFeature(FEATURE_LEANBACK));
8148 }
8149
8150 /**
Chalard Jean29d06db2018-05-02 21:14:54 +09008151 * Register a new agent with ConnectivityService to handle a network.
8152 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008153 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008154 * @param networkInfo the initial info associated with this network. It can be updated later :
8155 * see {@link #updateNetworkInfo}.
8156 * @param linkProperties the initial link properties of this network. They can be updated
8157 * later : see {@link #updateLinkProperties}.
8158 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008159 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008160 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008161 * @param localNetworkConfig config about this local network, or null if not a local network
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008162 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008163 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008164 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008165 */
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008166 public Network registerNetworkAgent(INetworkAgent na,
8167 NetworkInfo networkInfo,
8168 LinkProperties linkProperties,
8169 NetworkCapabilities networkCapabilities,
8170 @NonNull NetworkScore initialScore,
8171 @Nullable LocalNetworkConfig localNetworkConfig,
8172 NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09008173 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008174 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8175 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8176 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008177 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008178 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008179 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008180 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008181 } else {
8182 enforceNetworkFactoryPermission();
8183 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09008184 final boolean hasLocalCap =
8185 networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
8186 if (hasLocalCap && !areLocalAgentsSupported()) {
8187 // Before U, netd doesn't support PHYSICAL_LOCAL networks so this can't work.
8188 throw new IllegalArgumentException("Local agents are not supported in this version");
8189 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008190 final boolean hasLocalNetworkConfig = null != localNetworkConfig;
8191 if (hasLocalCap != hasLocalNetworkConfig) {
8192 throw new IllegalArgumentException(null != localNetworkConfig
8193 ? "Only local network agents can have a LocalNetworkConfig"
8194 : "Local network agents must have a LocalNetworkConfig"
8195 );
8196 }
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008197
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008198 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008199 final long token = Binder.clearCallingIdentity();
8200 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008201 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008202 networkCapabilities, initialScore, networkAgentConfig, localNetworkConfig,
8203 providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008204 } finally {
8205 Binder.restoreCallingIdentity(token);
8206 }
8207 }
8208
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008209 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008210 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008211 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig,
8212 @Nullable LocalNetworkConfig localNetworkConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09008213 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008214
Chalard Jeandbc46952022-02-02 00:14:18 +09008215 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8216 // and mutate them at any time.
8217 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8218 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8219 final LinkProperties lpCopy = new LinkProperties(linkProperties);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008220 // No need to copy |localNetworkConfiguration| as it is immutable.
Chalard Jeandbc46952022-02-02 00:14:18 +09008221
Chalard Jean366c5252022-01-25 18:27:53 +09008222 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008223 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008224 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8225 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008226 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008227 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008228 localNetworkConfig, currentScore, mContext, mTrackerHandler,
8229 new NetworkAgentConfig(networkAgentConfig), this, mNetd, mDnsResolver, providerId,
8230 uid, mLingerDelayMs, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008231
Chalard Jeandbc46952022-02-02 00:14:18 +09008232 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008233 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008234 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008235 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008236 mDeps.getNetworkStack().makeNetworkMonitor(
8237 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008238 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8239 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008240 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008241 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008242 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008243 }
8244
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008245 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008246 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008247 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008248 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008249 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008250 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8251 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8252 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008253
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008254 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008255
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008256 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008257 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008258 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008259 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008260
8261 try {
8262 networkMonitor.start();
8263 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008264 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008265 }
Chalard Jean366c5252022-01-25 18:27:53 +09008266
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008267 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008268 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008269 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008270 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008271 }
8272
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008273 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8274 @NonNull public final NetworkOffer offer;
8275
8276 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8277 this.offer = offer;
8278 }
8279
8280 @Override
8281 public void binderDied() {
8282 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8283 }
8284 }
8285
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008286 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8287 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8288 if (npi.providerId == providerId) return true;
8289 }
8290 return false;
8291 }
8292
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008293 /**
8294 * Register or update a network offer.
8295 * @param newOffer The new offer. If the callback member is the same as an existing
8296 * offer, it is an update of that offer.
8297 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008298 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008299 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8300 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008301 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008302 // This may actually happen if a provider updates its score or registers and then
8303 // immediately unregisters. The offer would still be in the handler queue, but the
8304 // provider would have been removed.
8305 if (DBG) log("Received offer from an unregistered provider");
8306 return;
8307 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008308 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8309 if (null != existingOffer) {
8310 handleUnregisterNetworkOffer(existingOffer);
8311 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008312 if (DBG) {
8313 // handleUnregisterNetworkOffer has already logged the old offer
8314 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8315 }
8316 } else {
8317 if (DBG) {
8318 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8319 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008320 }
8321 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8322 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008323 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008324 } catch (RemoteException e) {
8325 noi.binderDied();
8326 return;
8327 }
8328 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008329 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008330 }
8331
8332 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8333 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008334 if (DBG) {
8335 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8336 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008337
8338 // If the provider removes the offer and dies immediately afterwards this
8339 // function may be called twice in a row, but the array will no longer contain
8340 // the offer.
8341 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008342 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008343 }
8344
8345 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8346 @NonNull final INetworkOfferCallback callback) {
8347 ensureRunningOnConnectivityServiceThread();
8348 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008349 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008350 }
8351 return null;
8352 }
8353
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008354 /**
8355 * Called when receiving LinkProperties directly from a NetworkAgent.
8356 * Stores into |nai| any data coming from the agent that might also be written to the network's
8357 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8358 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008359 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008360 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008361 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8362 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008363 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008364 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008365 }
8366
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008367 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008368 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008369 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008370
Lorenzo Colittid523d142020-04-01 20:16:30 +09008371 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8372 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8373 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008374 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008375
Suprabh Shukla1e312032023-01-24 03:36:37 -08008376 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008377
8378 // update filtering rules, need to happen after the interface update so netd knows about the
8379 // new interface (the interface name -> index map becomes initialized)
8380 updateVpnFiltering(newLp, oldLp, networkAgent);
8381
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008382 updateMtu(newLp, oldLp);
8383 // TODO - figure out what to do for clat
8384// for (LinkProperties lp : newLp.getStackedLinks()) {
8385// updateMtu(lp, null);
8386// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008387 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008388 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008389 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8390 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008391
Erik Klineb9888902016-04-05 13:30:49 +09008392 updateRoutes(newLp, oldLp, netId);
8393 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008394 // Make sure LinkProperties represents the latest private DNS status.
8395 // This does not need to be done before updateDnses because the
8396 // LinkProperties are not the source of the private DNS configuration.
8397 // updateDnses will fetch the private DNS configuration from DnsManager.
8398 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008399
Chalard Jean5b409c72021-02-04 13:12:59 +09008400 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008401 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008402 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008403 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008404 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008405
8406 updateWakeOnLan(newLp);
8407
Hai Shalome58bdc62021-01-11 18:45:34 -08008408 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8409 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8410 // does, it needs to be merged here.
8411 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8412 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008413
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008414 // TODO - move this check to cover the whole function
8415 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008416 synchronized (networkAgent) {
8417 networkAgent.linkProperties = newLp;
8418 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008419 // Start or stop DNS64 detection and 464xlat according to network state.
8420 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008421 // Notify NSS when relevant events happened. Currently, NSS only cares about
8422 // interface changed to update clat interfaces accounting.
8423 final boolean interfacesChanged = oldLp == null
8424 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8425 if (interfacesChanged) {
8426 notifyIfacesChangedForNetworkStats();
8427 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008428 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8429 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008430 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008431 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008432
8433 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008434 }
8435
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008436 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8437 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8438 }
8439
Hai Shalome58bdc62021-01-11 18:45:34 -08008440 /**
8441 * @param naData captive portal data from NetworkAgent
8442 * @param apiData captive portal data from capport API
8443 */
8444 @Nullable
8445 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8446 CaptivePortalData apiData) {
8447 if (naData == null || apiData == null) {
8448 return naData == null ? apiData : naData;
8449 }
8450 final CaptivePortalData.Builder captivePortalBuilder =
8451 new CaptivePortalData.Builder(naData);
8452
8453 if (apiData.isCaptive()) {
8454 captivePortalBuilder.setCaptive(true);
8455 }
8456 if (apiData.isSessionExtendable()) {
8457 captivePortalBuilder.setSessionExtendable(true);
8458 }
8459 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8460 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8461 // otherwise data would be inconsistent. Prefer the capport API info if present,
8462 // as it can generally be refreshed more often.
8463 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8464 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8465 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8466 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8467 // No source has time / bytes remaining information: surface the newest refresh time
8468 // for other fields
8469 captivePortalBuilder.setRefreshTime(
8470 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8471 }
8472
Hai Shalom7c6ab402021-02-04 19:34:06 -08008473 // Prioritize the user portal URL from the network agent if the source is authenticated.
8474 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8475 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8476 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8477 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008478 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008479 // Prioritize the venue information URL from the network agent if the source is
8480 // authenticated.
8481 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8482 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8483 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8484 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008485 }
8486 return captivePortalBuilder.build();
8487 }
8488
Suprabh Shukla53e16392023-04-26 18:47:36 -07008489 @VisibleForTesting
8490 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008491 // This needs to be kept in sync and backwards compatible with the decoding logic in
8492 // NetdEventListenerService, which is non-mainline code.
8493 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8494 }
8495
Suprabh Shukla75642282023-04-25 23:15:43 -07008496 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8497 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8498 return true;
8499 }
8500 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8501 return true;
8502 }
8503 return false;
8504 }
8505
Suprabh Shukla1e312032023-01-24 03:36:37 -08008506 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008507 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008508 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008509 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008510 return;
8511 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008512
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008513 // Mask/mark of zero will not detect anything interesting.
8514 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008515 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008516 return;
8517 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008518
Suprabh Shukla1e312032023-01-24 03:36:37 -08008519 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008520 try {
8521 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008522 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008523 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008524 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008525 }
8526 } catch (Exception e) {
8527 loge("Exception modifying wakeup packet monitoring: " + e);
8528 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008529 }
8530
Junyu Lai970963e2022-10-25 15:46:47 +08008531 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008532 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008533 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008534 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008535 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008536 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008537 for (final String iface : interfaceDiff.added) {
8538 try {
8539 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008540 mRoutingCoordinatorService.addInterfaceToNetwork(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008541 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008542 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008543 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008544 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008545 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008546 }
Paul Jensenbff73492014-04-28 10:33:11 -04008547 }
8548 }
Chalard Jean9589e722019-11-19 19:03:53 +09008549 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008550 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008551 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008552 wakeupModifyInterface(iface, nai, false);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008553 mRoutingCoordinatorService.removeInterfaceFromNetwork(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008554 } catch (Exception e) {
8555 loge("Exception removing interface: " + e);
8556 }
8557 }
8558 }
8559
Paul Jensene0fd4a82014-08-06 15:51:33 -04008560 /**
8561 * Have netd update routes from oldLp to newLp.
8562 * @return true if routes changed between oldLp and newLp
8563 */
Junyu Lai970963e2022-10-25 15:46:47 +08008564 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8565 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008566 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008567 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8568 new CompareOrUpdateResult<>(
8569 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008570 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008571 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008572
8573 // add routes before removing old in case it helps with continuous connectivity
8574
Chalard Jean9dd11612018-06-04 16:52:49 +09008575 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008576 for (RouteInfo route : routeDiff.added) {
8577 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008578 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008579 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008580 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008581 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008582 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008583 loge("Exception in addRoute for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008584 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008585 }
8586 }
8587 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008588 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008589 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008590 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008591 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008592 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008593 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008594 loge("Exception in addRoute for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008595 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008596 }
8597 }
8598
8599 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008600 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008601 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008602 mRoutingCoordinatorService.removeRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008603 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008604 loge("Exception in removeRoute: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008605 }
8606 }
Tyler Weare4314862019-12-05 14:55:30 -08008607
8608 for (RouteInfo route : routeDiff.updated) {
8609 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8610 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008611 mRoutingCoordinatorService.updateRoute(netId, route);
Tyler Weare4314862019-12-05 14:55:30 -08008612 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008613 loge("Exception in updateRoute: " + e);
Tyler Weare4314862019-12-05 14:55:30 -08008614 }
8615 }
8616 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8617 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008618 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008619
Junyu Lai970963e2022-10-25 15:46:47 +08008620 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8621 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008622 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8623 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008624 }
Erik Klineb9888902016-04-05 13:30:49 +09008625
Erik Kline31b4a9e2018-01-11 21:07:29 +09008626 if (DBG) {
8627 final Collection<InetAddress> dnses = newLp.getDnsServers();
8628 log("Setting DNS servers for network " + netId + " to " + dnses);
8629 }
Erik Klineb9888902016-04-05 13:30:49 +09008630 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008631 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008632 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008633 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008634 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008635 }
Erik Kline54e35c02017-04-07 15:29:29 +09008636 }
8637
Junyu Lai970963e2022-10-25 15:46:47 +08008638 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8639 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008640 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8641 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008642 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8643 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008644
8645 if (!wasFiltering && !needsFiltering) {
8646 // Nothing to do.
8647 return;
8648 }
8649
8650 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8651 // Nothing changed.
8652 return;
8653 }
8654
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008655 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008656 if (ranges == null || ranges.isEmpty()) {
8657 return;
8658 }
8659
Qingxi Libb8da982020-01-17 17:54:27 -08008660 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008661 // TODO: this create a window of opportunity for apps to receive traffic between the time
8662 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008663 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008664 // old rules are being removed.
8665 if (wasFiltering) {
8666 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8667 }
8668 if (needsFiltering) {
8669 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8670 }
8671 }
8672
Valentin Iftime9fa35092019-09-24 13:32:13 +02008673 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008674 if (mWolSupportedInterfaces == null) {
8675 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008676 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008677 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008678 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8679 }
8680
Luke Huangb913c812018-08-24 20:33:16 +08008681 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008682 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008683 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008684 }
8685 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008686 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008687 }
Luke Huangb913c812018-08-24 20:33:16 +08008688 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008689 }
8690
Chalard Jean62edfd82019-12-02 18:39:29 +09008691 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8692 @NonNull final NetworkCapabilities newNc) {
8693 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8694 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008695 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008696 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008697 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008698 } catch (RemoteException | ServiceSpecificException e) {
8699 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008700 }
8701 }
8702 }
8703
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008704 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008705 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008706 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008707 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008708 underlyingNetworks = underlyingNetworksOrDefault(
8709 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008710 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008711 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8712 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008713 // metered if any underlying is metered, or originally declared metered by the agent.
8714 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008715 boolean roaming = false; // roaming if any underlying is roaming
8716 boolean congested = false; // congested if any underlying is congested
8717 boolean suspended = true; // suspended if all underlying are suspended
8718
8719 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008720 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008721 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008722 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008723 for (Network underlyingNetwork : underlyingNetworks) {
8724 final NetworkAgentInfo underlying =
8725 getNetworkAgentInfoForNetwork(underlyingNetwork);
8726 if (underlying == null) continue;
8727
8728 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8729 hadUnderlyingNetworks = true;
8730 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008731 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008732 }
8733
8734 // Merge capabilities of this underlying network. For bandwidth, assume the
8735 // worst case.
8736 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8737 underlyingCaps.getLinkDownstreamBandwidthKbps());
8738 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8739 underlyingCaps.getLinkUpstreamBandwidthKbps());
8740 // If this underlying network is metered, the VPN is metered (it may cost money
8741 // to send packets on this network).
8742 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8743 // If this underlying network is roaming, the VPN is roaming (the billing structure
8744 // is different than the usual, local one).
8745 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8746 // If this underlying network is congested, the VPN is congested (the current
8747 // condition of the network affects the performance of this network).
8748 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8749 // If this network is not suspended, the VPN is not suspended (the VPN
8750 // is able to transfer some data).
8751 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008752 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008753 }
8754 }
8755 if (!hadUnderlyingNetworks) {
8756 // No idea what the underlying networks are; assume reasonable defaults
8757 metered = true;
8758 roaming = false;
8759 congested = false;
8760 suspended = false;
8761 }
8762
Chalard Jean1d420b32022-10-12 16:39:37 +09008763 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008764 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8765 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8766 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8767 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8768 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8769 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008770 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008771 }
8772
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008773 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008774 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8775 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8776 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008777 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008778 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008779 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008780 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008781 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8782 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008783 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008784 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008785 if (nai.everConnected()
8786 && !nai.isVPN()
8787 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008788 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008789 // does not cause any request (that is not a listen) currently matching that agent to
8790 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008791 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008792 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008793 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008794 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008795 }
8796
Paul Jensen53f08952015-06-16 14:27:36 -04008797 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008798 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008799 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008800 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008801 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008802 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008803 }
Chalard Jean254bd162022-08-25 13:04:51 +09008804 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008805 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008806 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008807 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008808 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008809 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008810 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008811 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008812 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008813 }
Chalard Jean254bd162022-08-25 13:04:51 +09008814 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008815 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8816 } else {
8817 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8818 }
lucasline117e2e2019-10-22 18:27:33 +08008819 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008820
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008821 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008822 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8823 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008824 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008825 }
8826
Lorenzo Colittibd079452021-07-02 11:47:57 +09008827 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008828 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008829 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008830 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008831 }
8832
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008833 return newNc;
8834 }
8835
Lorenzo Colitti44840702021-01-11 22:27:57 +09008836 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8837 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8838 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8839 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8840 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8841 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8842 if (prevSuspended != suspended) {
8843 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8844 // onResumed have been removed.
8845 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8846 : ConnectivityManager.CALLBACK_RESUMED);
8847 }
8848 if (prevSuspended != suspended || prevRoaming != roaming) {
8849 // updateNetworkInfo will mix in the suspended info from the capabilities and
8850 // take appropriate action for the network having possibly changed state.
8851 updateNetworkInfo(nai, nai.networkInfo);
8852 }
8853 }
8854
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008855 /**
8856 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8857 *
8858 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8859 * capabilities we manage and store in {@code nai}, such as validated status and captive
8860 * portal status)
8861 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8862 * potentially triggers rematches.
8863 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8864 * change.)
8865 *
8866 * @param oldScore score of the network before any of the changes that prompted us
8867 * to call this function.
8868 * @param nai the network having its capabilities updated.
8869 * @param nc the new network capabilities.
8870 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008871 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008872 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008873 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008874 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008875 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8876 if (null != differences) {
8877 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8878 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008879 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008880 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008881
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008882 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008883 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008884 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008885
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008886 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008887 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8888 // the change we're processing can't affect any requests, it can only affect the listens
8889 // on this network. We might have been called by rematchNetworkAndRequests when a
8890 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008891 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008892 } else {
8893 // If the requestable capabilities have changed or the score changed, we can't have been
8894 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008895 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008896 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008897 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008898 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008899
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008900 final boolean oldMetered = prevNc.isMetered();
8901 final boolean newMetered = newNc.isMetered();
8902 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008903
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008904 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008905 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8906 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008907 }
junyulaif2c67e42018-08-07 19:50:45 +08008908
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008909 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8910 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008911
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008912 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008913 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008914 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008915 }
8916
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008917 // This network might have been underlying another network. Propagate its capabilities.
8918 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008919
Ken Chen5a35cf92023-10-07 07:54:22 +08008920 if (meteredChanged || !newNc.equalsTransportTypes(prevNc)) {
Ken Chen6b134f12023-10-07 07:46:47 +08008921 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(), newNc);
chenbruce7b2f8982020-02-20 14:28:31 +08008922 }
lucaslin53e8a262021-06-08 01:43:59 +08008923
8924 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008925 }
8926
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008927 /** Convenience method to update the capabilities for a given network. */
8928 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008929 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008930 }
8931
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008932 private void updateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
8933 @NonNull final LocalNetworkConfig config) {
8934 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK)) {
8935 Log.wtf(TAG, "Ignoring update of a local network info on non-local network " + nai);
8936 return;
8937 }
8938 // TODO : actually apply the diff.
8939 nai.localNetworkConfig = config;
8940 }
8941
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008942 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008943 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008944 *
8945 * Ingress interface filtering enforces that all apps under the given network can only receive
8946 * packets from the network's interface (and loopback). This is important for VPNs because
8947 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8948 * non-VPN interfaces.
8949 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008950 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008951 * 1. the network is an app VPN (not legacy VPN)
8952 * 2. the VPN does not allow bypass
8953 * 3. the VPN is fully-routed
8954 * 4. the VPN interface is non-null
8955 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008956 * @see INetd#firewallAddUidInterfaceRules
8957 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008958 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008959 @Nullable
8960 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008961 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008962 if (nc == null || lp == null) return null;
8963 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008964 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008965 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008966 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008967 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008968 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008969 && !lp.hasExcludeRoute()) {
8970 return lp.getInterfaceName();
8971 }
8972 return null;
8973 }
8974
8975 /**
8976 * Returns whether we need to set interface filtering rule or not
8977 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008978 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008979 String isolationIface) {
8980 // Allow rules are always needed if VPN isolation is enabled.
8981 if (isolationIface != null) return true;
8982
8983 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8984 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8985 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09008986 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008987 }
8988
Chiachang Wang28afaff2020-12-10 22:24:47 +08008989 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8990 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8991 int index = 0;
8992 for (UidRange range : ranges) {
8993 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8994 index++;
8995 }
8996 return stableRanges;
8997 }
8998
Chalard Jeane6c95272022-01-25 21:04:21 +09008999 private static UidRangeParcel[] intsToUidRangeStableParcels(
9000 final @NonNull ArraySet<Integer> uids) {
9001 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
9002 int index = 0;
9003 for (int uid : uids) {
9004 stableRanges[index] = new UidRangeParcel(uid, uid);
9005 index++;
9006 }
9007 return stableRanges;
9008 }
9009
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009010 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
9011 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
9012 for (int i = 0; i < ranges.length; i++) {
9013 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
9014 }
9015 return stableRanges;
9016 }
9017
Motomu Utsumi93a22182023-03-16 17:04:21 +09009018 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09009019 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08009020 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
9021 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009022 if (mDeps.isAtLeastU()) {
9023 final Set<Integer> exemptUidSet = new ArraySet<>();
9024 for (final int uid: exemptUids) {
9025 exemptUidSet.add(uid);
9026 }
9027 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
9028 } else {
9029 mNetd.socketDestroy(uidRangeParcels, exemptUids);
9030 }
Ken Chen5e65a852020-12-24 12:59:10 +08009031 } catch (Exception e) {
9032 loge("Exception in socket destroy: ", e);
9033 }
9034 }
9035 }
9036
paulhuaa0743d2021-05-26 21:56:03 +08009037 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009038 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08009039 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
9040 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
9041 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09009042 exemptUids[0] = VPN_UID;
9043 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08009044 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
9045
Motomu Utsumi6345e462023-03-13 13:24:50 +09009046 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009047 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009048 try {
9049 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08009050 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009051 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009052 } else {
paulhu0e79d952021-06-09 16:11:35 +08009053 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009054 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009055 }
9056 } catch (Exception e) {
9057 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
9058 " on netId " + nai.network.netId + ". " + e);
9059 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09009060 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009061 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009062 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009063
lucaslin53e8a262021-06-08 01:43:59 +08009064 private boolean isProxySetOnAnyDefaultNetwork() {
9065 ensureRunningOnConnectivityServiceThread();
9066 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9067 final NetworkAgentInfo nai = nri.getSatisfier();
9068 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9069 return true;
9070 }
9071 }
9072 return false;
9073 }
9074
9075 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9076 NetworkCapabilities newNc) {
9077 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9078 // the proxy might be changed since the default network satisfied by the apps might also
9079 // changed.
9080 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9081 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009082 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9083 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009084 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009085 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9086 mProxyTracker.sendProxyBroadcast();
9087 }
9088 }
9089
Chalard Jeane6c95272022-01-25 21:04:21 +09009090 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9091 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009092 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9093 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009094 if (null == prevRanges) prevRanges = new ArraySet<>();
9095 if (null == newRanges) newRanges = new ArraySet<>();
9096 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9097
9098 prevRanges.removeAll(newRanges);
9099 newRanges.removeAll(prevRangesCopy);
9100
9101 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009102 // When updating the VPN uid routing rules, add the new range first then remove the old
9103 // range. If old range were removed first, there would be a window between the old
9104 // range being removed and the new range being added, during which UIDs contained
9105 // in both ranges are not subject to any VPN routing rules. Adding new range before
9106 // removing old range works because, unlike the filtering rules below, it's possible to
9107 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009108 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9109 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9110 // [1-5] & [1-2],[4-5] == [3]
9111 // Then we can do:
9112 // maybeCloseSockets([3])
9113 // mNetd.networkAddUidRanges([1-2],[4-5])
9114 // mNetd.networkRemoveUidRanges([1-5])
9115 // maybeCloseSockets([3])
9116 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9117 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009118 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009119 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009120 }
9121 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009122 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009123 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009124 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9125 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009126 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9127 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009128 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009129 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009130 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9131 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9132 // were added first and then newRanges got removed later, there would be only one uid
9133 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9134 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9135 // Note that this is in contrast with the (more robust) update of VPN routing rules
9136 // above, where the addition of new ranges happens before the removal of old ranges.
9137 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9138 // to be removed will never overlap with the new range to be added.
9139 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009140 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9141 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009142 }
9143 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009144 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009145 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009146 } catch (Exception e) {
9147 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009148 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009149 }
9150 }
9151
Chalard Jeande665262022-02-25 16:12:12 +09009152 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009153 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9154 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009155 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9156 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009157 if (prevEmpty && newEmpty) return;
9158
9159 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009160 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009161 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009162 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009163
9164 if (prevUids.equals(newUids)) return;
9165
9166 // This implementation is very simple and vastly faster for sets of Integers than
9167 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9168 // a key computed from the value and has storage for that.
9169 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9170 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9171 toRemove.removeAll(newUids);
9172 toAdd.removeAll(prevUids);
9173
9174 try {
9175 if (!toAdd.isEmpty()) {
9176 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9177 nai.network.netId,
9178 intsToUidRangeStableParcels(toAdd),
9179 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9180 }
9181 if (!toRemove.isEmpty()) {
9182 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9183 nai.network.netId,
9184 intsToUidRangeStableParcels(toRemove),
9185 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9186 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009187 } catch (ServiceSpecificException e) {
9188 // Has the interface disappeared since the network was built ?
9189 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009190 } catch (RemoteException e) {
9191 // Netd died. This usually causes a runtime restart anyway.
9192 }
9193 }
9194
Junyu Lai2ed7d412022-10-07 16:52:21 +08009195 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9196 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009197 ensureRunningOnConnectivityServiceThread();
9198
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009199 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009200 // Ignore updates for disconnected networks
9201 return;
9202 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009203 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009204 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009205 + "; created=" + nai.getCreatedTime()
9206 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009207 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009208 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9209 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009210 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009211 }
9212
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009213 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9214 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009215 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009216 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009217 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009218 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9219 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9220 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009221 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9222 // need to be sent as a separate extra.
9223 final NetworkRequest req = nri.isMultilayerRequest()
9224 ? nri.getActiveRequest()
9225 // Non-multilayer listen requests do not have an active request
9226 : nri.mRequests.get(0);
9227 if (req == null) {
9228 Log.wtf(TAG, "No request in NRI " + nri);
9229 }
9230 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009231 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009232 sendIntent(nri.mPendingIntent, intent);
9233 }
9234 // else not handled
9235 }
9236
Michael Groover73f69482023-01-27 11:01:25 -06009237 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9238 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009239 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9240 mPendingIntentWakeLock.acquire();
9241 try {
9242 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009243 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009244 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009245 // Explicitly disallow the receiver from starting activities, to prevent apps from
9246 // utilizing the PendingIntent as a backdoor to do this.
9247 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9248 }
9249 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9250 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009251 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009252 } catch (PendingIntent.CanceledException e) {
9253 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9254 mPendingIntentWakeLock.release();
9255 releasePendingNetworkRequest(pendingIntent);
9256 }
9257 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9258 }
9259
9260 @Override
9261 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9262 String resultData, Bundle resultExtras) {
9263 if (DBG) log("Finished sending " + pendingIntent);
9264 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009265 // Release with a delay so the receiving client has an opportunity to put in its
9266 // own request.
9267 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009268 }
9269
Chalard Jean46bfbf02022-02-02 00:56:25 +09009270 // networkAgent is only allowed to be null if notificationType is
9271 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9272 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009273 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009274 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009275 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009276 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009277 // Default request has no msgr. Also prevents callbacks from being invoked for
9278 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9279 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9280 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009281 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09009282 final Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009283 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009284 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009285 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009286 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009287 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009288 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9289 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009290 }
Roshan Pius951c0032020-12-22 15:10:42 -08009291 final boolean includeLocationSensitiveInfo =
9292 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009293 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009294 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009295 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009296 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009297 networkCapabilitiesRestrictedForCallerPermissions(
9298 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9299 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009300 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009301 nri.mCallingAttributionTag);
9302 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009303 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9304 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08009305 // For this notification, arg1 contains the blocked status.
9306 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009307 break;
9308 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009309 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009310 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009311 break;
9312 }
9313 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009314 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009315 final NetworkCapabilities netCap =
9316 networkCapabilitiesRestrictedForCallerPermissions(
9317 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9318 putParcelable(
9319 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009320 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009321 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009322 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009323 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009324 break;
9325 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009326 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009327 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9328 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009329 break;
9330 }
junyulaif2c67e42018-08-07 19:50:45 +08009331 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009332 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009333 msg.arg1 = arg1;
9334 break;
9335 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009336 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009337 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009338 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009339 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009340 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009341 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009342 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009343 }
James Mattis45d81842021-01-10 14:24:24 -08009344 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009345 } catch (RemoteException e) {
9346 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009347 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009348 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009349 }
9350
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009351 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9352 bundle.putParcelable(t.getClass().getSimpleName(), t);
9353 }
9354
Chalard Jean0702f982021-09-16 21:50:07 +09009355 /**
9356 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9357 *
9358 * When a request should be assigned to a new network, it is normally lingered to give
9359 * time for apps to gracefully migrate their connections. When both networks are on the same
9360 * radio, but that radio can't do time-sharing efficiently, this may end up being
9361 * counter-productive because any traffic on the old network may drastically reduce the
9362 * performance of the new network.
9363 * The stack supports a configuration to let modem vendors state that their radio can't
9364 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9365 * from one cell network to another can't be done gracefully.
9366 *
9367 * @param oldNai the old network serving the request
9368 * @param newNai the new network serving the request
9369 * @return whether the switch can be graceful
9370 */
9371 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9372 @NonNull final NetworkAgentInfo newSatisfier) {
9373 if (mCellularRadioTimesharingCapable) return true;
9374 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9375 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9376 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9377 }
9378
Paul Jensenaf94b982014-09-30 15:37:41 -04009379 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009380 if (nai.numRequestNetworkRequests() != 0) {
9381 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9382 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009383 // Ignore listening and track default requests.
9384 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009385 loge("Dead network still had at least " + nr);
9386 break;
9387 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009388 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009389 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009390 }
9391
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009392 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9393 if (oldNetwork == null) {
9394 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9395 return;
9396 }
Chalard Jean49707572019-12-10 21:07:02 +09009397 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009398
9399 // If we get here it means that the last linger timeout for this network expired. So there
9400 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009401 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009402
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009403 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009404 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009405 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009406 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009407 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009408 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009409 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009410 }
9411
James Mattise3ef1912020-12-20 11:09:58 -08009412 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9413 boolean isDefaultChanged = false;
9414 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9415 final NetworkReassignment.RequestReassignment reassignment =
9416 changes.getReassignment(defaultRequestInfo);
9417 if (null == reassignment) {
9418 continue;
9419 }
9420 // reassignment only contains those instances where the satisfying network changed.
9421 isDefaultChanged = true;
9422 // Notify system services of the new default.
9423 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9424 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009425
James Mattise3ef1912020-12-20 11:09:58 -08009426 if (isDefaultChanged) {
9427 // Hold a wakelock for a short time to help apps in migrating to a new default.
9428 scheduleReleaseNetworkTransitionWakelock();
9429 }
9430 }
9431
Aaron Huang9fe47be2021-06-08 13:11:45 +08009432 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9433 if (null == oldDefaultNetwork) return;
9434 // The network stopped being the default. If it was using a PAC proxy, then the
9435 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9436 // to the local proxy server, which would forward them over the newly default network.
9437 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9438 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9439 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9440 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9441 }
9442
James Mattise3ef1912020-12-20 11:09:58 -08009443 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9444 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9445 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9446 if (DBG) {
9447 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9448 }
Chalard Jean8e382112019-12-03 20:45:30 +09009449
James Mattisd31bdfa2020-12-23 16:37:26 -08009450 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9451 if (newDefaultNetwork != null) {
9452 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009453 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009454
James Mattisd31bdfa2020-12-23 16:37:26 -08009455 // Set an app level managed default and return since further processing only applies to the
9456 // default network.
9457 if (mDefaultRequest != nri) {
9458 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9459 return;
9460 }
9461
9462 makeDefaultNetwork(newDefaultNetwork);
9463
James Mattise3ef1912020-12-20 11:09:58 -08009464 if (oldDefaultNetwork != null) {
9465 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9466 }
9467 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009468 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009469 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009470 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009471 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009472 updateTcpBufferSizes(null != newDefaultNetwork
9473 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009474 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009475 }
9476
James Mattisd31bdfa2020-12-23 16:37:26 -08009477 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9478 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9479 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9480 try {
9481 if (VDBG) {
9482 log("Setting default network for " + nri
9483 + " using UIDs " + nri.getUids()
9484 + " with old network " + (oldDefaultNetwork != null
9485 ? oldDefaultNetwork.network().getNetId() : "null")
9486 + " and new network " + (newDefaultNetwork != null
9487 ? newDefaultNetwork.network().getNetId() : "null"));
9488 }
9489 if (nri.getUids().isEmpty()) {
9490 throw new IllegalStateException("makeDefaultForApps called without specifying"
9491 + " any applications to set as the default." + nri);
9492 }
9493 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009494 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009495 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009496 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009497 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009498 }
9499 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009500 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009501 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009502 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009503 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009504 }
9505 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009506 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009507 }
9508 }
9509
Junyu Lai35665cc2022-12-19 17:37:48 +08009510 /**
9511 * Collect restricted uid ranges for the given network and UserHandle, these uids
9512 * are not restricted for matched enterprise networks but being restricted for non-matched
9513 * enterprise networks and non-enterprise networks.
9514 */
9515 @NonNull
9516 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9517 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9518 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9519 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9520 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9521
9522 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9523 // The NC is built from a `ProfileNetworkPreference` which has only one
9524 // enterprise ID, so it's guaranteed to have exactly one.
9525 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9526 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9527 continue;
9528 }
9529 }
9530
9531 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9532 pref.capabilities.getUidRanges())) {
9533 throw new IllegalArgumentException(
9534 "Overlapping uid range in preference: " + pref);
9535 }
9536 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9537 }
9538 return restrictedUidRanges;
9539 }
9540
9541 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009542 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +09009543 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009544
Junyu Lai35665cc2022-12-19 17:37:48 +08009545 ensureRunningOnConnectivityServiceThread();
9546 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9547 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9548 .getUserHandles(true /* excludeDying */);
9549 if (users.isEmpty()) {
9550 throw new IllegalStateException("No user is available");
9551 }
9552
9553 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9554 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9555 for (final UserHandle user : users) {
9556 final ArraySet<UidRange> restrictedUidRanges =
9557 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9558 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9559 UidRange.createForUser(user), restrictedUidRanges));
9560 }
9561
9562 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9563 configs.add(new NativeUidRangeConfig(
9564 nai.network.netId, rangesParcel, 0 /* subPriority */));
9565 }
9566
9567 // The netd API replaces the previous configs with the current configs.
9568 // Thus, for network disconnection or preference removal, no need to
9569 // unset previous config. Instead, collecting all currently needed
9570 // configs and issue to netd.
9571 try {
9572 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9573 } catch (ServiceSpecificException e) {
9574 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009575 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009576 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009577 // Netd died. This will cause a runtime restart anyway.
9578 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009579 }
9580 }
9581
James Mattisd31bdfa2020-12-23 16:37:26 -08009582 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9583 try {
9584 if (null != newDefaultNetwork) {
9585 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9586 } else {
9587 mNetd.networkClearDefault();
9588 }
9589 } catch (RemoteException | ServiceSpecificException e) {
9590 loge("Exception setting default network :" + e);
9591 }
9592 }
9593
Chalard Jean05cbe972019-12-09 11:50:38 +09009594 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009595 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009596 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009597 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009598 processNewlySatisfiedListenRequests(nai);
9599 }
9600
9601 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009602 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9603 if (nri.isMultilayerRequest()) {
9604 continue;
9605 }
9606 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009607 if (!nr.isListen()) continue;
9608 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009609 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009610 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9611 }
9612 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009613 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009614
Chalard Jeancd397a22019-11-22 22:33:33 +09009615 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009616 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9617 if (nri.isMultilayerRequest()) {
9618 continue;
9619 }
9620 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009621 if (!nr.isListen()) continue;
9622 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9623 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009624 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009625 }
9626 }
9627 }
9628
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009629 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009630 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009631 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009632 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009633 @Nullable public final NetworkRequest mOldNetworkRequest;
9634 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009635 @Nullable public final NetworkAgentInfo mOldNetwork;
9636 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009637 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009638 @Nullable final NetworkRequest oldNetworkRequest,
9639 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009640 @Nullable final NetworkAgentInfo oldNetwork,
9641 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009642 mNetworkRequestInfo = networkRequestInfo;
9643 mOldNetworkRequest = oldNetworkRequest;
9644 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009645 mOldNetwork = oldNetwork;
9646 mNewNetwork = newNetwork;
9647 }
Chalard Jean49707572019-12-10 21:07:02 +09009648
9649 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009650 final NetworkRequest requestToShow = null != mNewNetworkRequest
9651 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9652 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009653 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9654 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009655 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009656 }
9657
Chalard Jean46a62372019-12-10 21:25:24 +09009658 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009659
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009660 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009661 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009662 }
9663
9664 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009665 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009666 // The code is never supposed to add two reassignments of the same request. Make
9667 // sure this stays true, but without imposing this expensive check on all
9668 // reassignments on all user devices.
9669 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009670 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009671 throw new IllegalStateException("Trying to reassign ["
9672 + reassignment + "] but already have ["
9673 + existing + "]");
9674 }
9675 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009676 }
Chalard Jean46a62372019-12-10 21:25:24 +09009677 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009678 }
9679
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009680 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009681 // the passed request.
9682 @Nullable
9683 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009684 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009685 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009686 }
9687 return null;
9688 }
Chalard Jean49707572019-12-10 21:07:02 +09009689
9690 public String toString() {
9691 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9692 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009693 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009694 for (final RequestReassignment rr : getRequestReassignments()) {
9695 sj.add(rr.toString());
9696 }
9697 return sj.toString();
9698 }
9699
9700 public String debugString() {
9701 final StringBuilder sb = new StringBuilder();
9702 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009703 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009704 for (final RequestReassignment rr : getRequestReassignments()) {
9705 sb.append("\n ").append(rr);
9706 }
9707 return sb.append("\n").toString();
9708 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009709 }
9710
Chalard Jean24344d72019-12-04 13:32:31 +09009711 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009712 @Nullable final NetworkRequest previousRequest,
9713 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009714 @Nullable final NetworkAgentInfo previousSatisfier,
9715 @Nullable final NetworkAgentInfo newSatisfier,
9716 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009717 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009718 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009719 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009720 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009721 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09009722 }
James Mattisa076c532020-12-02 14:12:41 -08009723 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009724 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009725 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009726 // If this network switch can't be supported gracefully, the request is not
9727 // lingered. This allows letting go of the network sooner to reclaim some
9728 // performance on the new network, since the radio can't do both at the same
9729 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009730 //
9731 // Also don't linger the request if the old network has been destroyed.
9732 // A destroyed network does not provide actual network connectivity, so
9733 // lingering it is not useful. In particular this ensures that a destroyed
9734 // network is outscored by its replacement,
9735 // then it is torn down immediately instead of being lingered, and any apps that
9736 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009737 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9738 }
Chalard Jean24344d72019-12-04 13:32:31 +09009739 } else {
9740 if (VDBG || DDBG) log(" accepting network in place of null");
9741 }
junyulai0ac374f2020-12-14 18:41:52 +08009742
9743 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9744 // and immediately satisfies a request then remove the timer. This will happen for
9745 // all networks except in the case of an underlying network for a VCN.
9746 if (newSatisfier.isNascent()) {
9747 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009748 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009749 }
9750
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009751 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009752 newSatisfier.unlingerRequest(newRequest.requestId);
9753 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009754 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009755 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009756 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009757 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009758 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009759 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009760 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009761 }
James Mattisa076c532020-12-02 14:12:41 -08009762 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009763 }
James Mattisa076c532020-12-02 14:12:41 -08009764 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009765 }
9766
James Mattisa076c532020-12-02 14:12:41 -08009767 /**
9768 * This function is triggered when something can affect what network should satisfy what
9769 * request, and it computes the network reassignment from the passed collection of requests to
9770 * network match to the one that the system should now have. That data is encoded in an
9771 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9772 * satisfier.
9773 *
9774 * After the reassignment is computed, it is applied to the state objects.
9775 *
9776 * @param networkRequests the nri objects to evaluate for possible network reassignment
9777 * @return NetworkReassignment listing of proposed network assignment changes
9778 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009779 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009780 private NetworkReassignment computeNetworkReassignment(
9781 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009782 final NetworkReassignment changes = new NetworkReassignment();
9783
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009784 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009785 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009786 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009787 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009788 }
Chalard Jean857a1712019-12-10 21:08:07 +09009789
James Mattisa076c532020-12-02 14:12:41 -08009790 for (final NetworkRequestInfo nri : networkRequests) {
9791 // Non-multilayer listen requests can be ignored.
9792 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9793 continue;
9794 }
9795 NetworkAgentInfo bestNetwork = null;
9796 NetworkRequest bestRequest = null;
9797 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009798 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009799 // Stop evaluating as the highest possible priority request is satisfied.
9800 if (null != bestNetwork) {
9801 bestRequest = req;
9802 break;
9803 }
9804 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009805 if (null == bestNetwork && isDefaultBlocked(nri)) {
9806 // Remove default networking if disallowed for managed default requests.
9807 bestNetwork = mNoServiceNetwork;
9808 }
9809 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009810 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009811 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009812 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009813 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009814 }
9815 return changes;
9816 }
9817
James Mattisa076c532020-12-02 14:12:41 -08009818 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9819 return new HashSet<>(mNetworkRequests.values());
9820 }
9821
Paul Jensenc88b39b2015-06-16 14:27:36 -04009822 /**
James Mattisa076c532020-12-02 14:12:41 -08009823 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009824 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009825 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009826 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009827 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9828 }
9829
9830 /**
9831 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9832 * being disconnected.
9833 */
9834 private void rematchNetworksAndRequests(
9835 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9836 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009837 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009838 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009839 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009840 final long computed = SystemClock.elapsedRealtime();
9841 applyNetworkReassignment(changes, start);
9842 final long applied = SystemClock.elapsedRealtime();
9843 issueNetworkNeeds();
9844 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009845 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009846 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9847 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009848 log(changes.debugString());
9849 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009850 // Shorter form, only one line of log
9851 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9852 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009853 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009854 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009855
Chalard Jeand7f762d2019-12-10 19:01:29 +09009856 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009857 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009858 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009859
9860 // Since most of the time there are only 0 or 1 background networks, it would probably
9861 // be more efficient to just use an ArrayList here. TODO : measure performance
9862 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9863 for (final NetworkAgentInfo nai : nais) {
9864 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9865 }
9866
Chalard Jeand7f762d2019-12-10 19:01:29 +09009867 // First, update the lists of satisfied requests in the network agents. This is necessary
9868 // because some code later depends on this state to be correct, most prominently computing
9869 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009870 for (final NetworkReassignment.RequestReassignment event :
9871 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009872 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9873 event.mOldNetworkRequest, event.mNewNetworkRequest,
9874 event.mOldNetwork, event.mNewNetwork,
9875 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009876 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009877
James Mattise3ef1912020-12-20 11:09:58 -08009878 // Process default network changes if applicable.
9879 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009880
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009881 // Notify requested networks are available after the default net is switched, but
9882 // before LegacyTypeTracker sends legacy broadcasts
9883 for (final NetworkReassignment.RequestReassignment event :
9884 changes.getRequestReassignments()) {
9885 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009886 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009887 } else {
James Mattisa076c532020-12-02 14:12:41 -08009888 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009889 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009890 }
9891 }
9892
junyulai0ac374f2020-12-14 18:41:52 +08009893 // Update the inactivity state before processing listen callbacks, because the background
9894 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009895 // just yet though, because they have to be sent after the listens are processed to keep
9896 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009897 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009898 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009899 // Rematching may have altered the inactivity state of some networks, so update all
9900 // inactivity timers. updateInactivityState reads the state from the network agent
9901 // and does nothing if the state has not changed : the source of truth is controlled
9902 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9903 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009904 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009905 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009906 }
9907 }
9908
Chalard Jeanb10ab412019-12-11 14:12:30 +09009909 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009910 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009911 // Process listen requests and update capabilities if the background state has
9912 // changed for this network. For consistency with previous behavior, send onLost
9913 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009914 processNewlyLostListenRequests(nai);
9915 if (oldBackground != nai.isBackgroundNetwork()) {
9916 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009917 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009918 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009919 }
9920
junyulai0ac374f2020-12-14 18:41:52 +08009921 for (final NetworkAgentInfo nai : inactiveNetworks) {
9922 // For nascent networks, if connecting with no foreground request, skip broadcasting
9923 // LOSING for backward compatibility. This is typical when mobile data connected while
9924 // wifi connected with mobile data always-on enabled.
9925 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009926 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009927 }
9928
James Mattise3ef1912020-12-20 11:09:58 -08009929 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009930
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009931 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +00009932 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009933 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009934 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009935 // This network has active linger timers and no requests, but is not
9936 // lingering. Linger it.
9937 //
9938 // One way (the only way?) this can happen if this network is unvalidated
9939 // and became unneeded due to another network improving its score to the
9940 // point where this network will no longer be able to satisfy any requests
9941 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009942 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009943 notifyNetworkLosing(nai, now);
9944 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009945 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009946 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009947 teardownUnneededNetwork(nai);
9948 }
9949 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009950 }
9951 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009952
Chalard Jean62edfd82019-12-02 18:39:29 +09009953 /**
9954 * Apply a change in background state resulting from rematching networks with requests.
9955 *
9956 * During rematch, a network may change background states by starting to satisfy or stopping
9957 * to satisfy a foreground request. Listens don't count for this. When a network changes
9958 * background states, its capabilities need to be updated and callbacks fired for the
9959 * capability change.
9960 *
9961 * @param nai The network that changed background states
9962 */
9963 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
9964 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
9965 if (Objects.equals(nai.networkCapabilities, newNc)) return;
9966 updateNetworkPermissions(nai, newNc);
9967 nai.getAndSetNetworkCapabilities(newNc);
9968 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
9969 }
9970
Chalard Jeanf0344532019-11-19 19:23:38 +09009971 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08009972 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009973 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09009974 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
9975 changes.getReassignment(mDefaultRequest);
9976 final NetworkAgentInfo oldDefaultNetwork =
9977 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
9978 final NetworkAgentInfo newDefaultNetwork =
9979 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08009980
Chalard Jean5b409c72021-02-04 13:12:59 +09009981 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009982 // Maintain the illusion : since the legacy API only understands one network at a time,
9983 // if the default network changed, apps should see a disconnected broadcast for the
9984 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009985 if (oldDefaultNetwork != null) {
9986 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9987 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009988 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009989 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009990 // The new default network can be newly null if and only if the old default
9991 // network doesn't satisfy the default request any more because it lost a
9992 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009993 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009994 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009995 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009996 }
9997 }
9998
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009999 // Now that all the callbacks have been sent, send the legacy network broadcasts
10000 // as needed. This is necessary so that legacy requests correctly bind dns
10001 // requests to this network. The legacy users are listening for this broadcast
10002 // and will generally do a dns request so they can ensureRouteToHost and if
10003 // they do that before the callbacks happen they'll use the default network.
10004 //
10005 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
10006 // callbacks, but if apps can receive the broadcast before the callback, they still might
10007 // have an inconsistent view of networking.
10008 //
10009 // This *does* introduce a race where if the user uses the new api
10010 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
10011 // they may get old info. Reverse this after the old startUsing api is removed.
10012 // This is on top of the multiple intent sequencing referenced in the todo above.
10013 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +090010014 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010015 addNetworkToLegacyTypeTracker(nai);
10016 }
The Android Open Source Project28527d22009-03-03 19:31:44 -080010017 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010018 }
10019
Chalard Jean0354d8c2021-01-12 10:58:56 +090010020 private void issueNetworkNeeds() {
10021 ensureRunningOnConnectivityServiceThread();
10022 for (final NetworkOfferInfo noi : mNetworkOffers) {
10023 issueNetworkNeeds(noi);
10024 }
10025 }
10026
10027 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
10028 ensureRunningOnConnectivityServiceThread();
10029 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10030 informOffer(nri, noi.offer, mNetworkRanker);
10031 }
10032 }
10033
10034 /**
10035 * Inform a NetworkOffer about any new situation of a request.
10036 *
10037 * This function handles updates to offers. A number of events may happen that require
10038 * updating the registrant for this offer about the situation :
10039 * • The offer itself was updated. This may lead the offer to no longer being able
10040 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
10041 * or conversely being strengthened enough to beat the satisfier (and therefore
10042 * start being needed)
10043 * • The network satisfying a request changed (including cases where the request
10044 * starts or stops being satisfied). The new network may be a stronger or weaker
10045 * match than the old one, possibly affecting whether the offer is needed.
10046 * • The network satisfying a request updated their score. This may lead the offer
10047 * to no longer be able to beat it if the current satisfier got better, or
10048 * conversely start being a good choice if the current satisfier got weaker.
10049 *
10050 * @param nri The request
10051 * @param offer The offer. This may be an updated offer.
10052 */
10053 private static void informOffer(@NonNull NetworkRequestInfo nri,
10054 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
10055 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
10056 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090010057
10058 // Multi-layer requests have a currently active request, the one being satisfied.
10059 // Since the system will try to bring up a better network than is currently satisfying
10060 // the request, NetworkProviders need to be told the offers matching the requests *above*
10061 // the currently satisfied one are needed, that the ones *below* the satisfied one are
10062 // not needed, and the offer is needed for the active request iff the offer can beat
10063 // the satisfier.
10064 // For non-multilayer requests, the logic above gracefully degenerates to only the
10065 // last case.
10066 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10067 // providers that the offer is needed for this request, until the active request is found.
10068 // In a second phase, deal with the currently active request. In a third phase, inform
10069 // the providers that offer is unneeded for the remaining requests.
10070
10071 // First phase : inform providers of all requests above the active request.
10072 int i;
10073 for (i = 0; nri.mRequests.size() > i; ++i) {
10074 final NetworkRequest request = nri.mRequests.get(i);
10075 if (activeRequest == request) break; // Found the active request : go to phase 2
10076 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10077 // Since this request is higher-priority than the one currently satisfied, if the
10078 // offer can satisfy it, the provider should try and bring up the network for sure ;
10079 // no need to even ask the ranker – an offer that can satisfy is always better than
10080 // no network. Hence tell the provider so unless it already knew.
10081 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10082 offer.onNetworkNeeded(request);
10083 }
10084 }
10085
10086 // Second phase : deal with the active request (if any)
10087 if (null != activeRequest && activeRequest.isRequest()) {
10088 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010089 // If an offer can satisfy the request, it is considered needed if it is currently
10090 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010091 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010092 && satisfier.factorySerialNumber == offer.providerId
10093 && activeRequest.canBeSatisfiedBy(offer.caps);
10094 final boolean newNeeded = currentlyServing
10095 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010096 if (newNeeded != oldNeeded) {
10097 if (newNeeded) {
10098 offer.onNetworkNeeded(activeRequest);
10099 } else {
10100 // The offer used to be able to beat the satisfier. Now it can't.
10101 offer.onNetworkUnneeded(activeRequest);
10102 }
10103 }
10104 }
10105
10106 // Third phase : inform the providers that the offer isn't needed for any request
10107 // below the active one.
10108 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10109 final NetworkRequest request = nri.mRequests.get(i);
10110 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10111 // Since this request is lower-priority than the one currently satisfied, if the
10112 // offer can satisfy it, the provider should not try and bring up the network.
10113 // Hence tell the provider so unless it already knew.
10114 if (offer.neededFor(request)) {
10115 offer.onNetworkUnneeded(request);
10116 }
10117 }
10118 }
10119
Chalard Jean61c79252019-11-07 23:07:32 +090010120 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10121 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10122 NetworkRequest nr = nai.requestAt(i);
10123 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10124 // legacy type tracker filters out repeat adds
10125 mLegacyTypeTracker.add(nr.legacyType, nai);
10126 }
10127 }
10128
10129 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010130 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010131 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10132 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10133 if (nai.isVPN()) {
10134 mLegacyTypeTracker.add(TYPE_VPN, nai);
10135 }
10136 }
10137
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010138 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010139 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010140 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010141 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010142 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010143 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010144
Chalard Jean254bd162022-08-25 13:04:51 +090010145 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010146 // Don't repeat publish.
10147 if (newInetCondition == mDefaultInetConditionPublished) return;
10148
10149 mDefaultInetConditionPublished = newInetCondition;
10150 sendInetConditionBroadcast(nai.networkInfo);
10151 }
10152
Chalard Jeand61375d2020-01-14 22:46:36 +090010153 @NonNull
10154 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10155 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010156 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010157 final boolean suspended =
10158 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10159 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10160 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10161 // state. This is because the network could have been suspended before connecting,
10162 // or it could be disconnecting while being suspended, and in both these cases
10163 // the state should not be overridden. Note that the only detailed state that
10164 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10165 // worry about multiple different substates of CONNECTED.
10166 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10167 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010168 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10169 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10170 // network agent is created, then goes to suspended, then goes out of suspended without
10171 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010172 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010173 ? NetworkInfo.DetailedState.CONNECTED
10174 : NetworkInfo.DetailedState.CONNECTING,
10175 info.getReason(),
10176 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010177 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010178 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010179 return newInfo;
10180 }
10181
10182 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10183 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10184
Erik Kline99f301b2017-02-15 19:59:17 +090010185 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010186 NetworkInfo oldInfo = null;
10187 synchronized (networkAgent) {
10188 oldInfo = networkAgent.networkInfo;
10189 networkAgent.networkInfo = newInfo;
10190 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010191
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010192 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010193 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10194 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010195 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010196
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010197 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010198 // A network that has just connected has zero requests and is thus a foreground network.
10199 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10200
Luke Huangfdd11f82019-04-09 18:41:49 +080010201 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010202
10203 networkAgent.setCreated();
10204
10205 // If the network is created immediately on register, then apply the LinkProperties now.
10206 // Otherwise, this is done further down when the network goes into connected state.
10207 // Applying the LinkProperties means that the network is ready to carry traffic -
10208 // interfaces and routing rules have been added, DNS servers programmed, etc.
10209 // For VPNs, this must be done before the capabilities are updated, because as soon as
10210 // that happens, UIDs are routed to the network.
10211 if (shouldCreateNetworksImmediately()) {
10212 applyInitialLinkProperties(networkAgent);
10213 }
10214
10215 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10216 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010217 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010218 // Initialize the network's capabilities to their starting values according to the
10219 // underlying networks. This ensures that the capabilities are correct before
10220 // anything happens to the network.
10221 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010222 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010223 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010224 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010225 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010226 }
10227
Chalard Jean254bd162022-08-25 13:04:51 +090010228 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10229 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010230
lucaslin45e639b2019-04-03 17:09:28 +080010231 // NetworkCapabilities need to be set before sending the private DNS config to
10232 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010233 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10234
Erik Kline9a62f012018-03-21 07:18:33 -070010235 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010236 if (!shouldCreateNetworksImmediately()) {
10237 applyInitialLinkProperties(networkAgent);
10238 } else {
10239 // The network was created when the agent registered, and the LinkProperties are
10240 // already up-to-date. However, updateLinkProperties also makes some changes only
10241 // when the network connects. Apply those changes here. On T and below these are
10242 // handled by the applyInitialLinkProperties call just above.
10243 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10244 // If something depends on both LinkProperties and connected state, it should be in
10245 // this method as well.
10246 networkAgent.clatd.update();
10247 updateProxy(networkAgent.linkProperties, null);
10248 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010249
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010250 // If a rate limit has been configured and is applicable to this network (network
10251 // provides internet connectivity), apply it. The tc police filter cannot be attached
10252 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
Chalard Jean2fb66f12023-08-25 12:50:37 +090010253 // updateInterfaces -> RoutingCoordinatorManager#addInterfaceToNetwork
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010254 // Note: in case of a system server crash, the NetworkController constructor in netd
10255 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10256 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10257 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10258 mIngressRateLimit);
10259 }
10260
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010261 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10262 // command must be sent after updating LinkProperties to maximize chances of
10263 // NetworkMonitor seeing the correct LinkProperties when starting.
10264 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010265 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010266 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010267 }
Chalard Jeand4900722022-02-06 12:25:38 +090010268 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10269 params.networkAgentConfig = networkAgent.networkAgentConfig;
10270 params.networkCapabilities = networkAgent.networkCapabilities;
10271 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10272 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010273 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10274 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10275 // call that would cause a Log.wtf to be emitted from the system_server process, and
10276 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10277 // process to check the interface version, just use an SDK check. NetworkStack will
10278 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010279 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010280 networkAgent.networkMonitor().notifyNetworkConnected(params);
10281 } else {
10282 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10283 params.networkCapabilities);
10284 }
Chalard Jean0f141332023-06-05 19:26:17 +090010285 final long evaluationDelay;
10286 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10287 // If the network is anything other than pure wifi, use the default timeout.
10288 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10289 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10290 // If the network is explicitly selected, use the default timeout because it's
10291 // shorter and the user is likely staring at the screen expecting it to validate
10292 // right away.
10293 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10294 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10295 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10296 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10297 } else {
10298 // It's wifi, automatically connected, and bad wifi is preferred : use the
10299 // longer timeout to avoid the device switching to captive portals with bad
10300 // signal or very slow response.
10301 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10302 }
10303 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010304
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010305 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10306 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10307 // capabilities, so it only needs to be done once on initial connect, not every time the
10308 // network's capabilities change. Note that we do this before rematching the network,
10309 // so we could decide to tear it down immediately afterwards. That's fine though - on
10310 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10311 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010312 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010313
junyulai0ac374f2020-12-14 18:41:52 +080010314 // Before first rematching networks, put an inactivity timer without any request, this
10315 // allows {@code updateInactivityState} to update the state accordingly and prevent
10316 // tearing down for any {@code unneeded} evaluation in this period.
10317 // Note that the timer will not be rescheduled since the expiry time is
10318 // fixed after connection regardless of the network satisfying other requests or not.
10319 // But it will be removed as soon as the network satisfies a request for the first time.
10320 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10321 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010322 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010323
Paul Jensen05e85ee2014-09-11 11:00:39 -040010324 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010325 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010326
10327 // This has to happen after matching the requests, because callbacks are just requests.
10328 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010329 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010330 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010331 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010332 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010333 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010334 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010335 if (networkAgent.isVPN()) {
10336 // As the active or bound network changes for apps, broadcast the default proxy, as
10337 // apps may need to update their proxy data. This is called after disconnecting from
10338 // VPN to make sure we do not broadcast the old proxy data.
10339 // TODO(b/122649188): send the broadcast only to VPN users.
10340 mProxyTracker.sendProxyBroadcast();
10341 }
Chalard Jean254bd162022-08-25 13:04:51 +090010342 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10343 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010344 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010345 }
10346 }
10347
Chalard Jean28018572020-12-21 18:36:52 +090010348 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010349 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10350 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010351 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010352 }
10353
Erik Kline99f301b2017-02-15 19:59:17 +090010354 // Notify only this one new request of the current state. Transfer all the
10355 // current state by calling NetworkCapabilities and LinkProperties callbacks
10356 // so that callers can be guaranteed to have as close to atomicity in state
10357 // transfer as can be supported by this current API.
10358 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010359 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010360 if (nri.mPendingIntent != null) {
10361 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10362 // Attempt no subsequent state pushes where intents are involved.
10363 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010364 }
Erik Kline99f301b2017-02-15 19:59:17 +090010365
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010366 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010367 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010368 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10369 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10370 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010371 }
10372
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010373 // Notify the requests on this NAI that the network is now lingered.
10374 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010375 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010376 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10377 }
10378
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010379 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10380 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10381 return vpnBlocked
10382 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10383 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10384 }
10385
10386 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10387 if (blockedReasons == BLOCKED_REASON_NONE) {
10388 mUidBlockedReasons.delete(uid);
10389 } else {
10390 mUidBlockedReasons.put(uid, blockedReasons);
10391 }
10392 }
10393
junyulaif2c67e42018-08-07 19:50:45 +080010394 /**
10395 * Notify of the blocked state apps with a registered callback matching a given NAI.
10396 *
10397 * Unlike other callbacks, blocked status is different between each individual uid. So for
10398 * any given nai, all requests need to be considered according to the uid who filed it.
10399 *
10400 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010401 * @param oldMetered True if the previous network capabilities were metered.
10402 * @param newMetered True if the current network capabilities are metered.
10403 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10404 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010405 */
10406 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010407 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10408 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010409
10410 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10411 NetworkRequest nr = nai.requestAt(i);
10412 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010413
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010414 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10415 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10416 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010417 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010418 : oldVpnBlocked;
10419
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010420 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10421 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10422 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010423 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010424 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010425 }
10426 }
10427 }
10428
10429 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010430 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010431 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010432 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010433 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010434 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010435 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010436 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010437 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010438
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010439 final int oldBlockedState = getBlockedState(
10440 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10441 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10442 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010443 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010444 }
junyulaif2c67e42018-08-07 19:50:45 +080010445 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10446 NetworkRequest nr = nai.requestAt(i);
10447 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010448 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010449 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10450 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010451 }
10452 }
10453 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010454 }
10455
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010456 @VisibleForTesting
10457 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010458 // The NetworkInfo we actually send out has no bearing on the real
10459 // state of affairs. For example, if the default connection is mobile,
10460 // and a request for HIPRI has just gone away, we need to pretend that
10461 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10462 // the state to DISCONNECTED, even though the network is of type MOBILE
10463 // and is still connected.
10464 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10465 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010466 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010467 if (state != DetailedState.DISCONNECTED) {
10468 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010469 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010470 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010471 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010472 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10473 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10474 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10475 if (info.isFailover()) {
10476 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10477 nai.networkInfo.setFailover(false);
10478 }
10479 if (info.getReason() != null) {
10480 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10481 }
10482 if (info.getExtraInfo() != null) {
10483 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10484 }
10485 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010486 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010487 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010488 if (newDefaultAgent != null) {
10489 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10490 newDefaultAgent.networkInfo);
10491 } else {
10492 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10493 }
10494 }
10495 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10496 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010497 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010498 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010499 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010500 }
10501 }
10502 }
10503
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010504 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010505 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010506 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010507 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010508 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010509 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10510 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010511 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10512 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010513 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010514 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010515 } else {
10516 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10517 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010518 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010519 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010520
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010521 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10522 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10523 }
10524
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010525 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010526 * Returns the list of all interfaces that could be used by network traffic that does not
10527 * explicitly specify a network. This includes the default network, but also all VPNs that are
10528 * currently connected.
10529 *
10530 * Must be called on the handler thread.
10531 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010532 @NonNull
10533 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010534 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010535 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010536 final Set<Integer> activeNetIds = new ArraySet<>();
10537 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10538 if (nri.isBeingSatisfied()) {
10539 activeNetIds.add(nri.getSatisfier().network().netId);
10540 }
10541 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010542 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010543 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010544 defaultNetworks.add(nai.network);
10545 }
10546 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010547 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010548 }
10549
10550 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010551 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10552 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010553 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010554 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010555 ensureRunningOnConnectivityServiceThread();
10556 String activeIface = null;
10557 LinkProperties activeLinkProperties = getActiveLinkProperties();
10558 if (activeLinkProperties != null) {
10559 activeIface = activeLinkProperties.getInterfaceName();
10560 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010561
junyulai2050bed2021-01-23 09:46:34 +080010562 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010563 try {
junyulaide41fc22021-01-22 22:46:01 +080010564 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010565 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010566 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10567 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010568 } catch (Exception ignored) {
10569 }
10570 }
10571
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010572 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010573 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010574 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010575 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010576 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010577
10578 if (!TextUtils.isEmpty(settingUrl)) {
10579 return settingUrl;
10580 }
10581
10582 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010583 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010584 if (!TextUtils.isEmpty(settingUrl)) {
10585 return settingUrl;
10586 }
10587
10588 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010589 }
10590
10591 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010592 public void startNattKeepalive(Network network, int intervalSeconds,
10593 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010594 enforceKeepalivePermission();
10595 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010596 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010597 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10598 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010599 // false and set the underpinned network to null because there is no way and no
10600 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10601 // deprecated method.
10602 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010603 }
10604
10605 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010606 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010607 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010608 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010609 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010610 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010611 mKeepaliveTracker.startNattKeepalive(
10612 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010613 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10614 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010615 } finally {
10616 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10617 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010618 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10619 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010620 }
10621 }
junyulaid05a1922019-01-15 11:32:44 +080010622 }
10623
10624 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010625 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010626 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010627 try {
10628 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010629 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010630 mKeepaliveTracker.startTcpKeepalive(
10631 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10632 } finally {
10633 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10634 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010635 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10636 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010637 }
10638 }
junyulai0835a1e2019-01-08 20:04:33 +080010639 }
10640
10641 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010642 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010643 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010644 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10645 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010646 }
10647
10648 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090010649 public int[] getSupportedKeepalives() {
10650 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10651 // Backwards compatibility with CTS 13
10652 android.Manifest.permission.QUERY_ALL_PACKAGES);
10653
10654 return BinderUtils.withCleanCallingIdentity(() ->
10655 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10656 }
10657
10658 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010659 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010660 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010661
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010662 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010663 final long token = Binder.clearCallingIdentity();
10664 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010665 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10666 UserHandle.getUserHandleForUid(uid))) {
10667 return;
10668 }
10669
Heemin Seogdb8489d2019-06-12 09:21:44 -070010670 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10671 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010672
10673 // Turn airplane mode off
10674 setAirplaneMode(false);
10675
10676 // restore private DNS settings to default mode (opportunistic)
10677 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10678 UserHandle.getUserHandleForUid(uid))) {
10679 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10680 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10681 }
10682
10683 Settings.Global.putString(mContext.getContentResolver(),
10684 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010685 } finally {
10686 Binder.restoreCallingIdentity(token);
10687 }
Stuart Scottd5463642015-04-02 18:00:02 -070010688 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010689
Ricky Wai7097cc92018-01-23 04:09:45 +000010690 @Override
10691 public byte[] getNetworkWatchlistConfigHash() {
10692 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10693 if (nwm == null) {
10694 loge("Unable to get NetworkWatchlistManager");
10695 return null;
10696 }
10697 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10698 return nwm.getWatchlistConfigHash();
10699 }
10700
Hugo Benichibe0c7652016-05-31 16:28:06 +090010701 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010702 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010703 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010704 }
Hugo Benichif4210292017-04-21 15:07:12 +090010705
10706 private static boolean toBool(int encodedBoolean) {
10707 return encodedBoolean != 0; // Only 0 means false.
10708 }
10709
10710 private static int encodeBool(boolean b) {
10711 return b ? 1 : 0;
10712 }
mswest4632928412018-03-12 10:34:34 -070010713
10714 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010715 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10716 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10717 @NonNull String[] args) {
10718 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10719 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010720 }
10721
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010722 private Boolean parseBooleanArgument(final String arg) {
10723 if ("true".equals(arg)) {
10724 return true;
10725 } else if ("false".equals(arg)) {
10726 return false;
10727 } else {
10728 return null;
10729 }
10730 }
10731
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010732 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010733 @Override
10734 public int onCommand(String cmd) {
10735 if (cmd == null) {
10736 return handleDefaultCommands(cmd);
10737 }
10738 final PrintWriter pw = getOutPrintWriter();
10739 try {
10740 switch (cmd) {
10741 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010742 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
10743 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070010744 final String action = getNextArg();
10745 if ("enable".equals(action)) {
10746 setAirplaneMode(true);
10747 return 0;
10748 } else if ("disable".equals(action)) {
10749 setAirplaneMode(false);
10750 return 0;
10751 } else if (action == null) {
10752 final ContentResolver cr = mContext.getContentResolver();
10753 final int enabled = Settings.Global.getInt(cr,
10754 Settings.Global.AIRPLANE_MODE_ON);
10755 pw.println(enabled == 0 ? "disabled" : "enabled");
10756 return 0;
10757 } else {
10758 onHelp();
10759 return -1;
10760 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010761 case "set-chain3-enabled": {
10762 final Boolean enabled = parseBooleanArgument(getNextArg());
10763 if (null == enabled) {
10764 onHelp();
10765 return -1;
10766 }
10767 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
10768 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
10769 enabled);
10770 return 0;
10771 }
10772 case "get-chain3-enabled": {
10773 final boolean chainEnabled = getFirewallChainEnabled(
10774 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
10775 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
10776 return 0;
10777 }
10778 case "set-package-networking-enabled": {
10779 final Boolean enabled = parseBooleanArgument(getNextArg());
10780 final String packageName = getNextArg();
10781 if (null == enabled || null == packageName) {
10782 onHelp();
10783 return -1;
10784 }
10785 // Throws NameNotFound if the package doesn't exist.
10786 final int appId = setPackageFirewallRule(
10787 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
10788 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
10789 final String msg = (enabled ? "Enabled" : "Disabled")
10790 + " networking for " + packageName + ", appId " + appId;
10791 Log.i(TAG, msg);
10792 pw.println(msg);
10793 return 0;
10794 }
10795 case "get-package-networking-enabled": {
10796 final String packageName = getNextArg();
10797 final int rule = getPackageFirewallRule(
10798 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
10799 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
10800 pw.println(packageName + ":" + "allow");
10801 } else if (FIREWALL_RULE_DENY == rule) {
10802 pw.println(packageName + ":" + "deny");
10803 } else {
10804 throw new IllegalStateException("Unknown rule " + rule + " for package "
10805 + packageName);
10806 }
10807 return 0;
10808 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010809 case "reevaluate":
10810 // Usage : adb shell cmd connectivity reevaluate <netId>
10811 // If netId is omitted, then reevaluate the default network
10812 final String netId = getNextArg();
10813 final NetworkAgentInfo nai;
10814 if (null == netId) {
10815 // Note that the command is running on the wrong thread to call this,
10816 // so this could in principle return stale data. But it can't crash.
10817 nai = getDefaultNetwork();
10818 } else {
10819 // If netId can't be parsed, this throws NumberFormatException, which
10820 // is passed back to adb who prints it.
10821 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10822 }
10823 if (null == nai) {
10824 pw.println("Unknown network (net ID not found or no default network)");
10825 return 0;
10826 }
10827 Log.d(TAG, "Reevaluating network " + nai.network);
10828 reportNetworkConnectivity(nai.network, !nai.isValidated());
10829 return 0;
Junyu Lai452e4642023-10-05 17:21:19 +080010830 case "bpf-get-cgroup-program-id": {
10831 // Usage : adb shell cmd connectivity bpf-get-cgroup-program-id <type>
10832 // Get cgroup bpf program Id for the given type. See BpfUtils#getProgramId
10833 // for more detail.
10834 // If type can't be parsed, this throws NumberFormatException, which
10835 // is passed back to adb who prints it.
10836 final int type = Integer.parseInt(getNextArg());
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +000010837 final int ret = BpfUtils.getProgramId(type);
Junyu Lai452e4642023-10-05 17:21:19 +080010838 pw.println(ret);
10839 return 0;
10840 }
mswest4632928412018-03-12 10:34:34 -070010841 default:
10842 return handleDefaultCommands(cmd);
10843 }
10844 } catch (Exception e) {
10845 pw.println(e);
10846 }
10847 return -1;
10848 }
10849
10850 @Override
10851 public void onHelp() {
10852 PrintWriter pw = getOutPrintWriter();
10853 pw.println("Connectivity service commands:");
10854 pw.println(" help");
10855 pw.println(" Print this help text.");
10856 pw.println(" airplane-mode [enable|disable]");
10857 pw.println(" Turn airplane mode on or off.");
10858 pw.println(" airplane-mode");
10859 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010860 pw.println(" set-chain3-enabled [true|false]");
10861 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
10862 pw.println(" get-chain3-enabled");
10863 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
10864 pw.println(" set-package-networking-enabled [true|false] [package name]");
10865 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
10866 + " no effect if the chain is disabled.");
10867 pw.println(" get-package-networking-enabled [package name]");
10868 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
mswest4632928412018-03-12 10:34:34 -070010869 }
10870 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010871
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010872 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010873 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10874 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10875 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010876 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010877 }
10878
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010879 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10880 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010881 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10882 final TransportInfo newInfo = nc.getTransportInfo();
10883 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10884 return;
10885 }
10886 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010887 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010888 }
10889 }
10890
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010891 /**
10892 * @param connectionInfo the connection to resolve.
10893 * @return {@code uid} if the connection is found and the app has permission to observe it
10894 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10895 * connection is not found.
10896 */
10897 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010898 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10899 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10900 }
10901
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010902 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010903 connectionInfo.local, connectionInfo.remote);
10904
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010905 if (uid == INVALID_UID) return uid; // Not found.
10906
10907 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10908 // VPN, if any, that applies to the UID that owns the connection.
10909 if (checkNetworkStackPermission()) return uid;
10910
10911 final NetworkAgentInfo vpn = getVpnForUid(uid);
10912 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010913 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010914 return INVALID_UID;
10915 }
10916
10917 return uid;
10918 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010919
Benedict Wong493e04b2018-11-09 14:45:34 -080010920 /**
10921 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10922 *
10923 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10924 */
10925 @Override
10926 public IBinder startOrGetTestNetworkService() {
10927 synchronized (mTNSLock) {
10928 TestNetworkService.enforceTestNetworkPermissions(mContext);
10929
10930 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010931 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010932 }
10933
10934 return mTNS;
10935 }
10936 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010937
Cody Kesting73708bf2019-12-18 10:57:50 -080010938 /**
10939 * Handler used for managing all Connectivity Diagnostics related functions.
10940 *
10941 * @see android.net.ConnectivityDiagnosticsManager
10942 *
10943 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10944 */
10945 @VisibleForTesting
10946 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010947 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10948
Cody Kesting73708bf2019-12-18 10:57:50 -080010949 /**
10950 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10951 * android.net.ConnectivityDiagnosticsManager}.
10952 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10953 * NetworkRequestInfo to be registered
10954 */
10955 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10956
10957 /**
10958 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10959 * android.net.ConnectivityDiagnosticsManager}.
10960 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10961 * arg1 = the uid of the caller
10962 */
10963 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10964
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010965 /**
10966 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010967 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010968 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10969 * NetworkMonitor.
10970 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010971 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010972 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010973
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010974 /**
10975 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10976 * been detected on the network.
10977 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10978 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10979 * arg2 = NetID.
10980 * data = PersistableBundle of extras passed from NetworkMonitor.
10981 */
10982 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10983
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010984 /**
10985 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10986 * the platform. This event will invoke {@link
10987 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10988 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070010989 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010990 */
10991 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
10992
Cody Kesting73708bf2019-12-18 10:57:50 -080010993 private ConnectivityDiagnosticsHandler(Looper looper) {
10994 super(looper);
10995 }
10996
10997 @Override
10998 public void handleMessage(Message msg) {
10999 switch (msg.what) {
11000 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11001 handleRegisterConnectivityDiagnosticsCallback(
11002 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
11003 break;
11004 }
11005 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11006 handleUnregisterConnectivityDiagnosticsCallback(
11007 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
11008 break;
11009 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011010 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011011 final ConnectivityReportEvent reportEvent =
11012 (ConnectivityReportEvent) msg.obj;
11013
Aaron Huang959d3642021-01-21 15:47:41 +080011014 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011015 break;
11016 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011017 case EVENT_DATA_STALL_SUSPECTED: {
11018 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080011019 final Pair<Long, PersistableBundle> arg =
11020 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011021 if (nai == null) break;
11022
Aaron Huang959d3642021-01-21 15:47:41 +080011023 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011024 break;
11025 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011026 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070011027 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011028 break;
11029 }
11030 default: {
11031 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
11032 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011033 }
11034 }
11035 }
11036
11037 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
11038 @VisibleForTesting
11039 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
11040 @NonNull private final IConnectivityDiagnosticsCallback mCb;
11041 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011042 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011043
11044 @VisibleForTesting
11045 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011046 @NonNull IConnectivityDiagnosticsCallback cb,
11047 @NonNull NetworkRequestInfo nri,
11048 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011049 mCb = cb;
11050 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011051 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011052 }
11053
11054 @Override
11055 public void binderDied() {
11056 log("ConnectivityDiagnosticsCallback IBinder died.");
11057 unregisterConnectivityDiagnosticsCallback(mCb);
11058 }
11059 }
11060
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011061 /**
11062 * Class used for sending information from {@link
11063 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
11064 */
11065 private static class NetworkTestedResults {
11066 private final int mNetId;
11067 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011068 @Nullable private final String mRedirectUrl;
11069
11070 private NetworkTestedResults(
11071 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
11072 mNetId = netId;
11073 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011074 mRedirectUrl = redirectUrl;
11075 }
11076 }
11077
11078 /**
11079 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11080 * ConnectivityDiagnosticsHandler}.
11081 */
11082 private static class ConnectivityReportEvent {
11083 private final long mTimestampMillis;
11084 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011085 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011086
Aaron Huang959d3642021-01-21 15:47:41 +080011087 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11088 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011089 mTimestampMillis = timestampMillis;
11090 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011091 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011092 }
11093 }
11094
Cody Kestingf1120be2020-08-03 18:01:40 -070011095 /**
11096 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11097 * ConnectivityDiagnosticsHandler}.
11098 */
11099 private static class ReportedNetworkConnectivityInfo {
11100 public final boolean hasConnectivity;
11101 public final boolean isNetworkRevalidating;
11102 public final int reporterUid;
11103 @NonNull public final NetworkAgentInfo nai;
11104
11105 private ReportedNetworkConnectivityInfo(
11106 boolean hasConnectivity,
11107 boolean isNetworkRevalidating,
11108 int reporterUid,
11109 @NonNull NetworkAgentInfo nai) {
11110 this.hasConnectivity = hasConnectivity;
11111 this.isNetworkRevalidating = isNetworkRevalidating;
11112 this.reporterUid = reporterUid;
11113 this.nai = nai;
11114 }
11115 }
11116
Cody Kesting73708bf2019-12-18 10:57:50 -080011117 private void handleRegisterConnectivityDiagnosticsCallback(
11118 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11119 ensureRunningOnConnectivityServiceThread();
11120
11121 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011122 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011123 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11124
James Mattis64b8b0f2020-11-24 17:40:49 -080011125 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11126 // confusing for these networks to change when an NRI is satisfied in another layer.
11127 if (nri.isMultilayerRequest()) {
11128 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11129 + "network requests.");
11130 }
11131
Cody Kesting73708bf2019-12-18 10:57:50 -080011132 // This means that the client registered the same callback multiple times. Do
11133 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011134 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011135 if (VDBG) log("Diagnostics callback is already registered");
11136
11137 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11138 // incremented when the NetworkRequestInfo is created as part of
11139 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011140 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011141 return;
11142 }
11143
Cody Kesting31f1ff62020-03-05 10:46:02 -080011144 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011145
11146 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011147 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011148 } catch (RemoteException e) {
11149 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011150 return;
11151 }
11152
11153 // Once registered, provide ConnectivityReports for matching Networks
11154 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11155 synchronized (mNetworkForNetId) {
11156 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11157 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011158 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11159 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011160 matchingNetworks.add(nai);
11161 }
11162 }
11163 }
11164 for (final NetworkAgentInfo nai : matchingNetworks) {
11165 final ConnectivityReport report = nai.getConnectivityReport();
11166 if (report == null) {
11167 continue;
11168 }
11169 if (!checkConnectivityDiagnosticsPermissions(
11170 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11171 continue;
11172 }
11173
11174 try {
11175 cb.onConnectivityReportAvailable(report);
11176 } catch (RemoteException e) {
11177 // Exception while sending the ConnectivityReport. Move on to the next network.
11178 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011179 }
11180 }
11181
11182 private void handleUnregisterConnectivityDiagnosticsCallback(
11183 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11184 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011185 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011186
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011187 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11188 mConnectivityDiagnosticsCallbacks.remove(iCb);
11189 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011190 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11191 return;
11192 }
11193
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011194 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011195
Cody Kesting70fa2b22020-12-02 12:16:56 -080011196 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11197 // (if the Binder died)
11198 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11199 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011200 return;
11201 }
11202
Cody Kesting46cb1672020-03-04 13:35:20 -080011203 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11204 // incremented when the NetworkRequestInfo is created as part of
11205 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011206 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011207
Cody Kesting31f1ff62020-03-05 10:46:02 -080011208 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011209 }
11210
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011211 private void handleNetworkTestedWithExtras(
11212 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11213 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011214 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011215 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011216 final ConnectivityReport report =
11217 new ConnectivityReport(
11218 reportEvent.mNai.network,
11219 reportEvent.mTimestampMillis,
11220 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011221 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011222 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011223 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011224
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011225 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011226 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011227 for (final IConnectivityDiagnosticsCallback cb : results) {
11228 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011229 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011230 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011231 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011232 }
11233 }
11234 }
11235
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011236 private void handleDataStallSuspected(
11237 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11238 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011239 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011240 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011241 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011242 new DataStallReport(
11243 nai.network,
11244 timestampMillis,
11245 detectionMethod,
11246 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011247 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011248 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011249 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011250 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011251 for (final IConnectivityDiagnosticsCallback cb : results) {
11252 try {
11253 cb.onDataStallSuspected(report);
11254 } catch (RemoteException ex) {
11255 loge("Error invoking onDataStallSuspected", ex);
11256 }
11257 }
11258 }
11259
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011260 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011261 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11262 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11263 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11264
11265 // If the Network is being re-validated as a result of this call to
11266 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11267 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011268 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011269 getMatchingPermissionedCallbacks(
11270 nai,
11271 reportedNetworkConnectivityInfo.isNetworkRevalidating
11272 ? Process.INVALID_UID
11273 : reportedNetworkConnectivityInfo.reporterUid);
11274
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011275 for (final IConnectivityDiagnosticsCallback cb : results) {
11276 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011277 cb.onNetworkConnectivityReported(
11278 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011279 } catch (RemoteException ex) {
11280 loge("Error invoking onNetworkConnectivityReported", ex);
11281 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011282
11283 // If the Network isn't re-validating, also provide the cached report. If there is no
11284 // cached report, the Network is still being validated and a report will be sent once
11285 // validation is complete. Note that networks which never undergo validation will still
11286 // have a cached ConnectivityReport with RESULT_SKIPPED.
11287 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11288 try {
11289 cb.onConnectivityReportAvailable(cachedReport);
11290 } catch (RemoteException ex) {
11291 loge("Error invoking onConnectivityReportAvailable", ex);
11292 }
11293 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011294 }
11295 }
11296
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011297 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011298 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11299 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011300 sanitized.setUids(null);
11301 sanitized.setAdministratorUids(new int[0]);
11302 sanitized.setOwnerUid(Process.INVALID_UID);
11303 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011304 }
11305
Cody Kestingf1120be2020-08-03 18:01:40 -070011306 /**
11307 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11308 *
11309 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11310 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011311 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011312 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011313 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011314 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011315 mConnectivityDiagnosticsCallbacks.entrySet()) {
11316 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11317 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011318
James Mattis64b8b0f2020-11-24 17:40:49 -080011319 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011320 if (!nai.satisfies(nri.mRequests.get(0))) {
11321 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011322 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011323
11324 // UID for this callback must either be:
11325 // - INVALID_UID (which sends callbacks to all UIDs), or
11326 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11327 // notified as a result)
11328 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11329 continue;
11330 }
11331
11332 if (!checkConnectivityDiagnosticsPermissions(
11333 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11334 continue;
11335 }
11336
11337 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011338 }
11339 return results;
11340 }
11341
Cody Kesting7474f672021-05-11 14:22:40 -070011342 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11343 @NonNull NetworkAgentInfo nai) {
11344 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11345 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11346 }
11347
Cody Kesting160ef392021-05-05 13:17:22 -070011348 private boolean hasLocationPermission(String packageName, int uid) {
11349 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11350 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11351 // call in a try-catch.
11352 try {
11353 if (!mLocationPermissionChecker.checkLocationPermission(
11354 packageName, null /* featureId */, uid, null /* message */)) {
11355 return false;
11356 }
11357 } catch (SecurityException e) {
11358 return false;
11359 }
11360
11361 return true;
11362 }
11363
11364 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11365 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011366 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011367 && virtual.networkCapabilities.getOwnerUid() == uid
11368 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11369 return true;
11370 }
11371 }
11372
11373 return false;
11374 }
11375
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011376 @VisibleForTesting
11377 boolean checkConnectivityDiagnosticsPermissions(
11378 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
11379 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
11380 return true;
11381 }
11382
Cody Kesting160ef392021-05-05 13:17:22 -070011383 // Administrator UIDs also contains the Owner UID
11384 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11385 if (!CollectionUtils.contains(administratorUids, callbackUid)
11386 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011387 return false;
11388 }
11389
Cody Kesting7474f672021-05-11 14:22:40 -070011390 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11391 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011392 }
11393
Cody Kestingd199a9d2019-12-17 12:55:28 -080011394 @Override
11395 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011396 @NonNull IConnectivityDiagnosticsCallback callback,
11397 @NonNull NetworkRequest request,
11398 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011399 Objects.requireNonNull(callback, "callback must not be null");
11400 Objects.requireNonNull(request, "request must not be null");
11401 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11402
Cody Kesting73708bf2019-12-18 10:57:50 -080011403 if (request.legacyType != TYPE_NONE) {
11404 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11405 + " Please use NetworkCapabilities instead.");
11406 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011407 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011408 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011409
11410 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11411 // and administrator uids to be safe.
11412 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011413 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011414
11415 final NetworkRequest requestWithId =
11416 new NetworkRequest(
11417 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11418
11419 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11420 //
11421 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11422 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11423 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011424 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011425 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011426 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011427
11428 mConnectivityDiagnosticsHandler.sendMessage(
11429 mConnectivityDiagnosticsHandler.obtainMessage(
11430 ConnectivityDiagnosticsHandler
11431 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11432 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011433 }
11434
11435 @Override
11436 public void unregisterConnectivityDiagnosticsCallback(
11437 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011438 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011439 mConnectivityDiagnosticsHandler.sendMessage(
11440 mConnectivityDiagnosticsHandler.obtainMessage(
11441 ConnectivityDiagnosticsHandler
11442 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011443 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011444 0,
11445 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011446 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011447
Yan Yanfe96dde2022-12-05 23:00:01 +000011448 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11449 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11450 if (underlyingNetworks == null) return false;
11451
11452 for (Network network : underlyingNetworks) {
11453 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11454 return true;
11455 }
11456 }
11457 return false;
11458 }
11459
Cody Kestingf53a0752020-04-15 12:33:28 -070011460 @Override
11461 public void simulateDataStall(int detectionMethod, long timestampMillis,
11462 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011463 Objects.requireNonNull(network, "network must not be null");
11464 Objects.requireNonNull(extras, "extras must not be null");
11465
paulhu3ffffe72021-09-16 10:15:22 +080011466 enforceAnyPermissionOf(mContext,
11467 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011468 android.Manifest.permission.NETWORK_STACK);
11469 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011470 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11471 throw new SecurityException(
11472 "Data Stall simulation is only possible for test networks or networks built on"
11473 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011474 }
11475
11476 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011477 if (nai == null
11478 || (nai.creatorUid != mDeps.getCallingUid()
11479 && nai.creatorUid != Process.SYSTEM_UID)) {
11480 throw new SecurityException(
11481 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011482 }
11483
Cody Kesting652e3ec2020-05-21 12:08:21 -070011484 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11485 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11486 // Data Stall information as a DataStallReportParcelable and passing to
11487 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11488 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011489 final DataStallReportParcelable p = new DataStallReportParcelable();
11490 p.timestampMillis = timestampMillis;
11491 p.detectionMethod = detectionMethod;
11492
11493 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11494 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11495 }
11496 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11497 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11498 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11499 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11500 }
11501
Serik Beketayevec8ad212020-12-07 22:43:07 -080011502 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011503 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011504
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011505 /**
11506 * Class to hold the information for network activity change event from idle timers
11507 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
11508 */
11509 private static final class NetworkActivityParams {
11510 public final boolean isActive;
11511 // Label used for idle timer. Transport type is used as label.
11512 // label is int since NMS was using the identifier as int, and it has not been changed
11513 public final int label;
11514 public final long timestampNs;
11515 // Uid represents the uid that was responsible for waking the radio.
11516 // -1 for no uid and uid is -1 if isActive is false.
11517 public final int uid;
11518
11519 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
11520 this.isActive = isActive;
11521 this.label = label;
11522 this.timestampNs = timestampNs;
11523 this.uid = uid;
11524 }
11525 }
11526
lucaslin66f44212021-02-23 01:12:55 +080011527 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11528 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011529 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080011530 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011531 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
11532 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080011533 }
lucaslin37a16d92021-01-21 19:48:09 +080011534
11535 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011536 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011537 mHandler.post(() -> {
11538 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011539 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011540 }
11541 });
lucaslin37a16d92021-01-21 19:48:09 +080011542 }
11543
11544 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011545 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011546 mHandler.post(() -> {
11547 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011548 nai.clatd.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011549 }
11550 });
lucaslin66f44212021-02-23 01:12:55 +080011551 }
11552 }
11553
lucaslin1a8b4c62021-01-21 02:02:55 +080011554 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11555
11556 /**
11557 * Class used for updating network activity tracking with netd and notify network activity
11558 * changes.
11559 */
11560 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011561 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011562 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011563 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011564 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080011565 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11566 new RemoteCallbackList<>();
11567 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090011568 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011569 // If there is no default network, default network is considered active to keep the existing
11570 // behavior. Initial value is used until first connect to the default network.
11571 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011572 // Key is netId. Value is configured idle timer information.
11573 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080011574
Chalard Jean46bfbf02022-02-02 00:56:25 +090011575 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011576 public final int timeout;
11577 public final int transportType;
11578
11579 IdleTimerParams(int timeout, int transport) {
11580 this.timeout = timeout;
11581 this.transportType = transport;
11582 }
11583 }
11584
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011585 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011586 @NonNull Handler handler) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011587 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011588 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011589 mHandler = handler;
11590 }
11591
11592 private void ensureRunningOnConnectivityServiceThread() {
11593 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
11594 throw new IllegalStateException("Not running on ConnectivityService thread: "
11595 + Thread.currentThread().getName());
11596 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011597 }
11598
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011599 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011600 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011601 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011602 // This activity change is not for the current default network.
11603 // This can happen if netd callback post activity change event message but
11604 // the default network is lost before processing this message.
11605 return;
11606 }
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011607 sendDataActivityBroadcast(transportTypeToLegacyType(activityParams.label),
11608 activityParams.isActive, activityParams.timestampNs);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011609 mIsDefaultNetworkActive = activityParams.isActive;
11610 if (mIsDefaultNetworkActive) {
11611 reportNetworkActive();
lucaslin66f44212021-02-23 01:12:55 +080011612 }
11613 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011614
lucaslin1193a5d2021-01-21 02:04:15 +080011615 private void reportNetworkActive() {
11616 final int length = mNetworkActivityListeners.beginBroadcast();
11617 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
11618 try {
11619 for (int i = 0; i < length; i++) {
11620 try {
11621 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
11622 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011623 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080011624 }
11625 }
11626 } finally {
11627 mNetworkActivityListeners.finishBroadcast();
11628 }
11629 }
11630
lucaslin1a8b4c62021-01-21 02:02:55 +080011631 // This is deprecated and only to support legacy use cases.
11632 private int transportTypeToLegacyType(int type) {
11633 switch (type) {
11634 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011635 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080011636 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011637 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080011638 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011639 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080011640 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011641 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080011642 default:
11643 loge("Unexpected transport in transportTypeToLegacyType: " + type);
11644 }
11645 return ConnectivityManager.TYPE_NONE;
11646 }
11647
11648 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
11649 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
11650 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
11651 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
11652 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
11653 final long ident = Binder.clearCallingIdentity();
11654 try {
11655 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
11656 RECEIVE_DATA_ACTIVITY_CHANGE,
11657 null /* resultReceiver */,
11658 null /* scheduler */,
11659 0 /* initialCode */,
11660 null /* initialData */,
11661 null /* initialExtra */);
11662 } finally {
11663 Binder.restoreCallingIdentity(ident);
11664 }
11665 }
11666
11667 /**
11668 * Setup data activity tracking for the given network.
11669 *
11670 * Every {@code setupDataActivityTracking} should be paired with a
11671 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090011672 *
11673 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080011674 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090011675 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011676 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011677 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080011678
11679 final int timeout;
11680 final int type;
11681
11682 if (networkAgent.networkCapabilities.hasTransport(
11683 NetworkCapabilities.TRANSPORT_CELLULAR)) {
11684 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011685 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080011686 10);
11687 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11688 } else if (networkAgent.networkCapabilities.hasTransport(
11689 NetworkCapabilities.TRANSPORT_WIFI)) {
11690 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011691 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080011692 15);
11693 type = NetworkCapabilities.TRANSPORT_WIFI;
11694 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011695 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080011696 }
11697
lucaslinb961efc2021-01-21 02:03:17 +080011698 updateRadioPowerState(true /* isActive */, type);
11699
lucaslin1a8b4c62021-01-21 02:02:55 +080011700 if (timeout > 0 && iface != null) {
11701 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011702 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, type));
Motomu Utsumic298cf02023-05-31 12:06:12 +090011703 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
Motomu Utsumi6225d572023-05-29 15:08:57 +090011704 return true;
lucaslin1a8b4c62021-01-21 02:02:55 +080011705 } catch (Exception e) {
11706 // You shall not crash!
11707 loge("Exception in setupDataActivityTracking " + e);
11708 }
11709 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011710 return false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011711 }
11712
11713 /**
11714 * Remove data activity tracking when network disconnects.
11715 */
11716 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
11717 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011718 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080011719 final NetworkCapabilities caps = networkAgent.networkCapabilities;
11720
lucaslinb961efc2021-01-21 02:03:17 +080011721 if (iface == null) return;
11722
11723 final int type;
11724 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
11725 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11726 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
11727 type = NetworkCapabilities.TRANSPORT_WIFI;
11728 } else {
11729 return; // do not track any other networks
11730 }
11731
11732 try {
11733 updateRadioPowerState(false /* isActive */, type);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011734 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011735 if (params == null) {
11736 // IdleTimer is not added if the configured timeout is 0 or negative value
11737 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080011738 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011739 mActiveIdleTimers.remove(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011740 // The call fails silently if no idle timer setup for this interface
11741 mNetd.idletimerRemoveInterface(iface, params.timeout,
11742 Integer.toString(params.transportType));
lucaslinb961efc2021-01-21 02:03:17 +080011743 } catch (Exception e) {
11744 // You shall not crash!
11745 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080011746 }
11747 }
11748
Motomu Utsumi6225d572023-05-29 15:08:57 +090011749 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
11750 boolean hasIdleTimer) {
11751 if (defaultNetwork != null) {
11752 mIsDefaultNetworkActive = true;
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011753 // Callbacks are called only when the network has the idle timer.
11754 if (hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011755 reportNetworkActive();
11756 }
11757 } else {
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011758 // If there is no default network, default network is considered active to keep the
11759 // existing behavior.
11760 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090011761 }
11762 }
11763
lucaslin1a8b4c62021-01-21 02:02:55 +080011764 /**
11765 * Update data activity tracking when network state is updated.
11766 */
11767 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
11768 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011769 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi6225d572023-05-29 15:08:57 +090011770 boolean hasIdleTimer = false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011771 if (newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011772 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080011773 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011774 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
lucaslin1a8b4c62021-01-21 02:02:55 +080011775 if (oldNetwork != null) {
11776 removeDataActivityTracking(oldNetwork);
11777 }
11778 }
lucaslinb961efc2021-01-21 02:03:17 +080011779
11780 private void updateRadioPowerState(boolean isActive, int transportType) {
11781 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
11782 switch (transportType) {
11783 case NetworkCapabilities.TRANSPORT_CELLULAR:
11784 bs.reportMobileRadioPowerState(isActive, NO_UID);
11785 break;
11786 case NetworkCapabilities.TRANSPORT_WIFI:
11787 bs.reportWifiRadioPowerState(isActive, NO_UID);
11788 break;
11789 default:
11790 logw("Untracked transport type:" + transportType);
11791 }
11792 }
lucaslin1193a5d2021-01-21 02:04:15 +080011793
11794 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011795 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080011796 }
11797
11798 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
11799 mNetworkActivityListeners.register(l);
11800 }
11801
11802 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
11803 mNetworkActivityListeners.unregister(l);
11804 }
lucaslin012f7a12021-01-21 02:04:35 +080011805
11806 public void dump(IndentingPrintWriter pw) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011807 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
11808 pw.println("Idle timers:");
11809 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011810 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
11811 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
11812 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080011813 pw.print(" timeout="); pw.print(params.timeout);
11814 pw.print(" type="); pw.println(params.transportType);
11815 }
Motomu Utsumic298cf02023-05-31 12:06:12 +090011816 } catch (Exception e) {
11817 // mActiveIdleTimers should only be accessed from handler thread, except dump().
11818 // As dump() is never called in normal usage, it would be needlessly expensive
11819 // to lock the collection only for its benefit.
11820 // Also, mActiveIdleTimers is not expected to be updated frequently.
11821 // So catching the exception and logging.
11822 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080011823 }
11824 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011825 }
James Mattis47db0582021-01-01 14:13:35 -080011826
Daniel Brightf9e945b2020-06-15 16:10:01 -070011827 /**
11828 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
11829 *
11830 * @param socketInfo the socket information
11831 * @param callback the callback to register
11832 */
11833 @Override
11834 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
11835 @NonNull final IQosCallback callback) {
11836 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
11837 if (nai == null || nai.networkCapabilities == null) {
11838 try {
11839 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
11840 } catch (final RemoteException ex) {
11841 loge("registerQosCallbackInternal: RemoteException", ex);
11842 }
11843 return;
11844 }
11845 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
11846 }
11847
11848 /**
11849 * Register a {@link IQosCallback} with base {@link QosFilter}.
11850 *
11851 * @param filter the filter to register
11852 * @param callback the callback to register
11853 * @param nai the agent information related to the filter's network
11854 */
11855 @VisibleForTesting
11856 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
11857 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011858 Objects.requireNonNull(filter, "filter must be non-null");
11859 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011860
11861 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080011862 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
11863 // on this network is unregistered when the app loses permission or b) no QoS
11864 // callbacks are sent for restricted networks unless the app currently has permission
11865 // to access restricted networks.
11866 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070011867 }
11868 mQosCallbackTracker.registerCallback(callback, filter, nai);
11869 }
11870
11871 /**
11872 * Unregisters the given callback.
11873 *
11874 * @param callback the callback to unregister
11875 */
11876 @Override
11877 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011878 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011879 mQosCallbackTracker.unregisterCallback(callback);
11880 }
James Mattis47db0582021-01-01 14:13:35 -080011881
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011882 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
11883 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
11884 // Enterprise device can be fully managed like device owner and such use case
11885 // also should be supported. Calling app check for work profile and fully managed device
11886 // is already done in DevicePolicyManager.
11887 // This check is an extra caution to be sure device is fully managed or not.
11888 final UserManager um = mContext.getSystemService(UserManager.class);
11889 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
11890 if (um.isManagedProfile(profile.getIdentifier())) {
11891 return true;
11892 }
Chalard Jeandf29a852023-05-29 17:02:43 +090011893 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011894 return false;
11895 }
11896
James Mattis45d81842021-01-10 14:24:24 -080011897 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011898 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011899 *
11900 * See the documentation for the individual preferences for a description of the supported
11901 * behaviors.
11902 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011903 * @param profile If the device owner is set, any profile is allowed.
11904 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011905 * @param preferences the list of profile network preferences for the
11906 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011907 * @param listener an optional listener to listen for completion of the operation.
11908 */
11909 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011910 public void setProfileNetworkPreferences(
11911 @NonNull final UserHandle profile,
11912 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090011913 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011914 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011915 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011916
11917 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011918 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11919 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11920 .build();
11921 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011922 }
11923
paulhu3ffffe72021-09-16 10:15:22 +080011924 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011925 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011926 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011927 }
11928 if (profile.getIdentifier() < 0) {
11929 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11930 + "UserHandle.CURRENT not supported)");
11931 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011932 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11933 throw new IllegalArgumentException("Profile must be a managed profile "
11934 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011935 }
paulhuaa0743d2021-05-26 21:56:03 +080011936
Chalard Jean0606fc82022-12-14 20:34:43 +090011937 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011938 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011939 for (final ProfileNetworkPreference preference : preferences) {
11940 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011941 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011942 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011943 switch (preference.getPreference()) {
11944 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11945 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011946 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011947 if (preference.getPreferenceEnterpriseId() != 0) {
11948 throw new IllegalArgumentException(
11949 "Invalid enterprise identifier in setProfileNetworkPreferences");
11950 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011951 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011952 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11953 blockingNonEnterprise = true;
11954 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011955 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11956 allowFallback = false;
11957 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011958 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011959 // This code is needed even though there is a check later on,
11960 // because isRangeAlreadyInPreferenceList assumes that every preference
11961 // has a UID list.
11962 if (hasDefaultPreference) {
11963 throw new IllegalArgumentException(
11964 "Default profile preference should not be set along with other "
11965 + "preference");
11966 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011967 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11968 throw new IllegalArgumentException(
11969 "Invalid enterprise identifier in setProfileNetworkPreferences");
11970 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011971 final Set<UidRange> uidRangeSet =
11972 getUidListToBeAppliedForNetworkPreference(profile, preference);
11973 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11974 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11975 } else {
11976 throw new IllegalArgumentException(
11977 "Overlapping uid range in setProfileNetworkPreferences");
11978 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011979 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011980 nc.addEnterpriseId(
11981 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011982 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11983 break;
11984 default:
11985 throw new IllegalArgumentException(
11986 "Invalid preference in setProfileNetworkPreferences");
11987 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011988 preferenceList.add(new ProfileNetworkPreferenceInfo(
11989 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011990 if (hasDefaultPreference && preferenceList.size() > 1) {
11991 throw new IllegalArgumentException(
11992 "Default profile preference should not be set along with other preference");
11993 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011994 }
11995 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011996 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011997 }
11998
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011999 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
12000 @NonNull final UserHandle profile,
12001 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
12002 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080012003 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
12004 profileNetworkPreference.getIncludedUids());
12005
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012006 if (uidRangeSet.size() > 0) {
12007 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
12008 throw new IllegalArgumentException(
12009 "Allow uid range is outside the uid range of profile.");
12010 }
12011 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080012012 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012013 profileNetworkPreference.getExcludedUids());
12014 if (disallowUidRangeSet.size() > 0) {
12015 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
12016 throw new IllegalArgumentException(
12017 "disallow uid range is outside the uid range of profile.");
12018 }
12019 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
12020 disallowUidRangeSet);
12021 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012022 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012023 uidRangeSet.add(profileUids);
12024 }
12025 }
12026 return uidRangeSet;
12027 }
12028
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012029 private boolean isEnterpriseIdentifierValid(
12030 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012031 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012032 return true;
12033 }
12034 return false;
12035 }
12036
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012037 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090012038 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012039 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090012040 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012041 // The NRI for a user should contain the request for capabilities.
12042 // If fallback to default network is needed then NRI should include
12043 // the request for the default network. Create an image of it to
12044 // have the correct UIDs in it (also a request can only be part of one NRI, because
12045 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012046 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
12047 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012048 if (pref.allowFallback) {
12049 nrs.add(createDefaultInternetRequestForTransport(
12050 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12051 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012052 if (VDBG) {
12053 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
12054 pref.capabilities.getUids()));
12055 }
12056
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012057 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080012058 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080012059 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012060 result.add(nri);
12061 }
12062 return result;
12063 }
12064
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012065 /**
12066 * Compare if the given UID range sets have the same UIDs.
12067 *
12068 */
12069 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090012070 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012071 @NonNull Set<UidRange> uidRangeSet) {
12072 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
12073 return false;
12074 }
Chalard Jean0606fc82022-12-14 20:34:43 +090012075 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012076 if (UidRangeUtils.doesRangeSetOverlap(
12077 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12078 return true;
12079 }
12080 }
12081 return false;
12082 }
12083
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012084 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012085 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012086 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012087 /*
12088 * handleSetProfileNetworkPreference is always called for single user.
12089 * preferenceList only contains preferences for different uids within the same user
12090 * (enforced by getUidListToBeAppliedForNetworkPreference).
12091 * Clear all the existing preferences for the user before applying new preferences.
12092 *
12093 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012094 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12095 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012096 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12097 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012098
paulhu74128522021-09-28 02:29:03 +000012099 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12100 addPerAppDefaultNetworkRequests(
12101 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012102 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012103
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012104 // Finally, rematch.
12105 rematchAllNetworksAndRequests();
12106
12107 if (null != listener) {
12108 try {
12109 listener.onComplete();
12110 } catch (RemoteException e) {
12111 loge("Listener for setProfileNetworkPreference has died");
12112 }
12113 }
12114 }
12115
paulhu51f77dc2021-06-07 02:34:20 +000012116 @VisibleForTesting
12117 @NonNull
12118 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12119 @NonNull final Set<Integer> uids) {
12120 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12121 if (uids.size() == 0) {
12122 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12123 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
12124 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
12125 return nris;
12126 }
12127
12128 final List<NetworkRequest> requests = new ArrayList<>();
12129 // The NRI should be comprised of two layers:
12130 // - The request for the mobile network preferred.
12131 // - The request for the default network, for fallback.
12132 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012133 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012134 requests.add(createDefaultInternetRequestForTransport(
12135 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12136 final Set<UidRange> ranges = new ArraySet<>();
12137 for (final int uid : uids) {
12138 ranges.add(new UidRange(uid, uid));
12139 }
12140 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080012141 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080012142 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000012143 return nris;
12144 }
12145
12146 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012147 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012148 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12149 addPerAppDefaultNetworkRequests(
12150 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012151 // Finally, rematch.
12152 rematchAllNetworksAndRequests();
12153 }
12154
Patrick Rohr2857ac42022-01-21 14:58:16 +010012155 private void handleIngressRateLimitChanged() {
12156 final long oldIngressRateLimit = mIngressRateLimit;
12157 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12158 mContext);
12159 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12160 if (canNetworkBeRateLimited(networkAgent)) {
12161 // If rate limit has previously been enabled, remove the old limit first.
12162 if (oldIngressRateLimit >= 0) {
12163 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12164 }
12165 if (mIngressRateLimit >= 0) {
12166 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12167 mIngressRateLimit);
12168 }
12169 }
12170 }
12171 }
12172
12173 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012174 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090012175 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012176
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012177 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12178 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12179 // internet connectivity can be rate limited.
12180 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12181 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012182 return false;
12183 }
12184
12185 final String iface = networkAgent.linkProperties.getInterfaceName();
12186 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012187 // This may happen in tests, but if there is no interface then there is nothing that
12188 // can be rate limited.
12189 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012190 return false;
12191 }
12192 return true;
12193 }
12194
James Mattis45d81842021-01-10 14:24:24 -080012195 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012196 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12197 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012198 }
12199
12200 /**
12201 * Used by automotive devices to set the network preferences used to direct traffic at an
12202 * application level as per the given OemNetworkPreferences. An example use-case would be an
12203 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12204 * vehicle via a particular network.
12205 *
12206 * Calling this will overwrite the existing preference.
12207 *
James Mattisda32cfe2021-01-26 16:23:52 -080012208 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012209 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012210 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012211 */
James Mattis47db0582021-01-01 14:13:35 -080012212 @Override
James Mattis45d81842021-01-10 14:24:24 -080012213 public void setOemNetworkPreference(
12214 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012215 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012216
James Mattisfa270db2021-05-31 17:11:10 -070012217 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12218 // Only bypass the permission/device checks if this is a valid test request.
12219 if (isValidTestOemNetworkPreference(preference)) {
12220 enforceManageTestNetworksPermission();
12221 } else {
12222 enforceAutomotiveDevice();
12223 enforceOemNetworkPreferencesPermission();
12224 validateOemNetworkPreferences(preference);
12225 }
James Mattis45d81842021-01-10 14:24:24 -080012226
James Mattis45d81842021-01-10 14:24:24 -080012227 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12228 new Pair<>(preference, listener)));
12229 }
12230
James Mattisfa270db2021-05-31 17:11:10 -070012231 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012232 * Sets the specified UIDs to get/receive the VPN as the only default network.
12233 *
12234 * Calling this will overwrite the existing network preference for this session, and the
12235 * specified UIDs won't get any default network when no VPN is connected.
12236 *
12237 * @param session The VPN session which manages the passed UIDs.
12238 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12239 * setting for this session if the array is empty. Null is not allowed, the
12240 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12241 * @hide
12242 */
12243 @Override
12244 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12245 Objects.requireNonNull(ranges);
12246 enforceNetworkStackOrSettingsPermission();
12247 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12248 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12249 throw new IllegalArgumentException(
12250 "setVpnNetworkPreference: Passed UID ranges overlap");
12251 }
12252
12253 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12254 new VpnNetworkPreferenceInfo(session,
12255 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12256 }
12257
12258 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12259 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12260
12261 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12262 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12263
12264 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12265 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12266 // Finally, rematch.
12267 rematchAllNetworksAndRequests();
12268 }
12269
12270 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12271 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12272 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12273 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
12274 final List<NetworkRequest> requests = new ArrayList<>();
12275 // Request VPN only, so other networks won't be the fallback options when VPN is not
12276 // connected temporarily.
12277 requests.add(createVpnRequest());
12278 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
12279 setNetworkRequestUids(requests, uidRanges);
12280 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
12281 }
12282 return nris;
12283 }
12284
12285 /**
James Mattisfa270db2021-05-31 17:11:10 -070012286 * Check the validity of an OEM network preference to be used for testing purposes.
12287 * @param preference the preference to validate
12288 * @return true if this is a valid OEM network preference test request.
12289 */
12290 private boolean isValidTestOemNetworkPreference(
12291 @NonNull final OemNetworkPreferences preference) {
12292 // Allow for clearing of an existing OemNetworkPreference used for testing.
12293 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
12294 // changes after this check is complete. This is an unlikely scenario as calling of this API
12295 // is controlled by the OEM therefore the added complexity is not worth adding given those
12296 // circumstances. That said, it is an edge case to be aware of hence this comment.
12297 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
12298 && isTestOemNetworkPreference(mOemNetworkPreferences);
12299 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
12300 }
12301
12302 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
12303 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
12304 return prefMap.size() == 1
12305 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
12306 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
12307 }
12308
James Mattis45d81842021-01-10 14:24:24 -080012309 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
12310 for (@OemNetworkPreferences.OemNetworkPreference final int pref
12311 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070012312 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
12313 throw new IllegalArgumentException(
12314 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
12315 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080012316 }
12317 }
12318 }
12319
12320 private void handleSetOemNetworkPreference(
12321 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012322 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080012323 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12324 if (DBG) {
12325 log("set OEM network preferences :" + preference.toString());
12326 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012327
James Mattiscb1e0362021-04-06 17:07:42 -070012328 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012329 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12330 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12331 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012332 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012333
12334 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012335 try {
12336 listener.onComplete();
12337 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012338 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012339 }
James Mattis45d81842021-01-10 14:24:24 -080012340 }
12341 }
12342
paulhu74128522021-09-28 02:29:03 +000012343 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012344 // Skip the requests which are set by other network preference. Because the uid range rules
12345 // should stay in netd.
12346 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012347 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012348 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012349 }
12350
James Mattis3ce3d3c2021-02-09 18:18:28 -080012351 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12352 ensureRunningOnConnectivityServiceThread();
12353 mDefaultNetworkRequests.addAll(nris);
12354 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12355 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012356 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012357 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12358 nrisToRegister.addAll(
12359 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12360 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012361 }
12362
12363 /**
12364 * All current requests that are tracking the default network need to be assessed as to whether
12365 * or not the current set of per-application default requests will be changing their default
12366 * network. If so, those requests will need to be updated so that they will send callbacks for
12367 * default network changes at the appropriate time. Additionally, those requests tracking the
12368 * default that were previously updated by this flow will need to be reassessed.
12369 * @return the nris which will need to be updated.
12370 */
12371 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12372 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12373 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12374 // same nri in the map's values for each of its NetworkRequest objects.
12375 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012376 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012377 // Include this nri if it is currently being tracked.
12378 if (isPerAppTrackedNri(nri)) {
12379 defaultCallbackRequests.add(nri);
12380 continue;
12381 }
12382 // We only track callbacks for requests tracking the default.
12383 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12384 continue;
12385 }
12386 // Include this nri if it will be tracked by the new per-app default requests.
12387 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012388 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012389 if (isNriGoingToBeTracked) {
12390 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012391 }
12392 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012393 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012394 }
12395
James Mattis3ce3d3c2021-02-09 18:18:28 -080012396 /**
12397 * Create nris for those network requests that are currently tracking the default network that
12398 * are being controlled by a per-application default.
12399 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12400 * foundation when creating the nri. Important items include the calling uid's original
12401 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12402 * requests are assumed to have already been validated as needing to be updated.
12403 * @return the Set of nris to use when registering network requests.
12404 */
12405 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12406 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12407 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12408 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12409 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012410 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012411
Chalard Jean9473c982021-07-29 20:03:04 +090012412 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012413 if (trackingNri == mDefaultRequest) {
12414 callbackRequestsToRegister.add(new NetworkRequestInfo(
12415 callbackRequest,
12416 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12417 continue;
12418 }
12419
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012420 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012421 callbackRequestsToRegister.add(new NetworkRequestInfo(
12422 callbackRequest,
12423 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012424 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012425 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012426 }
12427 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012428 }
12429
Chalard Jean17215832021-03-01 14:06:28 +090012430 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12431 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012432 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012433 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012434 }
12435 }
12436
James Mattis45d81842021-01-10 14:24:24 -080012437 /**
12438 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12439 */
12440 @VisibleForTesting
12441 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012442 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080012443 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012444 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080012445 final SparseArray<Set<Integer>> uids =
12446 createUidsFromOemNetworkPreferences(preference);
12447 for (int i = 0; i < uids.size(); i++) {
12448 final int key = uids.keyAt(i);
12449 final Set<Integer> value = uids.valueAt(i);
12450 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
12451 // No need to add an nri without any requests.
12452 if (0 == nri.mRequests.size()) {
12453 continue;
12454 }
12455 nris.add(nri);
12456 }
12457
12458 return nris;
12459 }
12460
12461 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
12462 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070012463 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080012464 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080012465 final List<UserHandle> users =
12466 mContext.getSystemService(UserManager.class).getUserHandles(true);
12467 if (null == users || users.size() == 0) {
12468 if (VDBG || DDBG) {
12469 log("No users currently available for setting the OEM network preference.");
12470 }
James Mattisb6b6a432021-06-01 22:30:36 -070012471 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080012472 }
James Mattis45d81842021-01-10 14:24:24 -080012473 for (final Map.Entry<String, Integer> entry :
12474 preference.getNetworkPreferences().entrySet()) {
12475 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070012476 // Add the rules for all users as this policy is device wide.
12477 for (final UserHandle user : users) {
12478 try {
12479 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
12480 if (!prefToUids.contains(pref)) {
12481 prefToUids.put(pref, new ArraySet<>());
12482 }
12483 prefToUids.get(pref).add(uid);
12484 } catch (PackageManager.NameNotFoundException e) {
12485 // Although this may seem like an error scenario, it is ok that uninstalled
12486 // packages are sent on a network preference as the system will watch for
12487 // package installations associated with this network preference and update
12488 // accordingly. This is done to minimize race conditions on app install.
12489 continue;
James Mattis45d81842021-01-10 14:24:24 -080012490 }
James Mattis45d81842021-01-10 14:24:24 -080012491 }
12492 }
James Mattisb6b6a432021-06-01 22:30:36 -070012493 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080012494 }
12495
12496 private NetworkRequestInfo createNriFromOemNetworkPreferences(
12497 @OemNetworkPreferences.OemNetworkPreference final int preference,
12498 @NonNull final Set<Integer> uids) {
12499 final List<NetworkRequest> requests = new ArrayList<>();
12500 // Requests will ultimately be evaluated by order of insertion therefore it matters.
12501 switch (preference) {
12502 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
12503 requests.add(createUnmeteredNetworkRequest());
12504 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070012505 requests.add(createDefaultInternetRequestForTransport(
12506 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080012507 break;
12508 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
12509 requests.add(createUnmeteredNetworkRequest());
12510 requests.add(createOemPaidNetworkRequest());
12511 break;
12512 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
12513 requests.add(createOemPaidNetworkRequest());
12514 break;
12515 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
12516 requests.add(createOemPrivateNetworkRequest());
12517 break;
James Mattisfa270db2021-05-31 17:11:10 -070012518 case OEM_NETWORK_PREFERENCE_TEST:
12519 requests.add(createUnmeteredNetworkRequest());
12520 requests.add(createTestNetworkRequest());
12521 requests.add(createDefaultRequest());
12522 break;
12523 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
12524 requests.add(createTestNetworkRequest());
12525 break;
James Mattis45d81842021-01-10 14:24:24 -080012526 default:
12527 // This should never happen.
12528 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
12529 + " called with invalid preference of " + preference);
12530 }
12531
James Mattisfa270db2021-05-31 17:11:10 -070012532 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090012533 for (final int uid : uids) {
12534 ranges.add(new UidRange(uid, uid));
12535 }
12536 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080012537 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080012538 }
12539
12540 private NetworkRequest createUnmeteredNetworkRequest() {
12541 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12542 .addCapability(NET_CAPABILITY_NOT_METERED)
12543 .addCapability(NET_CAPABILITY_VALIDATED);
12544 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
12545 }
12546
12547 private NetworkRequest createOemPaidNetworkRequest() {
12548 // NET_CAPABILITY_OEM_PAID is a restricted capability.
12549 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12550 .addCapability(NET_CAPABILITY_OEM_PAID)
12551 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12552 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12553 }
12554
12555 private NetworkRequest createOemPrivateNetworkRequest() {
12556 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
12557 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12558 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
12559 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12560 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12561 }
12562
12563 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070012564 final NetworkCapabilities netcap = new NetworkCapabilities();
12565 netcap.addCapability(NET_CAPABILITY_INTERNET);
12566 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
12567 return netcap;
12568 }
12569
12570 private NetworkRequest createTestNetworkRequest() {
12571 final NetworkCapabilities netcap = new NetworkCapabilities();
12572 netcap.clearAll();
12573 netcap.addTransportType(TRANSPORT_TEST);
12574 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080012575 }
James Mattis47db0582021-01-01 14:13:35 -080012576 }
markchien738ad912021-12-09 18:15:45 +080012577
Ken Chen24330172023-10-20 13:02:14 +080012578 @TargetApi(Build.VERSION_CODES.TIRAMISU)
markchien738ad912021-12-09 18:15:45 +080012579 @Override
Junyu Laidf210362023-10-24 02:47:50 +000012580 public void setDataSaverEnabled(final boolean enable) {
12581 enforceNetworkStackOrSettingsPermission();
12582 try {
12583 final boolean ret = mNetd.bandwidthEnableDataSaver(enable);
12584 if (!ret) {
12585 throw new IllegalStateException("Error when changing iptables: " + enable);
12586 }
12587 } catch (RemoteException e) {
12588 // Lack of permission or binder errors.
12589 throw new IllegalStateException(e);
12590 }
Ken Chen24330172023-10-20 13:02:14 +080012591
12592 try {
12593 mBpfNetMaps.setDataSaverEnabled(enable);
12594 } catch (ServiceSpecificException | UnsupportedOperationException e) {
12595 Log.e(TAG, "Failed to set data saver " + enable + " : " + e);
12596 }
Junyu Laidf210362023-10-24 02:47:50 +000012597 }
12598
12599 @Override
markchien738ad912021-12-09 18:15:45 +080012600 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
12601 enforceNetworkStackOrSettingsPermission();
12602
12603 try {
12604 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012605 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012606 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012607 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012608 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012609 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012610 throw new IllegalStateException(e);
12611 }
12612 }
12613
12614 @Override
12615 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
12616 enforceNetworkStackOrSettingsPermission();
12617
12618 try {
12619 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012620 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012621 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012622 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012623 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012624 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012625 throw new IllegalStateException(e);
12626 }
12627 }
markchiene1561fa2021-12-09 22:00:56 +080012628
Chalard Jeanc8fefb32023-09-05 21:41:13 +090012629 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
12630 throws PackageManager.NameNotFoundException {
12631 final PackageManager pm = mContext.getPackageManager();
12632 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
12633 if (appId < Process.FIRST_APPLICATION_UID) {
12634 throw new RuntimeException("Can't set package firewall rule for system app "
12635 + packageName + " with appId " + appId);
12636 }
12637 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
12638 final int uid = uh.getUid(appId);
12639 setUidFirewallRule(chain, uid, rule);
12640 }
12641 return appId;
12642 }
12643
markchiene1561fa2021-12-09 22:00:56 +080012644 @Override
markchien3c04e662022-03-22 16:29:56 +080012645 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080012646 enforceNetworkStackOrSettingsPermission();
12647
markchien3c04e662022-03-22 16:29:56 +080012648 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
12649 int firewallRule = getFirewallRuleType(chain, rule);
12650
12651 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
12652 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
12653 }
12654
markchiene1561fa2021-12-09 22:00:56 +080012655 try {
markchien3c04e662022-03-22 16:29:56 +080012656 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012657 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080012658 throw new IllegalStateException(e);
12659 }
12660 }
markchien98a6f952022-01-13 23:43:53 +080012661
Chalard Jeanc8fefb32023-09-05 21:41:13 +090012662 private int getPackageFirewallRule(final int chain, final String packageName)
12663 throws PackageManager.NameNotFoundException {
12664 final PackageManager pm = mContext.getPackageManager();
12665 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
12666 return getUidFirewallRule(chain, appId);
12667 }
12668
Motomu Utsumi900b8062023-01-19 16:16:49 +090012669 @Override
12670 public int getUidFirewallRule(final int chain, final int uid) {
12671 enforceNetworkStackOrSettingsPermission();
12672 return mBpfNetMaps.getUidRule(chain, uid);
12673 }
12674
markchien3c04e662022-03-22 16:29:56 +080012675 private int getFirewallRuleType(int chain, int rule) {
12676 final int defaultRule;
12677 switch (chain) {
12678 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000012679 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
12680 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000012681 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080012682 defaultRule = FIREWALL_RULE_ALLOW;
12683 break;
12684 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
12685 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
12686 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
12687 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
12688 defaultRule = FIREWALL_RULE_DENY;
12689 break;
12690 default:
12691 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
12692 }
12693 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
12694
12695 return rule;
12696 }
12697
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012698 private void closeSocketsForFirewallChainLocked(final int chain)
12699 throws ErrnoException, SocketException, InterruptedIOException {
Junyu Laie0031522023-08-29 18:32:57 +080012700 if (BpfNetMapsUtils.isFirewallAllowList(chain)) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012701 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
12702 // So, close all non-system socket owned by uids that are not explicitly allowed
12703 Set<Range<Integer>> ranges = new ArraySet<>();
12704 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
12705 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
12706 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
12707 } else {
12708 // Denylist means the firewall allows all by default, uids must be explicitly denied
12709 // So, close socket owned by uids that are explicitly denied
12710 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
12711 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
12712 }
12713 }
12714
markchien98a6f952022-01-13 23:43:53 +080012715 @Override
12716 public void setFirewallChainEnabled(final int chain, final boolean enable) {
12717 enforceNetworkStackOrSettingsPermission();
12718
12719 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012720 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012721 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080012722 throw new IllegalStateException(e);
12723 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012724
Chalard Jeandf29a852023-05-29 17:02:43 +090012725 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012726 try {
12727 closeSocketsForFirewallChainLocked(chain);
12728 } catch (ErrnoException | SocketException | InterruptedIOException e) {
12729 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
12730 }
12731 }
markchien98a6f952022-01-13 23:43:53 +080012732 }
12733
markchien00a0bed2022-01-13 23:46:13 +080012734 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012735 public boolean getFirewallChainEnabled(final int chain) {
12736 enforceNetworkStackOrSettingsPermission();
12737
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000012738 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012739 }
12740
12741 @Override
markchien00a0bed2022-01-13 23:46:13 +080012742 public void replaceFirewallChain(final int chain, final int[] uids) {
12743 enforceNetworkStackOrSettingsPermission();
12744
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000012745 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080012746 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080012747
12748 @Override
12749 public IBinder getCompanionDeviceManagerProxyService() {
12750 enforceNetworkStackPermission(mContext);
12751 return mCdmps;
12752 }
Chalard Jean2fb66f12023-08-25 12:50:37 +090012753
12754 @Override
12755 public IBinder getRoutingCoordinatorService() {
12756 enforceNetworkStackPermission(mContext);
12757 return mRoutingCoordinatorService;
12758 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070012759}