blob: 8b933c537352d2662fd0d8edfb1c5078c4dc4f3d [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
Quang Anh Luong28eefef2023-11-07 09:43:41 +0900971 // Flag to allow SysUI to receive connectivity reports for wifi picker UI.
972 private final boolean mAllowSysUiConnectivityReports;
973
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900974 // Uids that ConnectivityService is pending to close sockets of.
975 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
976
Robert Greenwalt802c1102014-06-02 15:32:02 -0700977 /**
978 * Implements support for the legacy "one network per network type" model.
979 *
980 * We used to have a static array of NetworkStateTrackers, one for each
981 * network type, but that doesn't work any more now that we can have,
982 * for example, more that one wifi network. This class stores all the
983 * NetworkAgentInfo objects that support a given type, but the legacy
984 * API will only see the first one.
985 *
986 * It serves two main purposes:
987 *
988 * 1. Provide information about "the network for a given type" (since this
989 * API only supports one).
990 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
991 * the first network for a given type changes, or if the default network
992 * changes.
993 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900994 @VisibleForTesting
995 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900996
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900997 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900998 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900999
Robert Greenwalt802c1102014-06-02 15:32:02 -07001000 /**
1001 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
1002 * Each list holds references to all NetworkAgentInfos that are used to
1003 * satisfy requests for that network type.
1004 *
1005 * This array is built out at startup such that an unsupported network
1006 * doesn't get an ArrayList instance, making this a tristate:
1007 * unsupported, supported but not active and active.
1008 *
1009 * The actual lists are populated when we scan the network types that
1010 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +09001011 *
1012 * Threading model:
1013 * - addSupportedType() is only called in the constructor
1014 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1015 * They are therefore not thread-safe with respect to each other.
1016 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1017 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001018 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001019 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001020 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001021 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001022 @NonNull
1023 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001024
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001025 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1026 // an entry have no timer (equivalent to -1). Lazily loaded.
1027 @NonNull
1028 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1029
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001030 LegacyTypeTracker(@NonNull ConnectivityService service) {
1031 mService = service;
1032 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001033 }
1034
Chiachang Wang3bc52762021-11-25 14:17:57 +08001035 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1036 // addressed.
1037 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001038 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1039 final PackageManager pm = ctx.getPackageManager();
1040 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1041 addSupportedType(TYPE_WIFI);
1042 }
1043 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1044 addSupportedType(TYPE_WIFI_P2P);
1045 }
1046 if (tm.isDataCapable()) {
1047 // Telephony does not have granular support for these types: they are either all
1048 // supported, or none is supported
1049 addSupportedType(TYPE_MOBILE);
1050 addSupportedType(TYPE_MOBILE_MMS);
1051 addSupportedType(TYPE_MOBILE_SUPL);
1052 addSupportedType(TYPE_MOBILE_DUN);
1053 addSupportedType(TYPE_MOBILE_HIPRI);
1054 addSupportedType(TYPE_MOBILE_FOTA);
1055 addSupportedType(TYPE_MOBILE_IMS);
1056 addSupportedType(TYPE_MOBILE_CBS);
1057 addSupportedType(TYPE_MOBILE_IA);
1058 addSupportedType(TYPE_MOBILE_EMERGENCY);
1059 }
1060 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1061 addSupportedType(TYPE_BLUETOOTH);
1062 }
1063 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1064 // TYPE_PROXY is only used on Wear
1065 addSupportedType(TYPE_PROXY);
1066 }
1067 // Ethernet is often not specified in the configs, although many devices can use it via
1068 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001069 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001070 addSupportedType(TYPE_ETHERNET);
1071 }
1072
1073 // Always add TYPE_VPN as a supported type
1074 addSupportedType(TYPE_VPN);
1075 }
1076
1077 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001078 if (mTypeLists[type] != null) {
1079 throw new IllegalStateException(
1080 "legacy list for type " + type + "already initialized");
1081 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001082 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001083 }
1084
Robert Greenwalt802c1102014-06-02 15:32:02 -07001085 public boolean isTypeSupported(int type) {
1086 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1087 }
1088
1089 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001090 synchronized (mTypeLists) {
1091 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1092 return mTypeLists[type].get(0);
1093 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001094 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001095 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001096 }
1097
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001098 public int getRestoreTimerForType(int type) {
1099 synchronized (mTypeLists) {
1100 if (mRestoreTimers == null) {
1101 mRestoreTimers = loadRestoreTimers();
1102 }
1103 return mRestoreTimers.getOrDefault(type, -1);
1104 }
1105 }
1106
1107 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1108 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001109 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001110 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1111 for (final String config : configs) {
1112 final String[] splits = TextUtils.split(config, ",");
1113 if (splits.length != 2) {
1114 logwtf("Invalid restore timer token count: " + config);
1115 continue;
1116 }
1117 try {
1118 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1119 } catch (NumberFormatException e) {
1120 logwtf("Invalid restore timer number format: " + config, e);
1121 }
1122 }
1123 return ret;
1124 }
1125
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001126 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001127 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001128 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001129 log("Sending " + state
1130 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001131 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001132 }
1133 }
1134
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001135 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1136 // network type, to preserve previous behaviour.
1137 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1138 if (vpnNai != mService.getLegacyLockdownNai()) return;
1139
1140 if (vpnNai.declaredUnderlyingNetworks == null
1141 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1142 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1143 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1144 return;
1145 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001146 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001147 vpnNai.declaredUnderlyingNetworks[0]);
1148 if (underlyingNai == null) return;
1149
1150 final int type = underlyingNai.networkInfo.getType();
1151 final DetailedState state = DetailedState.CONNECTED;
1152 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1153 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1154 }
1155
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001156 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001157 public void add(int type, NetworkAgentInfo nai) {
1158 if (!isTypeSupported(type)) {
1159 return; // Invalid network type.
1160 }
1161 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1162
1163 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1164 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001165 return;
1166 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001167 synchronized (mTypeLists) {
1168 list.add(nai);
1169 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001170
Chalard Jean5b409c72021-02-04 13:12:59 +09001171 // Send a broadcast if this is the first network of its type or if it's the default.
1172 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001173
1174 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1175 // to preserve previous behaviour.
1176 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001177 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001178 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1179 mService.sendLegacyNetworkBroadcast(nai, state, type);
1180 }
1181
1182 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1183 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001184 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001185 }
1186
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001187 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001188 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001189 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1190 if (list == null || list.isEmpty()) {
1191 return;
1192 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001193 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001194
Hugo Benichi389633f2016-06-21 09:48:07 +09001195 synchronized (mTypeLists) {
1196 if (!list.remove(nai)) {
1197 return;
1198 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001199 }
1200
Lorenzo Colitti49767722015-05-01 00:30:10 +09001201 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001202 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1203 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001204 }
1205
1206 if (!list.isEmpty() && wasFirstNetwork) {
1207 if (DBG) log("Other network available for type " + type +
1208 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001209 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001210 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001211 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001212 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001213 }
1214 }
1215
1216 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001217 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1218 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001219 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001220 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001221 }
1222 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001223
Chalard Jean46bfbf02022-02-02 00:56:25 +09001224 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001225 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001226 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001227 final DetailedState state = nai.networkInfo.getDetailedState();
1228 for (int type = 0; type < mTypeLists.length; type++) {
1229 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001230 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001231 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001232 if (isFirst || contains && isDefault) {
1233 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001234 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001235 }
1236 }
1237 }
1238
Robert Greenwalt94e22142014-07-30 16:31:24 -07001239 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001240 pw.println("mLegacyTypeTracker:");
1241 pw.increaseIndent();
1242 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001243 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001244 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001245 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001246 pw.println();
1247 pw.println("Current state:");
1248 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001249 synchronized (mTypeLists) {
1250 for (int type = 0; type < mTypeLists.length; type++) {
1251 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1252 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001253 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001254 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001255 }
1256 }
1257 pw.decreaseIndent();
1258 pw.decreaseIndent();
1259 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001260 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001261 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001262 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001263
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001264 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001265 /**
1266 * Helper class which parses out priority arguments and dumps sections according to their
1267 * priority. If priority arguments are omitted, function calls the legacy dump command.
1268 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001269 private class LocalPriorityDump {
1270 private static final String PRIORITY_ARG = "--dump-priority";
1271 private static final String PRIORITY_ARG_HIGH = "HIGH";
1272 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
Junyu Laif8dba342023-10-12 17:01:03 +08001273 private static final int DUMPSYS_DEFAULT_TIMEOUT_MS = 10_000;
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001274
1275 LocalPriorityDump() {}
1276
1277 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
Junyu Laif8dba342023-10-12 17:01:03 +08001278 if (!HandlerUtils.runWithScissors(mHandler, () -> {
1279 doDump(fd, pw, new String[]{DIAG_ARG});
1280 doDump(fd, pw, new String[]{SHORT_ARG});
1281 }, DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1282 pw.println("dumpHigh timeout");
1283 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001284 }
1285
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001286 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
Junyu Laif8dba342023-10-12 17:01:03 +08001287 if (!HandlerUtils.runWithScissors(mHandler, () -> doDump(fd, pw, args),
1288 DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1289 pw.println("dumpNormal timeout");
1290 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001291 }
1292
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001293 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1294 if (args == null) {
1295 dumpNormal(fd, pw, args);
1296 return;
1297 }
1298
1299 String priority = null;
1300 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1301 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1302 argIndex++;
1303 priority = args[argIndex];
1304 }
1305 }
1306
1307 if (PRIORITY_ARG_HIGH.equals(priority)) {
1308 dumpHigh(fd, pw);
1309 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1310 dumpNormal(fd, pw, args);
1311 } else {
1312 // ConnectivityService publishes binder service using publishBinderService() with
1313 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001314 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1315 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001316 // TODO: Integrate into signal dump.
1317 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001318 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001319 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001320 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001321
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001322 /**
1323 * Dependencies of ConnectivityService, for injection in tests.
1324 */
1325 @VisibleForTesting
1326 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001327 public int getCallingUid() {
1328 return Binder.getCallingUid();
1329 }
1330
Chalard Jeandf29a852023-05-29 17:02:43 +09001331 public boolean isAtLeastS() {
1332 return SdkLevel.isAtLeastS();
1333 }
1334
1335 public boolean isAtLeastT() {
1336 return SdkLevel.isAtLeastT();
1337 }
1338
1339 public boolean isAtLeastU() {
1340 return SdkLevel.isAtLeastU();
1341 }
1342
Chalard Jeaneb663892023-10-07 15:17:07 +09001343 public boolean isAtLeastV() {
1344 return SdkLevel.isAtLeastV();
1345 }
1346
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001347 /**
1348 * Get system properties to use in ConnectivityService.
1349 */
1350 public MockableSystemProperties getSystemProperties() {
1351 return new MockableSystemProperties();
1352 }
1353
1354 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001355 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1356 */
1357 public ConnectivityResources getResources(@NonNull Context ctx) {
1358 return new ConnectivityResources(ctx);
1359 }
1360
1361 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001362 * Create a HandlerThread to use in ConnectivityService.
1363 */
1364 public HandlerThread makeHandlerThread() {
1365 return new HandlerThread("ConnectivityServiceThread");
1366 }
1367
1368 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001369 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001370 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001371 public NetworkStackClientBase getNetworkStack() {
1372 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001373 }
1374
1375 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001376 * @see ProxyTracker
1377 */
1378 public ProxyTracker makeProxyTracker(@NonNull Context context,
1379 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001380 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001381 }
1382
1383 /**
1384 * @see NetIdManager
1385 */
1386 public NetIdManager makeNetIdManager() {
1387 return new NetIdManager();
1388 }
1389
1390 /**
1391 * @see NetworkUtils#queryUserAccess(int, int)
1392 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001393 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1394 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001395 }
1396
1397 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001398 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1399 * requires CAP_NET_ADMIN, which the unit tests do not have.
1400 */
1401 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1402 InetSocketAddress remote) {
1403 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1404 }
1405
1406 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001407 * @see MultinetworkPolicyTracker
1408 */
1409 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1410 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1411 return new MultinetworkPolicyTracker(c, h, r);
1412 }
1413
Aaron Huang330a4c02020-10-27 03:36:19 +08001414 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001415 * @see AutomaticOnOffKeepaliveTracker
1416 */
1417 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1418 @NonNull Context c, @NonNull Handler h) {
1419 return new AutomaticOnOffKeepaliveTracker(c, h);
1420 }
1421
1422 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001423 * @see BatteryStatsManager
1424 */
1425 public void reportNetworkInterfaceForTransports(Context context, String iface,
1426 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001427 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001428 context.getSystemService(BatteryStatsManager.class);
1429 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1430 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001431
1432 public boolean getCellular464XlatEnabled() {
1433 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1434 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001435
1436 /**
1437 * @see PendingIntent#intentFilterEquals
1438 */
1439 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1440 return a.intentFilterEquals(b);
1441 }
1442
1443 /**
1444 * @see LocationPermissionChecker
1445 */
1446 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1447 return new LocationPermissionChecker(context);
1448 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001449
1450 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001451 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001452 *
1453 * This method returns null in versions before T, where carrier privilege
1454 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001455 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001456 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001457 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1458 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001459 if (isAtLeastT()) {
Chalard Jean84dfa9f2023-01-30 11:23:20 +09001460 return new CarrierPrivilegeAuthenticator(context, this, tm);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001461 } else {
1462 return null;
1463 }
1464 }
1465
1466 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001467 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001468 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001469 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001470 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001471 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001472
1473 /**
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001474 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1475 */
1476 public boolean isFeatureNotChickenedOut(Context context, String name) {
1477 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, name);
1478 }
1479
1480 /**
Wayne Ma2fde98c2022-01-17 18:04:05 +08001481 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001482 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001483 * @return BpfNetMaps implementation.
1484 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001485 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1486 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001487 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001488
1489 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001490 * @see ClatCoordinator
1491 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001492 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001493 public ClatCoordinator getClatCoordinator(INetd netd) {
1494 return new ClatCoordinator(
1495 new ClatCoordinator.Dependencies() {
1496 @NonNull
1497 public INetd getNetd() {
1498 return netd;
1499 }
1500 });
1501 }
1502
1503 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001504 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1505 */
1506 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1507 final InterfaceParams params = InterfaceParams.getByName(iface);
1508 if (params == null) {
1509 // the interface might have disappeared.
1510 logw("Failed to get interface params for interface " + iface);
1511 return;
1512 }
1513 try {
1514 // converting rateInBytesPerSecond from long to int is safe here because the
1515 // setting's range is limited to INT_MAX.
1516 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001517 Log.i(TAG,
1518 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001519 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1520 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1521 } catch (IOException e) {
1522 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1523 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1524 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1525 + ") failure: ", e);
1526 }
1527 }
1528
1529 /**
1530 * Wraps {@link TcUtils#tcFilterDelDev}
1531 */
1532 public void disableIngressRateLimit(String iface) {
1533 final InterfaceParams params = InterfaceParams.getByName(iface);
1534 if (params == null) {
1535 // the interface might have disappeared.
1536 logw("Failed to get interface params for interface " + iface);
1537 return;
1538 }
1539 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001540 Log.i(TAG,
1541 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001542 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1543 } catch (IOException e) {
1544 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1545 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1546 }
1547 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001548
1549 /**
Junyu Lai155760b2023-10-05 14:51:00 +08001550 * Get BPF program Id from CGROUP. See {@link BpfUtils#getProgramId}.
1551 */
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001552 public int getBpfProgramId(final int attachType)
Junyu Lai155760b2023-10-05 14:51:00 +08001553 throws IOException {
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001554 return BpfUtils.getProgramId(attachType);
Junyu Lai155760b2023-10-05 14:51:00 +08001555 }
1556
1557 /**
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001558 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1559 */
1560 // TODO: when available in all active branches:
1561 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1562 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1563 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1564 return BroadcastOptionsShimImpl.newInstance(options);
1565 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001566
1567 /**
1568 * Wrapper method for
1569 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1570 *
1571 * @param changeId The ID of the compatibility change in question.
1572 * @param packageName The package name of the app in question.
1573 * @param user The user that the operation is done for.
1574 * @return {@code true} if the change is enabled for the specified package.
1575 */
1576 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1577 @NonNull final UserHandle user) {
1578 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1579 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001580
1581 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001582 * As above but with a UID.
1583 * @see CompatChanges#isChangeEnabled(long, int)
1584 */
1585 public boolean isChangeEnabled(final long changeId, final int uid) {
1586 return CompatChanges.isChangeEnabled(changeId, uid);
1587 }
1588
1589 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001590 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1591 *
1592 * @param ranges target uid ranges
1593 * @param exemptUids uids to skip close socket
1594 */
1595 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1596 @NonNull final Set<Integer> exemptUids)
1597 throws SocketException, InterruptedIOException, ErrnoException {
1598 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1599 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001600
1601 /**
1602 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1603 *
1604 * @param ownerUids target uids to close sockets
1605 */
1606 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1607 throws SocketException, InterruptedIOException, ErrnoException {
1608 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1609 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001610
1611 /**
1612 * Schedule the evaluation timeout.
1613 *
1614 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1615 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1616 * of these events happen, this time will run out, after which the network is considered
1617 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1618 * on this network and considers it won't provide connectivity. In particular, that means
1619 * it's when the system prefers it to cell if it's wifi and configuration says it should
1620 * prefer bad wifi to cell.
1621 */
1622 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1623 @NonNull final Network network, final long delayMs) {
1624 handler.sendMessageDelayed(
1625 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1626 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001627 }
1628
junyulaie7c7d2a2021-01-26 15:29:15 +08001629 public ConnectivityService(Context context) {
1630 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001631 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1632 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001633 }
1634
1635 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001636 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1637 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001638 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001639
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001640 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001641 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001642 mSystemProperties = mDeps.getSystemProperties();
1643 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001644 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001645 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001646 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1647 // Pass limit - 1 to maintain backward compatibility.
1648 // TODO: Remove the workaround.
1649 mNetworkRequestCounter =
1650 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1651 mSystemNetworkRequestCounter =
1652 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001653
Hugo Benichi208c0102016-07-28 17:53:06 +09001654 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001655 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1656 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001657 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001658 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001659 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001660 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1661 mDefaultNetworkRequests.add(mDefaultRequest);
1662 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001663
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001664 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001665 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001666
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001667 // The default WiFi request is a background request so that apps using WiFi are
1668 // migrated to a better network (typically ethernet) when one comes up, instead
1669 // of staying on WiFi forever.
1670 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1671 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1672
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001673 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1674 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1675 NetworkRequest.Type.BACKGROUND_REQUEST);
1676
Chalard Jean0702f982021-09-16 21:50:07 +09001677 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1678 // TODO: Consider making the timer customizable.
1679 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1680 mCellularRadioTimesharingCapable =
1681 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1682
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001683 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1684 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1685
1686 if (SdkLevel.isAtLeastU()) {
1687 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1688 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1689 final int defaultUMarkMask = 0x80000000; // u32
1690
1691 if ((mark == 0) || (mask == 0)) {
1692 // simply treat unset/disabled as the default U value
1693 mark = defaultUMarkMask;
1694 mask = defaultUMarkMask;
1695 }
1696 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1697 // invalid device overlay settings
1698 throw new IllegalArgumentException(
1699 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1700 }
1701 }
1702
1703 mWakeUpMark = mark;
1704 mWakeUpMask = mask;
1705
Paul Hu51f816b2022-08-11 14:43:47 +00001706 mNetd = netd;
1707 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001708 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001709 mPermissionMonitor =
1710 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001711 mHandlerThread.start();
1712 mHandler = new InternalHandler(mHandlerThread.getLooper());
1713 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001714 mConnectivityDiagnosticsHandler =
1715 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001716
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001717 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001718 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001719
junyulaie7c7d2a2021-01-26 15:29:15 +08001720 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001721 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001722 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001723 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001724
Wink Saville32506bc2013-06-29 21:10:57 -07001725 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001726 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001727 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001728 mCarrierPrivilegeAuthenticator =
1729 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001730
Sudheer Shanka9967d462021-03-18 19:09:25 +00001731 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001732 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1733 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001734 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001735
1736 final PowerManager powerManager = (PowerManager) context.getSystemService(
1737 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001738 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001739 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001740
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001741 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1742 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001743 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001744 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001745 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001746 mProtectedNetworks.add(p);
1747 } else {
1748 if (DBG) loge("Ignoring protectedNetwork " + p);
1749 }
1750 }
1751
soma, kawata29444ae2019-05-23 09:30:40 +09001752 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1753
James Mattis02220e22021-03-13 19:27:21 -08001754 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001755 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001756 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001757 final IntentFilter userIntentFilter = new IntentFilter();
1758 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1759 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1760 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1761 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001762
James Mattis02220e22021-03-13 19:27:21 -08001763 // Listen to package add/removes for netd
1764 final IntentFilter packageIntentFilter = new IntentFilter();
1765 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1766 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1767 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1768 packageIntentFilter.addDataScheme("package");
1769 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001770 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001771
Motomu Utsumi1e51a642023-07-18 15:11:41 +09001772 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001773
Chalard Jean46bfbf02022-02-02 00:56:25 +09001774 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001775 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001776 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001777 } catch (RemoteException | ServiceSpecificException e) {
1778 loge("Error registering event listener :" + e);
1779 }
1780
Erik Kline05f2b402015-04-30 12:58:40 +09001781 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1782 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001783
chiachangwang7c17c282023-02-02 05:58:59 +00001784 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001785 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001786 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001787
1788 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001789 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001790 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1791 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001792 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001793 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1794 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001795
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001796 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001797 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001798 mNetworkRanker =
1799 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1800
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001801 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001802
Chiachang Wangc1215d32020-10-20 15:38:58 +08001803 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001804 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001805
Chalard Jean28018572020-12-21 18:36:52 +09001806 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1807 // request that doesn't allow fallback to the default network. It should never be visible
1808 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1809 // arguments like the handler or the DnsResolver.
1810 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001811 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001812 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001813 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09001814 new LinkProperties(), new NetworkCapabilities(), null /* localNetworkConfig */,
Chalard Jean28018572020-12-21 18:36:52 +09001815 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001816 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1817 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001818
1819 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001820 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1821 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1822 // Even if it could, running on S would at least require mocking out the BPF map,
1823 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1824 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001825 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001826 mDscpPolicyTracker = new DscpPolicyTracker();
1827 }
Tyler Wear72388212021-09-09 14:49:02 -07001828 } catch (ErrnoException e) {
1829 loge("Unable to create DscpPolicyTracker");
1830 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001831
1832 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1833 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001834
Chalard Jeandf29a852023-05-29 17:02:43 +09001835 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001836 mCdmps = new CompanionDeviceManagerProxyService(context);
1837 } else {
1838 mCdmps = null;
1839 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001840
Chalard Jean2fb66f12023-08-25 12:50:37 +09001841 mRoutingCoordinatorService = new RoutingCoordinatorService(netd);
1842
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001843 mDestroyFrozenSockets = mDeps.isAtLeastU()
1844 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
1845 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1846 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001847 mAllowSysUiConnectivityReports = mDeps.isFeatureNotChickenedOut(
1848 mContext, ALLOW_SYSUI_CONNECTIVITY_REPORTS);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001849 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001850 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1851 new UidFrozenStateChangedCallback() {
1852 @Override
1853 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1854 if (uids.length != frozenStates.length) {
1855 Log.wtf(TAG, "uids has length " + uids.length
1856 + " but frozenStates has length " + frozenStates.length);
1857 return;
1858 }
1859
1860 final UidFrozenStateChangedArgs args =
1861 new UidFrozenStateChangedArgs(uids, frozenStates);
1862
1863 mHandler.sendMessage(
1864 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1865 }
1866 };
1867
1868 final ActivityManager activityManager =
1869 mContext.getSystemService(ActivityManager.class);
1870 activityManager.registerUidFrozenStateChangedCallback(
1871 (Runnable r) -> r.run(), frozenStateChangedCallback);
1872 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001873 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001874
Xiao Ma0a171c02022-01-23 16:14:51 +00001875 /**
1876 * Check whether or not the device supports Ethernet transport.
1877 */
1878 public static boolean deviceSupportsEthernet(final Context context) {
1879 final PackageManager pm = context.getPackageManager();
1880 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1881 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1882 }
1883
Chalard Jean46adcf32018-04-18 20:18:38 +09001884 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001885 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1886 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001887 }
1888
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001889 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1890 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001891 final NetworkCapabilities netCap = new NetworkCapabilities();
1892 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001893 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001894 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001895 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001896 return netCap;
1897 }
1898
James Mattis45d81842021-01-10 14:24:24 -08001899 private NetworkRequest createDefaultRequest() {
1900 return createDefaultInternetRequestForTransport(
1901 TYPE_NONE, NetworkRequest.Type.REQUEST);
1902 }
1903
lucaslin3ba7cc22022-12-19 02:35:33 +00001904 private NetworkRequest createVpnRequest() {
1905 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1906 .withoutDefaultCapabilities()
1907 .addTransportType(TRANSPORT_VPN)
1908 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1909 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1910 .build();
1911 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1912 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1913 }
1914
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001915 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001916 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001917 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001918 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001919 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001920 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001921 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001922 netCap.addTransportType(transportType);
1923 }
James Mattis45d81842021-01-10 14:24:24 -08001924 return createNetworkRequest(type, netCap);
1925 }
1926
1927 private NetworkRequest createNetworkRequest(
1928 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001929 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001930 }
1931
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001932 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1933 NetworkRequest.Type type) {
1934 final NetworkCapabilities netCap = new NetworkCapabilities();
1935 netCap.clearAll();
1936 netCap.addCapability(capability);
1937 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1938 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1939 }
1940
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001941 // Used only for testing.
1942 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001943 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001944 // changing ContentResolver to make registerContentObserver non-final).
1945 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1946 // by subclassing SettingsObserver.
1947 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001948 void updateAlwaysOnNetworks() {
1949 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001950 }
1951
Erik Kline9a62f012018-03-21 07:18:33 -07001952 // See FakeSettingsProvider comment above.
1953 @VisibleForTesting
1954 void updatePrivateDnsSettings() {
1955 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1956 }
1957
paulhu51f77dc2021-06-07 02:34:20 +00001958 @VisibleForTesting
1959 void updateMobileDataPreferredUids() {
1960 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1961 }
1962
Patrick Rohr2857ac42022-01-21 14:58:16 +01001963 @VisibleForTesting
1964 void updateIngressRateLimit() {
1965 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1966 }
1967
Aaron Huang40b52442021-06-08 04:34:24 +08001968 @VisibleForTesting
1969 void simulateUpdateProxyInfo(@Nullable final Network network,
1970 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001971 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08001972 new Pair<>(network, proxyInfo)).sendToTarget();
1973 }
1974
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001975 private void handleAlwaysOnNetworkRequest(
1976 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001977 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001978 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001979 handleAlwaysOnNetworkRequest(networkRequest, enable);
1980 }
1981
1982 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001983 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001984 if (enable == isEnabled) {
1985 return; // Nothing to do.
1986 }
1987
1988 if (enable) {
1989 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001990 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001991 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001992 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001993 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001994 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1995 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001996 }
1997 }
1998
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001999 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08002000 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
2001 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
2002 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
2003 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09002004 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
2005 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09002006 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002007 }
2008
paulhu51f77dc2021-06-07 02:34:20 +00002009 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08002010 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09002011 private void registerSettingsCallbacks() {
2012 // Watch for global HTTP proxy changes.
2013 mSettingsObserver.observe(
2014 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
2015 EVENT_APPLY_GLOBAL_HTTP_PROXY);
2016
Chalard Jean46bfbf02022-02-02 00:56:25 +09002017 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09002018 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002019 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002020 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
2021
Chalard Jean46bfbf02022-02-02 00:56:25 +09002022 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002023 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002024 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002025 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00002026
2027 // Watch for mobile data preferred uids changes.
2028 mSettingsObserver.observe(
2029 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
2030 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002031
2032 // Watch for ingress rate limit changes.
2033 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002034 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002035 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2036 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002037 }
2038
Erik Kline31b4a9e2018-01-11 21:07:29 +09002039 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002040 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2041 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002042 }
2043 }
2044
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002045 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002046 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2047 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002048 return mNextNetworkRequestId++;
2049 }
2050
junyulai74f9a8b2018-06-13 15:00:37 +08002051 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002052 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002053 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002054 if (network == null) {
2055 return null;
2056 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002057 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002058 }
2059
2060 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002061 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002062 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002063 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002064 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002065
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002066 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002067 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002068 private NetworkAgentInfo getVpnForUid(int uid) {
2069 synchronized (mNetworkForNetId) {
2070 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2071 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002072 if (nai.isVPN() && nai.everConnected()
2073 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002074 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002075 }
2076 }
2077 }
2078 return null;
2079 }
2080
Chalard Jean46bfbf02022-02-02 00:56:25 +09002081 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002082 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002083 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002084 final NetworkAgentInfo nai = getVpnForUid(uid);
2085 if (nai != null) return nai.declaredUnderlyingNetworks;
2086 return null;
2087 }
2088
Lorenzo Colittia7574052021-01-19 01:33:05 +09002089 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002090 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002091
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002092 final Network[] networks = getVpnUnderlyingNetworks(uid);
2093 if (networks != null) {
2094 // getUnderlyingNetworks() returns:
2095 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2096 // empty array => the VPN explicitly said "no default network".
2097 // non-empty array => the VPN specified one or more default networks; we use the
2098 // first one.
2099 if (networks.length > 0) {
2100 nai = getNetworkAgentInfoForNetwork(networks[0]);
2101 } else {
2102 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002103 }
2104 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002105 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002106 }
2107
2108 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002109 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002110 */
paulhu7aeba372020-12-30 00:42:19 +08002111 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2112 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002113 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002114 if (ignoreBlocked) {
2115 return false;
2116 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002117 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002118 final long ident = Binder.clearCallingIdentity();
2119 try {
2120 final boolean metered = nc == null ? true : nc.isMetered();
2121 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2122 } finally {
2123 Binder.restoreCallingIdentity(ident);
2124 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002125 }
2126
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002127 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002128 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2129 return;
2130 }
Hugo Benichi47011212017-03-30 10:46:05 +09002131 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002132 synchronized (mBlockedAppUids) {
2133 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002134 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002135 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002136 blocked = false;
2137 } else {
2138 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002139 }
2140 }
Hugo Benichi47011212017-03-30 10:46:05 +09002141 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2142 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2143 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002144 }
2145
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002146 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002147 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2148 return;
2149 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002150 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002151 final int requestId = nri.getActiveRequest() != null
2152 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002153 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002154 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002155 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002156 }
2157
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002158 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002159 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002160 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002161 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002162 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002163 @NonNull
2164 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2165 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002166 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2167 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2168 // but only exists if an app asks about them or requests them. Ensure the requesting app
2169 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002170 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002171 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2172 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2173 null /* extraInfo */);
2174 }
2175 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002176 return filtered;
2177 }
2178
2179 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2180 boolean ignoreBlocked) {
2181 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2182 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002183 }
2184
2185 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002186 * Return NetworkInfo for the active (i.e., connected) network interface.
2187 * It is assumed that at most one network is active at a time. If more
2188 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002189 * @return the info for the active network, or {@code null} if none is
2190 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002191 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002192 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002193 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002194 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002195 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002196 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002197 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2198 if (nai == null) return null;
2199 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2200 maybeLogBlockedNetworkInfo(networkInfo, uid);
2201 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002202 }
2203
Paul Jensen1f567382015-02-13 14:18:39 -05002204 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002205 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002206 public Network getActiveNetwork() {
2207 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002208 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002209 }
2210
2211 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002212 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002213 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002214 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002215 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002216 }
2217
Chalard Jean46bfbf02022-02-02 00:56:25 +09002218 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002219 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002220 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2221 if (vpnNai != null) {
2222 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2223 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2224 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002225 }
Paul Jensen1f567382015-02-13 14:18:39 -05002226 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002227
James Mattis2516da32021-01-31 17:06:19 -08002228 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002229 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2230 ignoreBlocked)) {
2231 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002232 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002233 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002234 }
2235
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002236 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002237 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002238 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002239 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002240 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2241 if (nai == null) return null;
2242 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002243 }
2244
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002245 /** Returns a NetworkInfo object for a network that doesn't exist. */
2246 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2247 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2248 getNetworkTypeName(networkType), "" /* subtypeName */);
2249 info.setIsAvailable(true);
2250 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2251 // background data is restricted.
2252 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2253 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2254 ? DetailedState.BLOCKED
2255 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002256 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2257 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002258 return info;
2259 }
2260
Lorenzo Colittia7574052021-01-19 01:33:05 +09002261 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002262 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2263 return null;
2264 }
2265 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002266 if (nai == null) {
2267 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002268 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002269 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2270 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002271 }
2272
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002273 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002274 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002275 public NetworkInfo getNetworkInfo(int networkType) {
2276 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002277 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002278 if (getVpnUnderlyingNetworks(uid) != null) {
2279 // A VPN is active, so we may need to return one of its underlying networks. This
2280 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002281 // getNetworkAgentInfoForUid.
2282 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2283 if (nai == null) return null;
2284 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2285 if (networkInfo.getType() == networkType) {
2286 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002287 }
2288 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002289 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002290 }
2291
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002292 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002293 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002294 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002295 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002296 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002297 if (nai == null) return null;
2298 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002299 }
2300
2301 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002302 public NetworkInfo[] getAllNetworkInfo() {
2303 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002304 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002305 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2306 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002307 NetworkInfo info = getNetworkInfo(networkType);
2308 if (info != null) {
2309 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002310 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002311 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002312 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002313 }
2314
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002315 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002316 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002317 public Network getNetworkForType(int networkType) {
2318 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002319 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2320 return null;
2321 }
2322 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2323 if (nai == null) {
2324 return null;
2325 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002326 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002327 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2328 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002329 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002330 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002331 }
2332
2333 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002334 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002335 public Network[] getAllNetworks() {
2336 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002337 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002338 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002339 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002340 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002341 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002342 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002343 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002344 }
2345
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002346 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002347 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002348 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002349 // The basic principle is: if an app's traffic could possibly go over a
2350 // network, without the app doing anything multinetwork-specific,
2351 // (hence, by "default"), then include that network's capabilities in
2352 // the array.
2353 //
2354 // In the normal case, app traffic only goes over the system's default
2355 // network connection, so that's the only network returned.
2356 //
2357 // With a VPN in force, some app traffic may go into the VPN, and thus
2358 // over whatever underlying networks the VPN specifies, while other app
2359 // traffic may go over the system default network (e.g.: a split-tunnel
2360 // VPN, or an app disallowed by the VPN), so the set of networks
2361 // returned includes the VPN's underlying networks and the system
2362 // default.
2363 enforceAccessPermission();
2364
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002365 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002366
James Mattis2516da32021-01-31 17:06:19 -08002367 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2368 if (!nri.isBeingSatisfied()) {
2369 continue;
2370 }
2371 final NetworkAgentInfo nai = nri.getSatisfier();
2372 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2373 if (null != nc
2374 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2375 && !result.containsKey(nai.network)) {
2376 result.put(
2377 nai.network,
2378 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002379 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002380 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2381 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002382 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002383 }
2384
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002385 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002386 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002387 if (null != networks) {
2388 for (final Network network : networks) {
2389 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2390 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002391 result.put(
2392 network,
2393 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002394 nc,
2395 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002396 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002397 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002398 }
2399 }
2400 }
2401
2402 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2403 out = result.values().toArray(out);
2404 return out;
2405 }
2406
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002407 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2408 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2409 // can call sampleConnectivityState and make the checks on it.
2410 @NonNull
2411 private StatsEvent sampleConnectivityStateToStatsEvent() {
2412 final ConnectivityStateSample sample = sampleConnectivityState();
2413 return ConnectivityStatsLog.buildStatsEvent(
2414 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2415 sample.getNetworkCountPerTransports().toByteArray(),
2416 sample.getConnectionDurationPerTransports().toByteArray(),
2417 sample.getNetworkRequestCount().toByteArray(),
2418 sample.getNetworks().toByteArray());
2419 }
2420
2421 /**
2422 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2423 *
2424 * This is used for metrics. These snapshots will be sampled and constitute a base for
2425 * statistics about connectivity state of devices.
2426 */
2427 @VisibleForTesting
2428 @NonNull
2429 public ConnectivityStateSample sampleConnectivityState() {
2430 ensureRunningOnConnectivityServiceThread();
2431 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2432 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2433 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2434 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2435 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2436 return builder.build();
2437 }
2438
2439 private static NetworkCountPerTransports sampleNetworkCount(
2440 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2441 final SparseIntArray countPerTransports = new SparseIntArray();
2442 for (final NetworkAgentInfo nai : nais) {
2443 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2444 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2445 }
2446 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2447 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2448 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2449 c.setTransportTypes(countPerTransports.keyAt(i));
2450 c.setNetworkCount(countPerTransports.valueAt(i));
2451 builder.addNetworkCountForTransports(c);
2452 }
2453 return builder.build();
2454 }
2455
2456 private static ConnectionDurationPerTransports sampleConnectionDuration(
2457 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2458 final ConnectionDurationPerTransports.Builder builder =
2459 ConnectionDurationPerTransports.newBuilder();
2460 for (final NetworkAgentInfo nai : nais) {
2461 final ConnectionDurationForTransports.Builder c =
2462 ConnectionDurationForTransports.newBuilder();
2463 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2464 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2465 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2466 // Add millisPerSecond/2 to round up or down to the nearest value
2467 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2468 builder.addConnectionDurationForTransports(c);
2469 }
2470 return builder.build();
2471 }
2472
2473 private static NetworkRequestCount sampleNetworkRequestCount(
2474 @NonNull final Collection<NetworkRequestInfo> nris) {
2475 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2476 final SparseIntArray countPerType = new SparseIntArray();
2477 for (final NetworkRequestInfo nri : nris) {
2478 final int type;
2479 if (Process.SYSTEM_UID == nri.mAsUid) {
2480 // The request is filed "as" the system, so it's the system on its own behalf.
2481 type = RequestType.RT_SYSTEM.getNumber();
2482 } else if (Process.SYSTEM_UID == nri.mUid) {
2483 // The request is filed by the system as some other app, so it's the system on
2484 // behalf of an app.
2485 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2486 } else {
2487 // Not the system, so it's an app requesting on its own behalf.
2488 type = RequestType.RT_APP.getNumber();
2489 }
2490 countPerType.put(type, countPerType.get(type, 0));
2491 }
2492 for (int i = countPerType.size() - 1; i >= 0; --i) {
2493 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2494 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2495 r.setRequestCount(countPerType.valueAt(i));
2496 builder.addRequestCountForType(r);
2497 }
2498 return builder.build();
2499 }
2500
2501 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2502 final NetworkList.Builder builder = NetworkList.newBuilder();
2503 for (final NetworkAgentInfo nai : nais) {
2504 final NetworkCapabilities nc = nai.networkCapabilities;
2505 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2506 d.setTransportTypes((int) nc.getTransportTypesInternal());
2507 final MeteredState meteredState;
2508 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2509 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2510 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2511 meteredState = MeteredState.METERED_NO;
2512 } else {
2513 meteredState = MeteredState.METERED_YES;
2514 }
2515 d.setMeteredState(meteredState);
2516 final ValidatedState validatedState;
2517 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2518 validatedState = ValidatedState.VS_PORTAL;
2519 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2520 validatedState = ValidatedState.VS_PARTIAL;
2521 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2522 validatedState = ValidatedState.VS_VALID;
2523 } else {
2524 validatedState = ValidatedState.VS_INVALID;
2525 }
2526 d.setValidatedState(validatedState);
2527 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2528 d.setCapabilities(nc.getCapabilitiesInternal());
2529 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2530 builder.addNetworkDescription(d);
2531 }
2532 return builder.build();
2533 }
2534
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002535 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002536 public boolean isNetworkSupported(int networkType) {
2537 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002538 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002539 }
2540
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002541 /**
2542 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002543 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002544 * @return the ip properties for the active network, or {@code null} if
2545 * none is active
2546 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002547 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002548 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002549 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002550 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002551 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2552 if (nai == null) return null;
2553 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002554 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002555 }
2556
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002557 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002558 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002559 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002560 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002561 final LinkProperties lp = getLinkProperties(nai);
2562 if (lp == null) return null;
2563 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002564 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002565 }
2566
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002567 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002568 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002569 public LinkProperties getLinkProperties(Network network) {
2570 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002571 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2572 if (lp == null) return null;
2573 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002574 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002575 }
2576
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002577 @Nullable
2578 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002579 if (nai == null) {
2580 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002581 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002582 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002583 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002584 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002585 }
2586
lucaslinc582d502022-01-27 09:07:00 +08002587 @Override
2588 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002589 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002590 @NonNull String packageName, @Nullable String callingAttributionTag) {
2591 Objects.requireNonNull(packageName);
2592 Objects.requireNonNull(lp);
2593 enforceNetworkStackOrSettingsPermission();
2594 if (!checkAccessPermission(-1 /* pid */, uid)) {
2595 return null;
2596 }
2597 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2598 }
2599
Qingxi Lib2748102020-01-08 12:51:49 -08002600 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2601 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2602 }
2603
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002604 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002605 if (nai == null) return null;
2606 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002607 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002608 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002609 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002610 }
2611
2612 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002613 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2614 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002615 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002616 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002617 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002618 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002619 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002620 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002621 }
2622
lucaslinc582d502022-01-27 09:07:00 +08002623 @Override
lucaslind2b06132022-03-02 10:56:57 +08002624 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2625 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2626 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002627 Objects.requireNonNull(nc);
2628 Objects.requireNonNull(packageName);
2629 enforceNetworkStackOrSettingsPermission();
2630 if (!checkAccessPermission(-1 /* pid */, uid)) {
2631 return null;
2632 }
2633 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2634 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2635 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2636 callingAttributionTag);
2637 }
2638
lucaslin69e1aa92022-03-22 18:15:09 +08002639 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2640 if (nc.getUnderlyingNetworks() != null
2641 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2642 nc.setUnderlyingNetworks(null);
2643 }
2644 }
2645
Qingxi Libb8da982020-01-17 17:54:27 -08002646 @VisibleForTesting
2647 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002648 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002649 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2650 // this would be expensive (one more permission check every time any NC callback is
2651 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2652 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2653 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002654 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002655 if (!checkSettingsPermission(callerPid, callerUid)) {
2656 newNc.setUids(null);
2657 newNc.setSSID(null);
2658 }
Etan Cohen107ae952018-12-30 17:59:59 -08002659 if (newNc.getNetworkSpecifier() != null) {
2660 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2661 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002662 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2663 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002664 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2665 newNc.setAdministratorUids(new int[0]);
2666 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002667 if (!checkAnyPermissionOf(mContext,
Benedict Wong53de25f2021-03-24 14:01:51 -07002668 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002669 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002670 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002671 }
lucaslin69e1aa92022-03-22 18:15:09 +08002672 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002673
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002674 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002675 }
2676
Roshan Pius98f59ec2021-02-23 08:47:39 -08002677 /**
2678 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002679 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002680 * NetworkCapabilities.
2681 * Note: This wrapper does not support any sort of invalidation and thus must not be
2682 * persistent or long-lived. It may only be used for the time necessary to
2683 * compute the redactions required by one particular NetworkCallback or
2684 * synchronous call.
2685 */
2686 private class RedactionPermissionChecker {
2687 private final int mCallingPid;
2688 private final int mCallingUid;
2689 @NonNull private final String mCallingPackageName;
2690 @Nullable private final String mCallingAttributionTag;
2691
2692 private Boolean mHasLocationPermission = null;
2693 private Boolean mHasLocalMacAddressPermission = null;
2694 private Boolean mHasSettingsPermission = null;
2695
2696 RedactionPermissionChecker(int callingPid, int callingUid,
2697 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2698 mCallingPid = callingPid;
2699 mCallingUid = callingUid;
2700 mCallingPackageName = callingPackageName;
2701 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002702 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002703
2704 private boolean hasLocationPermissionInternal() {
2705 final long token = Binder.clearCallingIdentity();
2706 try {
2707 return mLocationPermissionChecker.checkLocationPermission(
2708 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2709 null /* message */);
2710 } finally {
2711 Binder.restoreCallingIdentity(token);
2712 }
2713 }
2714
2715 /**
2716 * Returns whether the app holds location permission or not (might return cached result
2717 * if the permission was already checked before).
2718 */
2719 public boolean hasLocationPermission() {
2720 if (mHasLocationPermission == null) {
2721 // If there is no cached result, perform the check now.
2722 mHasLocationPermission = hasLocationPermissionInternal();
2723 }
2724 return mHasLocationPermission;
2725 }
2726
2727 /**
2728 * Returns whether the app holds local mac address permission or not (might return cached
2729 * result if the permission was already checked before).
2730 */
2731 public boolean hasLocalMacAddressPermission() {
2732 if (mHasLocalMacAddressPermission == null) {
2733 // If there is no cached result, perform the check now.
2734 mHasLocalMacAddressPermission =
2735 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2736 }
2737 return mHasLocalMacAddressPermission;
2738 }
2739
2740 /**
2741 * Returns whether the app holds settings permission or not (might return cached
2742 * result if the permission was already checked before).
2743 */
2744 public boolean hasSettingsPermission() {
2745 if (mHasSettingsPermission == null) {
2746 // If there is no cached result, perform the check now.
2747 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2748 }
2749 return mHasSettingsPermission;
2750 }
2751 }
2752
2753 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2754 @NetworkCapabilities.NetCapability long redaction) {
2755 return (redactions & redaction) != 0;
2756 }
2757
2758 /**
2759 * Use the provided |applicableRedactions| to check the receiving app's
2760 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2761 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2762 * before being sent to the corresponding app.
2763 */
2764 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2765 @NetworkCapabilities.RedactionType long applicableRedactions,
2766 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2767 boolean includeLocationSensitiveInfo) {
2768 long redactions = applicableRedactions;
2769 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2770 if (includeLocationSensitiveInfo
2771 && redactionPermissionChecker.hasLocationPermission()) {
2772 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2773 }
2774 }
2775 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2776 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2777 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2778 }
2779 }
2780 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2781 if (redactionPermissionChecker.hasSettingsPermission()) {
2782 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2783 }
2784 }
2785 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002786 }
2787
Qingxi Lib2748102020-01-08 12:51:49 -08002788 @VisibleForTesting
2789 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002790 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002791 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002792 int callingPid, int callingUid, @NonNull String callingPkgName,
2793 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002794 if (nc == null) {
2795 return null;
2796 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002797 // Avoid doing location permission check if the transport info has no location sensitive
2798 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002799 final RedactionPermissionChecker redactionPermissionChecker =
2800 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2801 callingAttributionTag);
2802 final long redactions = retrieveRequiredRedactions(
2803 nc.getApplicableRedactions(), redactionPermissionChecker,
2804 includeLocationSensitiveInfo);
2805 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002806 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002807 // TODO : calling UID is redacted because apps should generally not know what UID is
2808 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002809 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002810 newNc.setOwnerUid(INVALID_UID);
2811 return newNc;
2812 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002813 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2814 if (nc.hasTransport(TRANSPORT_VPN)) {
2815 // Owner UIDs already checked above. No need to re-check.
2816 return newNc;
2817 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002818 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2819 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002820 // compatibility for older apps.
2821 if (!includeLocationSensitiveInfo
2822 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002823 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002824 newNc.setOwnerUid(INVALID_UID);
2825 return newNc;
2826 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002827 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002828 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002829 newNc.setOwnerUid(INVALID_UID);
2830 }
Qingxi Lib2748102020-01-08 12:51:49 -08002831 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002832 }
2833
lucaslinc582d502022-01-27 09:07:00 +08002834 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002835 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2836 LinkProperties lp, int callerPid, int callerUid) {
2837 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002838 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2839 // this would be expensive (one more permission check every time any LP callback is
2840 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2841 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2842 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002843
2844 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2845 final boolean needsSanitization =
2846 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2847 if (!needsSanitization) {
2848 return new LinkProperties(lp);
2849 }
2850
2851 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002852 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002853 }
2854
2855 final LinkProperties newLp = new LinkProperties(lp);
2856 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2857 // object gets parceled.
2858 newLp.setCaptivePortalApiUrl(null);
2859 newLp.setCaptivePortalData(null);
2860 return newLp;
2861 }
2862
Roshan Pius08c94fb2020-01-16 12:17:17 -08002863 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2864 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002865 // There is no need to track the effective UID of the request here. If the caller
2866 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002867 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002868 // Unprivileged apps can only pass in null or their own UID.
2869 if (nc.getUids() == null) {
2870 // If the caller passes in null, the callback will also match networks that do not
2871 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2872 // In this case, redact everything in the request immediately. This ensures that the
2873 // app is not able to get any redacted information by filing an unredacted request
2874 // and observing whether the request matches something.
2875 if (nc.getNetworkSpecifier() != null) {
2876 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2877 }
2878 } else {
2879 nc.setSingleUid(callerUid);
2880 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002881 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002882 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002883 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002884
2885 // Clear owner UID; this can never come from an app.
2886 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002887 }
2888
Chalard Jean38354d12018-03-20 19:13:57 +09002889 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002890 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002891 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2892 }
2893 }
2894
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002895 @Override
2896 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2897 enforceAccessPermission();
2898 final int callerUid = Binder.getCallingUid();
2899 final long token = Binder.clearCallingIdentity();
2900 try {
2901 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2902 } finally {
2903 Binder.restoreCallingIdentity(token);
2904 }
2905 }
2906
junyulaiebd15162021-03-03 12:09:05 +08002907 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002908 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002909 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002910 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002911 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002912
Serik Beketayev05130302021-01-15 16:47:25 -08002913 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002914 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002915 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2916 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002917 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002918 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002919 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002920 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2921 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002922 }
2923 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002924 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002925 }
2926
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002927 @Override
junyulaiebd15162021-03-03 12:09:05 +08002928 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002929 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002930 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002931 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002932
2933 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2934 for (Network network : getAllNetworks()) {
2935 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09002936 final boolean includeNetwork = (nai != null) && nai.isCreated();
2937 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002938 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2939 // NetworkCapabilities, which may contain UIDs of apps to which the
2940 // network applies. Should the UIDs be cleared so as not to leak or
2941 // interfere ?
2942 result.add(nai.getNetworkStateSnapshot());
2943 }
2944 }
2945 return result;
2946 }
2947
2948 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002949 public boolean isActiveNetworkMetered() {
2950 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002951
Qingxi Lib2748102020-01-08 12:51:49 -08002952 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002953 if (caps != null) {
2954 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2955 } else {
2956 // Always return the most conservative value
2957 return true;
2958 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002959 }
2960
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002961 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002962 * Ensures that the system cannot call a particular method.
2963 */
2964 private boolean disallowedBecauseSystemCaller() {
2965 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002966 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2967 // for devices launched with Q and above. However, existing devices upgrading to Q and
2968 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002969 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002970 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002971 log("This method exists only for app backwards compatibility"
2972 + " and must not be called by system services.");
2973 return true;
2974 }
2975 return false;
2976 }
2977
paulhub2c28682021-08-18 18:35:54 +08002978 private int getAppUid(final String app, final UserHandle user) {
2979 final PackageManager pm =
2980 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2981 final long token = Binder.clearCallingIdentity();
2982 try {
2983 return pm.getPackageUid(app, 0 /* flags */);
2984 } catch (PackageManager.NameNotFoundException e) {
2985 return -1;
2986 } finally {
2987 Binder.restoreCallingIdentity(token);
2988 }
2989 }
2990
2991 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2992 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2993 if (getAppUid(packageName, user) != callingUid) {
2994 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2995 }
2996 }
2997
Lorenzo Colitti23862912018-09-28 11:31:55 +09002998 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002999 * Ensure that a network route exists to deliver traffic to the specified
3000 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07003001 * @param networkType the type of the network over which traffic to the
3002 * specified host is to be routed
3003 * @param hostAddress the IP address of the host to which the route is
3004 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08003005 * @return {@code true} on success, {@code false} on failure
3006 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09003007 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003008 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
3009 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003010 if (disallowedBecauseSystemCaller()) {
3011 return false;
3012 }
paulhub2c28682021-08-18 18:35:54 +08003013 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003014 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003015 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003016 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003017 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003018
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003019 InetAddress addr;
3020 try {
3021 addr = InetAddress.getByAddress(hostAddress);
3022 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003023 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003024 return false;
3025 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003026
The Android Open Source Project28527d22009-03-03 19:31:44 -08003027 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003028 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003029 return false;
3030 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003031
3032 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3033 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003034 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003035 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3036 } else {
3037 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3038 }
3039 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003040 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003041
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003042 DetailedState netState;
3043 synchronized (nai) {
3044 netState = nai.networkInfo.getDetailedState();
3045 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003046
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003047 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003048 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003049 log("requestRouteToHostAddress on down network "
3050 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003051 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003052 }
3053 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003054 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003055
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003056 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003057 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003058 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003059 LinkProperties lp;
3060 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003061 synchronized (nai) {
3062 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003063 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003064 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003065 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003066 if (DBG) {
3067 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3068 }
Wink Saville32506bc2013-06-29 21:10:57 -07003069 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003070 } finally {
3071 Binder.restoreCallingIdentity(token);
3072 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003073 }
3074
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003075 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003076 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003077 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003078 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003079 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003080 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003081 if (bestRoute.getGateway().equals(addr)) {
3082 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003083 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003084 } else {
3085 // if we will connect to this through another route, add a direct route
3086 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003087 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003088 }
3089 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003090 if (DBG) log("Adding legacy route " + bestRoute +
3091 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003092
3093 final String dst = bestRoute.getDestinationLinkAddress().toString();
3094 final String nextHop = bestRoute.hasGateway()
3095 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003096 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003097 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3098 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003099 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003100 return false;
3101 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003102 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003103 }
3104
paulhu7c0a2e62021-01-08 00:51:49 +08003105 class DnsResolverUnsolicitedEventCallback extends
3106 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003107 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003108 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003109 try {
3110 mHandler.sendMessage(mHandler.obtainMessage(
3111 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003112 new PrivateDnsValidationUpdate(event.netId,
3113 InetAddresses.parseNumericAddress(event.ipAddress),
3114 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003115 } catch (IllegalArgumentException e) {
3116 loge("Error parsing ip address in validation event");
3117 }
3118 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003119
3120 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003121 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3122 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003123 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3124 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3125 // event callback for certain nai. e.g. cellular. Register here to pass to
3126 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003127 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003128 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3129 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003130 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003131 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003132 }
3133 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003134
3135 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003136 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3137 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3138 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003139 }
dalyk1720e542018-03-05 12:42:22 -05003140
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003141 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003142 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003143 return this.VERSION;
3144 }
3145
3146 @Override
3147 public String getInterfaceHash() {
3148 return this.HASH;
3149 }
paulhu7c0a2e62021-01-08 00:51:49 +08003150 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003151
3152 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003153 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3154 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003155
paulhu7c0a2e62021-01-08 00:51:49 +08003156 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003157 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003158 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003159 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003160 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003161 }
3162 }
3163
Sudheer Shanka9967d462021-03-18 19:09:25 +00003164 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003165 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003166 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003167 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3168 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003169 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003170 };
3171
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003172 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003173 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003174 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003175 }
3176
Mark Fasheh7c999d82023-05-04 20:23:11 +00003177 static final class UidFrozenStateChangedArgs {
3178 final int[] mUids;
3179 final int[] mFrozenStates;
3180
3181 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3182 mUids = uids;
3183 mFrozenStates = frozenStates;
3184 }
3185 }
3186
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003187 /**
3188 * Check if the cell network is idle.
3189 * @return true if the cell network state is idle
3190 * false if the cell network state is active or unknown
3191 */
3192 private boolean isCellNetworkIdle() {
3193 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3194 if (defaultNai == null
3195 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3196 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3197 // cell network is not the default network, cell network state is unknown.
3198 // TODO(b/279380356): Track cell network state when the cell is not the default network
3199 return false;
3200 }
3201
3202 return !mNetworkActivityTracker.isDefaultNetworkActive();
3203 }
3204
Mark Fasheh7c999d82023-05-04 20:23:11 +00003205 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003206 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003207
3208 for (int i = 0; i < uids.length; i++) {
3209 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003210 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003211 } else {
3212 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003213 }
3214 }
3215
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003216 if (ownerUids.isEmpty()) {
3217 return;
3218 }
3219
3220 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3221 // Delay closing sockets to avoid waking the cell modem up.
3222 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3223 // than waking cell modem up.
3224 mPendingFrozenUids.addAll(ownerUids);
3225 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003226 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003227 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003228 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003229 loge("Exception in socket destroy: " + e);
3230 }
3231 }
3232 }
3233
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003234 private void closePendingFrozenSockets() {
3235 ensureRunningOnConnectivityServiceThread();
3236
3237 try {
3238 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3239 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3240 loge("Failed to close pending frozen app sockets: " + e);
3241 }
3242 mPendingFrozenUids.clear();
3243 }
3244
3245 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3246 mNetworkActivityTracker.handleReportNetworkActivity(params);
3247
3248 if (mDelayDestroyFrozenSockets
3249 && params.isActive
3250 && params.label == TRANSPORT_CELLULAR
3251 && !mPendingFrozenUids.isEmpty()) {
3252 closePendingFrozenSockets();
3253 }
3254 }
3255
3256 /**
3257 * If the cellular network is no longer the default network, close pending frozen sockets.
3258 *
3259 * @param newNetwork new default network
3260 * @param oldNetwork old default network
3261 */
3262 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3263 NetworkAgentInfo oldNetwork) {
3264 final boolean isOldNetworkCellular = oldNetwork != null
3265 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3266 final boolean isNewNetworkCellular = newNetwork != null
3267 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3268
3269 if (isOldNetworkCellular
3270 && !isNewNetworkCellular
3271 && !mPendingFrozenUids.isEmpty()) {
3272 closePendingFrozenSockets();
3273 }
3274 }
3275
3276 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3277 pw.println("CloseFrozenAppSockets:");
3278 pw.increaseIndent();
3279 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3280 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3281 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3282 pw.decreaseIndent();
3283 }
3284
Junyu Lai155760b2023-10-05 14:51:00 +08003285 private void dumpBpfProgramStatus(IndentingPrintWriter pw) {
3286 pw.println("Bpf Program Status:");
3287 pw.increaseIndent();
3288 try {
3289 pw.print("CGROUP_INET_INGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003290 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_INGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003291 pw.print("CGROUP_INET_EGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003292 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_EGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003293 pw.print("CGROUP_INET_SOCK_CREATE: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003294 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_CREATE));
Junyu Lai155760b2023-10-05 14:51:00 +08003295 pw.print("CGROUP_INET4_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003296 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003297 pw.print("CGROUP_INET6_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003298 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003299 } catch (IOException e) {
3300 pw.println(" IOException");
3301 }
3302 pw.decreaseIndent();
3303 }
3304
Mark Fasheh7c999d82023-05-04 20:23:11 +00003305 @VisibleForTesting
3306 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003307 @VisibleForTesting
3308 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3309 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003310
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003311 @VisibleForTesting
3312 public static final String ALLOW_SYSUI_CONNECTIVITY_REPORTS =
3313 "allow_sysui_connectivity_reports";
3314
Paul Jensen83f5d572014-08-29 09:54:01 -04003315 private void enforceInternetPermission() {
3316 mContext.enforceCallingOrSelfPermission(
3317 android.Manifest.permission.INTERNET,
3318 "ConnectivityService");
3319 }
3320
The Android Open Source Project28527d22009-03-03 19:31:44 -08003321 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003322 mContext.enforceCallingOrSelfPermission(
3323 android.Manifest.permission.ACCESS_NETWORK_STATE,
3324 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003325 }
3326
lucaslinc582d502022-01-27 09:07:00 +08003327 private boolean checkAccessPermission(int pid, int uid) {
3328 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3329 == PERMISSION_GRANTED;
3330 }
3331
paulhua6ee2122021-02-22 15:40:43 +08003332 /**
3333 * Performs a strict and comprehensive check of whether a calling package is allowed to
3334 * change the state of network, as the condition differs for pre-M, M+, and
3335 * privileged/preinstalled apps. The caller is expected to have either the
3336 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3337 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3338 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3339 * permission and cannot be revoked. See http://b/23597341
3340 *
3341 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3342 * of this app will be updated to the current time.
3343 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003344 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003345 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3346 == PackageManager.PERMISSION_GRANTED) {
3347 return;
3348 }
3349
3350 if (callingPkg == null) {
3351 throw new SecurityException("Calling package name is null.");
3352 }
3353
3354 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3355 final int uid = mDeps.getCallingUid();
3356 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3357 callingPkg, callingAttributionTag, null /* message */);
3358
3359 if (mode == AppOpsManager.MODE_ALLOWED) {
3360 return;
3361 }
3362
3363 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3364 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3365 return;
3366 }
3367
3368 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3369 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3370 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003371 }
3372
Charles He9369e612017-05-15 17:07:18 +01003373 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003374 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003375 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003376 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003377 }
3378
Quang Luong98858d62023-02-11 00:25:24 +00003379 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003380 enforceAnyPermissionOf(mContext,
3381 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003382 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003383 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3384 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3385 }
3386
paulhu8e96a752019-08-12 16:25:11 +08003387 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003388 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003389 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003390 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003391 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003392 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003393 }
3394
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003395 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003396 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003397 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003398 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003399 android.Manifest.permission.NETWORK_SETTINGS,
3400 android.Manifest.permission.NETWORK_FACTORY,
3401 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3402 }
3403
3404 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003405 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003406 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003407 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003408 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3409 android.Manifest.permission.NETWORK_FACTORY,
3410 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3411 }
3412
lucaslin69e1aa92022-03-22 18:15:09 +08003413 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3414 return PERMISSION_GRANTED == mContext.checkPermission(
3415 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3416 || PERMISSION_GRANTED == mContext.checkPermission(
3417 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3418 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003419 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003420 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003421 }
3422
Chalard Jean9a396cc2018-02-21 18:43:54 +09003423 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003424 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003425 android.Manifest.permission.NETWORK_SETTINGS,
3426 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003427 }
3428
3429 private boolean checkSettingsPermission(int pid, int uid) {
3430 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003431 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3432 || PERMISSION_GRANTED == mContext.checkPermission(
3433 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003434 }
3435
paulhu8e96a752019-08-12 16:25:11 +08003436 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003437 enforceNetworkStackPermissionOr(mContext,
3438 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003439 }
3440
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003441 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003442 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003443 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003444 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003445 }
3446
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003447 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003448 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003449 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3450 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003451 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003452 }
3453
James Mattis8378aec2021-01-26 14:05:36 -08003454 private void enforceOemNetworkPreferencesPermission() {
3455 mContext.enforceCallingOrSelfPermission(
3456 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3457 "ConnectivityService");
3458 }
3459
James Mattisfa270db2021-05-31 17:11:10 -07003460 private void enforceManageTestNetworksPermission() {
3461 mContext.enforceCallingOrSelfPermission(
3462 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3463 "ConnectivityService");
3464 }
3465
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003466 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003467 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003468 android.Manifest.permission.NETWORK_STACK,
3469 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003470 }
3471
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003472 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003473 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003474 android.Manifest.permission.NETWORK_STACK,
3475 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3476 }
3477
Chris Göllnercc962022023-12-26 09:55:32 +00003478 private boolean checkSystemBarServicePermission(int pid, int uid) {
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003479 return checkAnyPermissionOf(mContext, pid, uid,
3480 android.Manifest.permission.STATUS_BAR_SERVICE);
3481 }
3482
paulhu1a407652019-03-22 16:35:06 +08003483 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003484 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003485 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003486 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3487 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003488 }
3489
Paul Hu8fc2a552022-05-04 18:44:42 +08003490 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3491 boolean checkUidsAllowedList) {
3492 if (PermissionUtils.checkAnyPermissionOf(mContext,
3493 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3494 return true;
3495 }
3496
3497 // fallback to ConnectivityInternalPermission
3498 // TODO: Remove this fallback check after all apps have declared
3499 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3500 if (PermissionUtils.checkAnyPermissionOf(mContext,
3501 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3502 return true;
3503 }
3504
3505 // Check whether uid is in allowed on restricted networks list.
3506 if (checkUidsAllowedList
3507 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3508 return true;
3509 }
3510 return false;
3511 }
3512
3513 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3514 final int callingUid = mDeps.getCallingUid();
3515 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3516 throw new SecurityException("ConnectivityService: user " + callingUid
3517 + " has no permission to access restricted network.");
3518 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003519 }
3520
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003521 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003522 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003523 }
3524
Roshan Pius98f59ec2021-02-23 08:47:39 -08003525 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3526 return PERMISSION_GRANTED == mContext.checkPermission(
3527 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3528 }
3529
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003530 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003531 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003532 }
3533
3534 private void sendInetConditionBroadcast(NetworkInfo info) {
3535 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3536 }
3537
Wink Saville4f0de1e2011-08-04 15:01:58 -07003538 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003539 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003540 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003541 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003542 if (info.isFailover()) {
3543 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3544 info.setFailover(false);
3545 }
3546 if (info.getReason() != null) {
3547 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3548 }
3549 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003550 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3551 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003552 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003553 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003554 return intent;
3555 }
3556
3557 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3558 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3559 }
3560
Michael Groover73f69482023-01-27 11:01:25 -06003561 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3562 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003563 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3564 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003565 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003566 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003567 if (!mSystemReady
3568 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003569 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003570 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003571 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003572 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003573 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003574 }
3575
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003576 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003577 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003578 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003579 final NetworkInfo ni = intent.getParcelableExtra(
3580 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003581 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3582 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003583 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003584 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003585 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003586 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003587 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003588 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003589 } finally {
3590 Binder.restoreCallingIdentity(ident);
3591 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003592 }
3593 }
3594
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003595 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3596 NetworkInfo info) {
3597 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003598 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003599
3600 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3601 try {
3602 // This allows us to discard older broadcasts still waiting to be delivered
3603 // which have the same namespace and key.
3604 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3605 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3606 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003607 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003608 } catch (UnsupportedApiLevelException e) {
3609 Log.wtf(TAG, "Using unsupported API" + e);
3610 }
3611 }
3612
3613 @VisibleForTesting
3614 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3615 final StringBuilder sb = new StringBuilder();
3616 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3617 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3618 sb.append(info.getExtraInfo());
3619 return sb.toString();
3620 }
3621
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003622 /**
Aaron Huang96011892020-06-27 07:18:23 +08003623 * Called by SystemServer through ConnectivityManager when the system is ready.
3624 */
3625 @Override
3626 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003627 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003628 throw new SecurityException("Calling Uid is not system uid.");
3629 }
3630 systemReadyInternal();
3631 }
3632
3633 /**
3634 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003635 */
3636 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003637 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003638 // Load flags after PackageManager is ready to query module version
3639 mFlags.loadFlags(mDeps, mContext);
3640
Aaron Huang9a57acf2020-12-08 10:03:29 +08003641 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3642 // listening network request which is sent by MultipathPolicyTracker won't be added
3643 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3644 // be called after PermissionMonitor#startMonitoring().
3645 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3646 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3647 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003648 final ConditionVariable startMonitoringDone = new ConditionVariable();
3649 mHandler.post(() -> {
3650 mPermissionMonitor.startMonitoring();
3651 startMonitoringDone.open();
3652 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003653 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003654 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003655
Hugo Benichie5220992017-04-26 14:53:28 +09003656 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003657 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003658 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003659 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003660 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003661 }
3662 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003663
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003664 // Create network requests for always-on networks.
3665 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003666
3667 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003668 // Note that updating can be skipped here if the list is empty only because no uid
3669 // rules are applied before system ready. Normally, the empty uid list means to clear
3670 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003671 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3672 updateMobileDataPreferredUids();
3673 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003674
3675 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003676 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003677 mBpfNetMaps.setPullAtomCallback(mContext);
3678 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003679 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3680 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003681 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3682 // have permission problem. While CV#block() is unbounded in time and can in principle block
3683 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3684 // could have blocked forever too.
3685 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003686 }
3687
The Android Open Source Project28527d22009-03-03 19:31:44 -08003688 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003689 * Start listening for default data network activity state changes.
3690 */
3691 @Override
3692 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003693 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003694 }
3695
3696 /**
3697 * Stop listening for default data network activity state changes.
3698 */
3699 @Override
3700 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003701 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003702 }
3703
3704 /**
3705 * Check whether the default network radio is currently active.
3706 */
3707 @Override
3708 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003709 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003710 }
3711
3712 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003713 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003714 * and set it on it's iface.
3715 */
Junyu Lai970963e2022-10-25 15:46:47 +08003716 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003717 final String iface = newLp.getInterfaceName();
3718 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003719 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003720 // Silently ignore unset MTU value.
3721 return;
3722 }
Hansen Kurli04252032022-12-07 11:21:49 +00003723 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3724 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3725 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003726 return;
3727 }
Hansen Kurli04252032022-12-07 11:21:49 +00003728 // Cannot set MTU without interface name
3729 if (TextUtils.isEmpty(iface)) {
3730 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003731 return;
3732 }
sy.yun4aa73922013-09-02 05:24:09 +09003733
Hansen Kurli04252032022-12-07 11:21:49 +00003734 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3735 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003736 return;
3737 }
3738
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003739 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003740 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003741 mNetd.interfaceSetMtu(iface, mtu);
3742 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003743 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003744 }
3745 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003746
Chenbo Feng15416292018-11-08 17:36:21 -08003747 @VisibleForTesting
3748 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003749
Junyu Lai970963e2022-10-25 15:46:47 +08003750 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003751 String[] values = null;
3752 if (tcpBufferSizes != null) {
3753 values = tcpBufferSizes.split(",");
3754 }
3755
3756 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003757 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003758 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3759 values = tcpBufferSizes.split(",");
3760 }
3761
3762 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3763
3764 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003765 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003766
Chenbo Feng15416292018-11-08 17:36:21 -08003767 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3768 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3769 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003770 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003771 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003772 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003773 }
3774 }
3775
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003776 @Override
3777 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003778 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003779 NETWORK_RESTORE_DELAY_PROP_NAME);
3780 if(restoreDefaultNetworkDelayStr != null &&
3781 restoreDefaultNetworkDelayStr.length() != 0) {
3782 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003783 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003784 } catch (NumberFormatException e) {
3785 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003786 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003787 // if the system property isn't set, use the value for the apn type
3788 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3789
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003790 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3791 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003792 }
3793 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003794 }
3795
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003796 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003797 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003798 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003799 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003800 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003801 // Start gathering diagnostic information.
3802 netDiags.add(new NetworkDiagnostics(
3803 nai.network,
3804 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003805 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003806 DIAG_TIME_MS));
3807 }
3808
3809 for (NetworkDiagnostics netDiag : netDiags) {
3810 pw.println();
3811 netDiag.waitForMeasurements();
3812 netDiag.dump(pw);
3813 }
3814 }
3815
The Android Open Source Project28527d22009-03-03 19:31:44 -08003816 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003817 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3818 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003819 if (!checkDumpPermission(mContext, TAG, writer)) return;
3820
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003821 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003822 }
3823
lucaslin99473f62020-12-10 15:10:54 +08003824 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3825 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3826 != PackageManager.PERMISSION_GRANTED) {
3827 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003828 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003829 + " due to missing android.permission.DUMP permission");
3830 return false;
3831 } else {
3832 return true;
3833 }
3834 }
3835
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003836 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003837 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003838
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003839 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003840 dumpNetworkDiagnostics(pw);
3841 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003842 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003843 dumpNetworks(pw);
3844 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003845 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003846 dumpNetworkRequests(pw);
3847 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003848 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3849 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3850 dumpTrafficController(pw, fd, verbose);
3851 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003852 }
Erik Kline9647f382015-06-05 17:47:34 +09003853
Junyu Lai0da479b2022-04-20 15:06:29 +08003854 pw.println("NetworkProviders for:");
3855 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003856 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003857 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003858 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003859 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003860 pw.println();
3861
Chalard Jean5b409c72021-02-04 13:12:59 +09003862 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003863 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003864 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003865 pw.println("none");
3866 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003867 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003868 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003869 pw.println();
3870
James Mattis8b298a02021-06-01 22:34:04 -07003871 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003872 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003873 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003874 pw.decreaseIndent();
3875 pw.println();
3876
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003877 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003878 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003879 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003880 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003881 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003882
junyulaif2c67e42018-08-07 19:50:45 +08003883 pw.println("Status for known UIDs:");
3884 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003885 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003886 for (int i = 0; i < size; i++) {
3887 // Don't crash if the array is modified while dumping in bugreports.
3888 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003889 final int uid = mUidBlockedReasons.keyAt(i);
3890 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3891 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003892 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003893 } catch (ArrayIndexOutOfBoundsException e) {
3894 pw.println(" ArrayIndexOutOfBoundsException");
3895 } catch (ConcurrentModificationException e) {
3896 pw.println(" ConcurrentModificationException");
3897 }
3898 }
3899 pw.println();
3900 pw.decreaseIndent();
3901
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003902 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003903 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003904 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003905 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003906 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003907
Junyu Lai0da479b2022-04-20 15:06:29 +08003908 pw.println("Network Offers:");
3909 pw.increaseIndent();
3910 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3911 pw.println(offerInfo.offer);
3912 }
3913 pw.decreaseIndent();
3914 pw.println();
3915
Robert Greenwalt94e22142014-07-30 16:31:24 -07003916 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003917
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003918 pw.println();
markchien5e866652019-09-30 14:40:57 +08003919 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003920
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003921 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003922 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003923
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003924 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003925 dumpCloseFrozenAppSockets(pw);
3926
3927 pw.println();
Junyu Lai155760b2023-10-05 14:51:00 +08003928 dumpBpfProgramStatus(pw);
3929
3930 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003931
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003932 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003933 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003934 pw.println("mNetworkRequestInfoLogs (most recent first):");
3935 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003936 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003937 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003938
3939 pw.println();
3940 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3941 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003942 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003943 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003944
3945 pw.println();
3946 pw.println("NetTransition WakeLock activity (most recent first):");
3947 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003948 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3949 pw.println("total releases: " + mTotalWakelockReleases);
3950 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3951 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3952 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3953 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3954 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3955 }
James Mattiscb1e0362021-04-06 17:07:42 -07003956 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003957
3958 pw.println();
3959 pw.println("bandwidth update requests (by uid):");
3960 pw.increaseIndent();
3961 synchronized (mBandwidthRequests) {
3962 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3963 pw.println("[" + mBandwidthRequests.keyAt(i)
3964 + "]: " + mBandwidthRequests.valueAt(i));
3965 }
3966 }
3967 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003968 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003969
James Mattiscb1e0362021-04-06 17:07:42 -07003970 pw.println();
3971 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3972 pw.increaseIndent();
3973 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003974 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003975 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003976
3977 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003978
3979 pw.println();
3980 pw.println("Permission Monitor:");
3981 pw.increaseIndent();
3982 mPermissionMonitor.dump(pw);
3983 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003984
3985 pw.println();
3986 pw.println("Legacy network activity:");
3987 pw.increaseIndent();
3988 mNetworkActivityTracker.dump(pw);
3989 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003990 }
3991
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003992 private void dumpNetworks(IndentingPrintWriter pw) {
3993 for (NetworkAgentInfo nai : networksSortedById()) {
3994 pw.println(nai.toString());
3995 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003996 pw.println("Nat464Xlat:");
3997 pw.increaseIndent();
3998 nai.dumpNat464Xlat(pw);
3999 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004000 pw.println(String.format(
4001 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
4002 nai.numForegroundNetworkRequests(),
4003 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
4004 nai.numBackgroundNetworkRequests(),
4005 nai.numNetworkRequests()));
4006 pw.increaseIndent();
4007 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4008 pw.println(nai.requestAt(i).toString());
4009 }
4010 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004011 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004012 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004013 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004014 pw.decreaseIndent();
4015 pw.decreaseIndent();
4016 }
4017 }
4018
James Mattis8b298a02021-06-01 22:34:04 -07004019 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
4020 if (!mProfileNetworkPreferences.isEmpty()) {
4021 pw.println("Profile preferences:");
4022 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09004023 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07004024 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08004025 }
James Mattis8b298a02021-06-01 22:34:04 -07004026 if (!mOemNetworkPreferences.isEmpty()) {
4027 pw.println("OEM preferences:");
4028 pw.increaseIndent();
4029 pw.println(mOemNetworkPreferences);
4030 pw.decreaseIndent();
4031 }
4032 if (!mMobileDataPreferredUids.isEmpty()) {
4033 pw.println("Mobile data preferred UIDs:");
4034 pw.increaseIndent();
4035 pw.println(mMobileDataPreferredUids);
4036 pw.decreaseIndent();
4037 }
James Mattis45d81842021-01-10 14:24:24 -08004038
James Mattis8b298a02021-06-01 22:34:04 -07004039 pw.println("Default requests:");
4040 pw.increaseIndent();
4041 dumpPerAppDefaultRequests(pw);
4042 pw.decreaseIndent();
4043 }
4044
4045 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08004046 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
4047 if (mDefaultRequest == defaultRequest) {
4048 continue;
4049 }
4050
James Mattis8b298a02021-06-01 22:34:04 -07004051 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
4052 final String networkOutput;
4053 if (null == satisfier) {
4054 networkOutput = "null";
4055 } else if (mNoServiceNetwork.equals(satisfier)) {
4056 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08004057 } else {
James Mattis8b298a02021-06-01 22:34:04 -07004058 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08004059 }
James Mattis8b298a02021-06-01 22:34:04 -07004060 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
4061 ? "" : " asUid: " + defaultRequest.mAsUid;
4062 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
4063 + defaultRequest.mPid + asUidString + "]";
4064 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4065 + " Preference order: " + defaultRequest.mPreferenceOrder
4066 + " Tracked UIDs: " + defaultRequest.getUids();
4067 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004068 }
4069 }
4070
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004071 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004072 NetworkRequestInfo[] infos = null;
4073 while (infos == null) {
4074 try {
4075 infos = requestsSortedById();
4076 } catch (ConcurrentModificationException e) {
4077 // mNetworkRequests should only be accessed from handler thread, except dump().
4078 // As dump() is never called in normal usage, it would be needlessly expensive
4079 // to lock the collection only for its benefit. Instead, retry getting the
4080 // requests if ConcurrentModificationException is thrown during dump().
4081 }
4082 }
4083 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004084 pw.println(nri.toString());
4085 }
4086 }
4087
Ken Chene6d511f2022-01-25 11:10:42 +08004088 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4089 boolean verbose) {
4090 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004091 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004092 } catch (ServiceSpecificException e) {
4093 pw.println(e.getMessage());
4094 } catch (IOException e) {
4095 loge("Dump BPF maps failed, " + e);
4096 }
4097 }
4098
Chalard Jean524f0b12021-10-25 21:11:56 +09004099 private void dumpAllRequestInfoLogsToLogcat() {
4100 try (PrintWriter logPw = new PrintWriter(new Writer() {
4101 @Override
4102 public void write(final char[] cbuf, final int off, final int len) {
4103 // This method is called with 0-length and 1-length arrays for empty strings
4104 // or strings containing only the DEL character.
4105 if (len <= 1) return;
4106 Log.e(TAG, new String(cbuf, off, len));
4107 }
4108 @Override public void flush() {}
4109 @Override public void close() {}
4110 })) {
4111 mNetworkRequestInfoLogs.dump(logPw);
4112 }
4113 }
4114
Hugo Benichia480ba52018-09-03 08:19:02 +09004115 /**
4116 * Return an array of all current NetworkAgentInfos sorted by network id.
4117 */
4118 private NetworkAgentInfo[] networksSortedById() {
4119 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004120 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004121 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004122 return networks;
4123 }
4124
4125 /**
4126 * Return an array of all current NetworkRequest sorted by request id.
4127 */
James Mattis258ea3c2020-11-15 15:04:40 -08004128 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004129 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004130 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004131 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004132 // Sort the array based off the NRI containing the min requestId in its requests.
4133 Arrays.sort(requests,
4134 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4135 Comparator.comparingInt(req -> req.requestId)).requestId
4136 )
4137 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004138 return requests;
4139 }
4140
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004141 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004142 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004143 if (officialNai != null && officialNai.equals(nai)) return true;
4144 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004145 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004146 " - " + nai);
4147 }
4148 return false;
4149 }
4150
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004151 private boolean isDisconnectRequest(Message msg) {
4152 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4153 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4154 return info.getState() == NetworkInfo.State.DISCONNECTED;
4155 }
4156
Robert Greenwalt2034b912009-08-12 16:08:25 -07004157 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004158 private class NetworkStateTrackerHandler extends Handler {
4159 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004160 super(looper);
4161 }
4162
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004163 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004164 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4165 final NetworkAgentInfo nai = arg.first;
4166 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004167 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004168 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004169 }
4170 return;
4171 }
4172
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004173 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004174 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004175 return;
4176 }
4177
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004178 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004179 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean78c9a382023-10-26 19:53:33 +09004180 final NetworkCapabilities proposed = (NetworkCapabilities) arg.second;
4181 if (!nai.respectsNcStructuralConstraints(proposed)) {
4182 Log.wtf(TAG, "Agent " + nai + " violates nc structural constraints : "
4183 + nai.networkCapabilities + " -> " + proposed);
4184 disconnectAndDestroyNetwork(nai);
4185 return;
4186 }
4187 nai.setDeclaredCapabilities(proposed);
Chalard Jean39b12d42022-02-27 12:08:49 +09004188 final NetworkCapabilities sanitized =
4189 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004190 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004191 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004192 break;
4193 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004194 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004195 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004196 processLinkPropertiesFromAgent(nai, newLp);
4197 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004198 break;
4199 }
4200 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004201 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004202 updateNetworkInfo(nai, info);
4203 break;
4204 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004205 case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
4206 final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
Chalard Jean1e4c2182023-10-06 18:45:53 +09004207 updateLocalNetworkConfig(nai, nai.localNetworkConfig, config);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004208 break;
4209 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004210 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004211 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004212 break;
4213 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004214 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004215 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004216 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004217 // Note that if the NAI had been connected, this would affect the
4218 // score, and therefore would require re-mixing the score and performing
4219 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004220 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004221 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4222 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004223 // Mark the network as temporarily accepting partial connectivity so that it
4224 // will be validated (and possibly become default) even if it only provides
4225 // partial internet access. Note that if user connects to partial connectivity
4226 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4227 // out of wifi coverage) and if the same wifi is available again, the device
4228 // will auto connect to this wifi even though the wifi has "no internet".
4229 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004230 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004231 break;
4232 }
junyulai011b1f12019-01-03 18:50:15 +08004233 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004234 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004235 break;
4236 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004237 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004238 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004239 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004240
4241 if (isLegacyLockdownNai(nai)
4242 && (underlying == null || underlying.size() != 1)) {
4243 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4244 + " must have exactly one underlying network: " + underlying);
4245 }
4246
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004247 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4248 nai.declaredUnderlyingNetworks = (underlying != null)
4249 ? underlying.toArray(new Network[0]) : null;
4250
4251 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4252 if (DBG) {
4253 log(nai.toShortString() + " changed underlying networks to "
4254 + Arrays.toString(nai.declaredUnderlyingNetworks));
4255 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004256 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004257 notifyIfacesChangedForNetworkStats();
4258 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004259 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004260 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004261 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4262 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4263 nai.teardownDelayMs = msg.arg1;
4264 } else {
4265 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4266 }
Chalard Jean550b5212021-03-05 23:07:53 +09004267 break;
4268 }
4269 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4270 nai.setLingerDuration((int) arg.second);
4271 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004272 }
Tyler Wear72388212021-09-09 14:49:02 -07004273 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4274 DscpPolicy policy = (DscpPolicy) arg.second;
4275 if (mDscpPolicyTracker != null) {
4276 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4277 }
4278 break;
4279 }
4280 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4281 if (mDscpPolicyTracker != null) {
4282 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4283 }
4284 break;
4285 }
4286 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4287 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004288 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004289 }
4290 break;
4291 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004292 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004293 if (!nai.everConnected()) {
4294 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4295 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004296 teardownUnneededNetwork(nai);
4297 break;
4298 }
4299
4300 if (nai.isDestroyed()) {
4301 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4302 + ", ignoring");
4303 break;
4304 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004305
4306 final int timeoutMs = (int) arg.second;
4307 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4308 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4309 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4310 }
4311
4312 // Marking a network awaiting replacement is used to ensure that any requests
4313 // satisfied by the network do not switch to another network until a
4314 // replacement is available or the wait for a replacement times out.
4315 // If the network is inactive (i.e., nascent or lingering), then there are no
4316 // such requests, and there is no point keeping it. Just tear it down.
4317 // Note that setLingerDuration(0) cannot be used to do this because the network
4318 // could be nascent.
4319 nai.clearInactivityState();
4320 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4321 Log.d(TAG, nai.toShortString()
4322 + " marked awaiting replacement is unneeded, tearing down instead");
4323 teardownUnneededNetwork(nai);
4324 break;
4325 }
4326
4327 Log.d(TAG, "Marking " + nai.toShortString()
4328 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4329 destroyNativeNetwork(nai);
4330
4331 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4332 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4333 // consider the fact that the network could already have disconnected or been
4334 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4335 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4336 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4337 mKeepaliveTracker.handleStopAllKeepalives(nai,
4338 SocketKeepalive.ERROR_INVALID_NETWORK);
4339
4340 nai.updateScoreForNetworkAgentUpdate();
4341 // This rematch is almost certainly not going to result in any changes, because
4342 // the destroyed flag is only just above the "current satisfier wins"
4343 // tie-breaker. But technically anything that affects scoring should rematch.
4344 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004345 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004346 break;
4347 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004348 }
4349 }
4350
4351 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004352 final int netId = msg.arg2;
4353 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004354 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004355 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004356 switch (msg.what) {
4357 default:
4358 return false;
lucasline117e2e2019-10-22 18:27:33 +08004359 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004360 if (nai == null) {
4361 break;
4362 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004363 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4364 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004365 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004366 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004367 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004368 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004369 if (probePrivateDnsCompleted) {
4370 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4371 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004372 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004373 }
4374 // Only show the notification when the private DNS is broken and the
4375 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004376 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004377 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4378 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004379 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004380 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4381 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4382 // private DNS is broken, it means this network is being reevaluated.
4383 // Either probing private DNS is not necessary any more or it hasn't been
4384 // done yet. In either case, the networkCapabilities should be updated to
4385 // reflect the new status.
4386 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004387 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004388 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004389 }
4390 break;
4391 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004392 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004393 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4394
Erik Kline31b4a9e2018-01-11 21:07:29 +09004395 if (nai == null) break;
4396
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004397 handleNetworkTested(nai, results.mTestResult,
4398 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004399 break;
4400 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004401 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004402 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004403 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004404 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004405 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004406 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004407 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4408 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004409 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004410 if (nai == null) {
4411 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4412 break;
4413 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004414 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004415 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004416 (PendingIntent) msg.obj,
4417 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004418 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004419 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004420 break;
4421 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004422 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004423 if (nai == null) break;
4424
Erik Kline9a62f012018-03-21 07:18:33 -07004425 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004426 break;
4427 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004428 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004429 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004430 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004431 break;
4432 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004433 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004434 return true;
4435 }
4436
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004437 private void handleNetworkTested(
4438 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004439 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4440 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004441 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004442
4443 // If there is any kind of working networking, then the NAI has been evaluated
4444 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4445 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004446 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004447 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004448 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4449 // any callback that receives onAvailable for that rematch receives an extra caps
4450 // callback. To prevent that, update the score in the agent so the updates below won't
4451 // see an update to both caps and score at the same time.
4452 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004453 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4454
he_won.hwang881307a2022-03-15 21:23:52 +09004455 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4456 // Assume the validation failure is due to a temporary failure after roaming
4457 // and ignore it. NetworkMonitor will continue to retry validation. If it
4458 // continues to fail after the block timeout expires, the network will be
4459 // marked unvalidated. If it succeeds, then validation state will not change.
4460 return;
4461 }
4462
Chalard Jean254bd162022-08-25 13:04:51 +09004463 final boolean wasValidated = nai.isValidated();
4464 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004465 final boolean wasPortal = nai.captivePortalDetected();
4466 nai.setPartialConnectivity(partial);
4467 nai.setCaptivePortalDetected(portal);
4468 nai.updateScoreForNetworkAgentUpdate();
4469 final boolean partialConnectivityChanged = (wasPartial != partial);
4470 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004471
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004472 if (DBG) {
4473 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4474 ? " with redirect to " + redirectUrl
4475 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004476 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004477 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004478 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004479 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004480 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004481 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004482 if (valid) {
4483 handleFreshlyValidatedNetwork(nai);
4484 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4485 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004486 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004487 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004488 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004489 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004490 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004491 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004492 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004493 NotificationType.PRIVATE_DNS_BROKEN);
4494 // If network becomes valid, the hasShownBroken should be reset for
4495 // that network so that the notification will be fired when the private
4496 // DNS is broken again.
4497 nai.networkAgentConfig.hasShownBroken = false;
4498 }
4499 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004500 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004501 } else if (portalChanged) {
4502 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004503 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004504 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4505 nai.onPreventAutomaticReconnect();
4506 teardownUnneededNetwork(nai);
4507 return;
4508 } else {
4509 updateCapabilitiesForNetwork(nai);
4510 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004511 } else if (becameEvaluated) {
4512 // If valid or partial connectivity changed, updateCapabilities* has
4513 // done the rematch.
4514 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004515 }
4516 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004517
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004518 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004519 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004520 nai.onValidationStatusChanged(
4521 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4522 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004523
4524 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004525 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004526 // immediately. Re-notify partial connectivity silently if no internet
4527 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004528 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004529 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004530 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4531 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004532 }
4533
Chalard Jean254bd162022-08-25 13:04:51 +09004534 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004535 handleNetworkUnvalidated(nai);
4536 }
4537 }
4538
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004539 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4540 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4541 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4542 // Do not avoid captive portal when network is wear proxy.
4543 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4544 }
4545
Calvin Ondada1452016-10-11 15:10:46 -07004546 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004547 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4548 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004549 }
4550
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004551 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4552 switch (msg.what) {
4553 default:
4554 return false;
4555 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4556 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4557 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4558 handleLingerComplete(nai);
4559 }
4560 break;
4561 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004562 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4563 handleNetworkAgentRegistered(msg);
4564 break;
4565 }
4566 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4567 handleNetworkAgentDisconnected(msg);
4568 break;
4569 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004570 }
4571 return true;
4572 }
4573
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004574 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004575 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004576 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004577 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004578 maybeHandleNetworkAgentMessage(msg);
4579 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004580 }
4581 }
4582
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004583 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004584 private final int mNetId;
4585 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004586
4587 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004588 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004589 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004590 }
4591
4592 @Override
4593 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4594 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004595 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004596 }
4597
4598 @Override
4599 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004600 // Legacy version of notifyNetworkTestedWithExtras.
4601 // Would only be called if the system has a NetworkStack module older than the
4602 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004603 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004604 }
4605
4606 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004607 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004608 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4609 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004610 final Message msg = mTrackerHandler.obtainMessage(
4611 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004612 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004613 new NetworkTestedResults(
4614 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004615 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004616
4617 // Invoke ConnectivityReport generation for this Network test event.
4618 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4619 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004620
Cody Kestingf1120be2020-08-03 18:01:40 -07004621 // NetworkMonitor reports the network validation result as a bitmask while
4622 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4623 // logical value for ConnectivityDiagnostics.
4624 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4625 p.result);
4626
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004627 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004628 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004629 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4630 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4631
Aaron Huang959d3642021-01-21 15:47:41 +08004632 ConnectivityReportEvent reportEvent =
4633 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4634 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004635 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004636 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004637 }
4638
4639 @Override
4640 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4641 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4642 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004643 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004644 }
4645
4646 @Override
lucasline117e2e2019-10-22 18:27:33 +08004647 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4648 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4649 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004650 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004651 }
4652
4653 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004654 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4655 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4656 EVENT_CAPPORT_DATA_CHANGED,
4657 0, mNetId, data));
4658 }
4659
4660 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004661 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004662 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004663 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004664
4665 final PendingIntent pendingIntent;
4666 // Only the system server can register notifications with package "android"
4667 final long token = Binder.clearCallingIdentity();
4668 try {
paulhu7746e4e2020-06-09 19:07:03 +08004669 pendingIntent = PendingIntent.getBroadcast(
4670 mContext,
4671 0 /* requestCode */,
4672 intent,
4673 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004674 } finally {
4675 Binder.restoreCallingIdentity(token);
4676 }
4677 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4678 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004679 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004680 }
4681
4682 @Override
4683 public void hideProvisioningNotification() {
4684 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004685 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004686 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004687
4688 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004689 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004690 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004691 }
4692
4693 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004694 public int getInterfaceVersion() {
4695 return this.VERSION;
4696 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004697
4698 @Override
4699 public String getInterfaceHash() {
4700 return this.HASH;
4701 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004702 }
4703
Cody Kestingf1120be2020-08-03 18:01:40 -07004704 /**
4705 * Converts the given NetworkMonitor-specific validation result bitmask to a
4706 * ConnectivityDiagnostics-specific validation result int.
4707 */
4708 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4709 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4710 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4711 }
4712 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4713 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4714 }
4715 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4716 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4717 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4718 }
4719
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004720 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004721 log("Data stall detected with methods: " + p.detectionMethod);
4722
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004723 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004724 int detectionMethod = 0;
4725 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4726 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4727 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4728 }
4729 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4730 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4731 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4732 p.tcpMetricsCollectionPeriodMillis);
4733 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004734 }
4735
Cody Kestingf53a0752020-04-15 12:33:28 -07004736 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004737 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004738 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004739
4740 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4741 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4742 // the cost of going through two handlers.
4743 mConnectivityDiagnosticsHandler.sendMessage(msg);
4744 }
4745
Cody Kestingb37958e2020-05-15 10:36:01 -07004746 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4747 return (p.detectionMethod & detectionMethod) != 0;
4748 }
4749
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004750 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4751 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004752 }
4753
Erik Klinea73af002018-06-26 18:53:43 +09004754 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4755 if (nai == null) return;
4756 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4757 // in order to restart a validation pass from within netd.
4758 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4759 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004760 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004761 }
4762 }
4763
Erik Kline31b4a9e2018-01-11 21:07:29 +09004764 private void handlePrivateDnsSettingsChanged() {
4765 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4766
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004767 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004768 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004769 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004770 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4771 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004772 }
4773 }
4774
Erik Kline9a62f012018-03-21 07:18:33 -07004775 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4776 // Private DNS only ever applies to networks that might provide
4777 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004778 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004779
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004780 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004781 // schedule DNS resolutions. If a DNS resolution is required the
4782 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004783 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004784
4785 // With Private DNS bypass support, we can proceed to update the
4786 // Private DNS config immediately, even if we're in strict mode
4787 // and have not yet resolved the provider name into a set of IPs.
4788 updatePrivateDns(nai, cfg);
4789 }
4790
4791 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4792 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004793 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004794 }
4795
dalyk1720e542018-03-05 12:42:22 -05004796 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4797 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4798 if (nai == null) {
4799 return;
4800 }
4801 mDnsManager.updatePrivateDnsValidation(update);
4802 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4803 }
4804
paulhu7c0a2e62021-01-08 00:51:49 +08004805 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004806 int prefixLength) {
4807 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4808 if (nai == null) return;
4809
paulhu7c0a2e62021-01-08 00:51:49 +08004810 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4811 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004812
4813 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004814 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004815 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004816 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004817 prefixLength);
4818 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004819 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004820 return;
4821 }
4822 }
4823
Lorenzo Colittid523d142020-04-01 20:16:30 +09004824 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004825 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4826 }
4827
Hai Shalome58bdc62021-01-11 18:45:34 -08004828 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004829 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004830 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004831 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4832 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4833 }
4834
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004835 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004836 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004837 * @param nai the agent info to update
4838 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004839 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004840 */
junyulai2b6f0c22021-02-03 20:15:30 +08004841 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4842 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4843 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004844 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004845 // one lingered request, set inactive.
4846 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004847 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004848 if (DBG) log("Unsetting inactive " + nai.toShortString());
4849 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004850 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004851 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004852 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004853 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4854 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004855 }
junyulai2b6f0c22021-02-03 20:15:30 +08004856 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004857 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004858 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004859 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004860 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004861 }
4862
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004863 private void handleNetworkAgentRegistered(Message msg) {
4864 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4865 if (!mNetworkAgentInfos.contains(nai)) {
4866 return;
4867 }
4868
4869 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4870 if (VDBG) log("NetworkAgent registered");
4871 } else {
4872 loge("Error connecting NetworkAgent");
4873 mNetworkAgentInfos.remove(nai);
4874 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004875 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004876 synchronized (mNetworkForNetId) {
4877 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004878 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004879 mNetIdManager.releaseNetId(nai.network.getNetId());
4880 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004881 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004882 }
4883 }
4884 }
Paul Jensend5f53392014-11-25 15:26:53 -05004885
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004886 @VisibleForTesting
4887 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09004888 // The feature of creating the networks immediately was slated for U, but race conditions
4889 // detected late required this was flagged off.
4890 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
4891 // in NetworkAgentTest.
4892 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004893 }
4894
4895 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4896 @NonNull NetworkInfo.State state) {
4897 if (nai.isCreated()) return false;
4898 if (state == NetworkInfo.State.CONNECTED) return true;
4899 if (state != NetworkInfo.State.CONNECTING) {
4900 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09004901 if (shouldCreateNetworksImmediately()) {
4902 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4903 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004904 return false;
4905 }
4906 return nai.isVPN() || shouldCreateNetworksImmediately();
4907 }
4908
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004909 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004910 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004911 }
4912
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004913 @VisibleForTesting
4914 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004915 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09004916 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004917
4918 // If the network never roamed, return false. The check below is not sufficient if time
4919 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4920 if (nai.lastRoamTime == 0) return false;
4921
he_won.hwang881307a2022-03-15 21:23:52 +09004922 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4923 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004924 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004925 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004926 final long currentTimeMs = SystemClock.elapsedRealtime();
4927 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004928 if (timeSinceLastRoam <= blockTimeOut) {
4929 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4930 return true;
4931 }
4932 }
4933 return false;
4934 }
4935
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004936 private void handleNetworkAgentDisconnected(Message msg) {
4937 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004938 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004939 }
4940
Chalard Jeand9fffc32018-05-11 20:19:20 +09004941 // Destroys a network, remove references to it from the internal state managed by
4942 // ConnectivityService, free its interfaces and clean up.
4943 // Must be called on the Handler thread.
4944 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004945 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004946
4947 if (!mNetworkAgentInfos.contains(nai)) return;
4948
Chalard Jeand9fffc32018-05-11 20:19:20 +09004949 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004950 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004951 }
lucaslinb25c9a62019-02-12 15:30:13 +08004952 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004953 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004954 // A network agent has disconnected.
4955 // TODO - if we move the logic to the network agent (have them disconnect
4956 // because they lost all their requests or because their score isn't good)
4957 // then they would disconnect organically, report their new state and then
4958 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08004959 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004960 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4961 null, null);
4962 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004963 final boolean wasDefault = isDefaultNetwork(nai);
4964 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004965 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004966 }
4967 notifyIfacesChangedForNetworkStats();
Chalard Jean1e4c2182023-10-06 18:45:53 +09004968 // If this was a local network forwarded to some upstream, or if some local network was
4969 // forwarded to this nai, then disable forwarding rules now.
4970 maybeDisableForwardRulesForDisconnectingNai(nai);
4971 // If this is a local network with an upstream selector, remove the associated network
4972 // request.
4973 if (nai.isLocalNetwork()) {
4974 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
4975 if (null != selector) {
4976 handleRemoveNetworkRequest(mNetworkRequests.get(selector));
4977 }
4978 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004979 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4980 // by other networks that are already connected. Perhaps that can be done by
4981 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4982 // of rematchAllNetworksAndRequests
4983 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004984 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004985
4986 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004987 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4988 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08004989 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004990 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004991 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004992 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004993 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004994 synchronized (mNetworkForNetId) {
4995 // Remove the NetworkAgent, but don't mark the netId as
4996 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004997 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004998 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004999 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08005000 // Update allowed network lists in netd. This should be called after removing nai
5001 // from mNetworkAgentInfos.
5002 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005003 // Remove all previously satisfied requests.
5004 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005005 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09005006 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08005007 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08005008 if (currentNetwork != null
5009 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005010 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09005011 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
5012 // rematch not to keep disconnected agents instead of setting it here ; this
5013 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08005014 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09005015 for (final NetworkOfferInfo noi : mNetworkOffers) {
5016 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08005017 }
James Mattise3ef1912020-12-20 11:09:58 -08005018
Chalard Jean5b409c72021-02-04 13:12:59 +09005019 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08005020 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09005021 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08005022 // network, because while incorrect this is the closest to the old (also
5023 // incorrect) behavior.
5024 mNetworkActivityTracker.updateDataActivityTracking(
5025 null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09005026 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08005027 ensureNetworkTransitionWakelock(nai.toShortString());
5028 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005029 }
5030 }
junyulai2b6f0c22021-02-03 20:15:30 +08005031 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08005032 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09005033 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08005034 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09005035 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005036 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005037 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005038
Aaron Huang9fe47be2021-06-08 13:11:45 +08005039 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
5040 // The obvious place to do this would be in makeDefault(), however makeDefault() is
5041 // not called by the rematch in this case. This is because the code above unset
5042 // this network from the default request's satisfier, and that is what the rematch
5043 // is using as its source data to know what the old satisfier was. So as far as the
5044 // rematch above is concerned, the old default network was null.
5045 // Therefore if there is no new default, the default network was null and is still
5046 // null, thus there was no change so makeDefault() is not called. So if the old
5047 // network had a proxy and there is no new default, the proxy tracker should be told
5048 // that there is no longer a default proxy.
5049 // Strictly speaking this is not essential because having a proxy setting when
5050 // there is no network is harmless, but it's still counter-intuitive so reset to null.
5051 mProxyTracker.setDefaultProxy(null);
5052 }
5053
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005054 // Immediate teardown.
5055 if (nai.teardownDelayMs == 0) {
5056 destroyNetwork(nai);
5057 return;
5058 }
5059
5060 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09005061 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05305062 try {
5063 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
5064 } catch (RemoteException e) {
5065 Log.d(TAG, "Error marking network restricted during teardown: ", e);
5066 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005067 }
5068 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
5069 }
5070
5071 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005072 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005073 // Tell netd to clean up the configuration for this network
5074 // (routing rules, DNS, etc).
5075 // This may be slow as it requires a lot of netd shelling out to ip and
5076 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09005077 // after we've rematched networks with requests (which might change the default
5078 // network or service a new request from an app), so network traffic isn't interrupted
5079 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08005080 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005081 }
Chalard Jeandf29a852023-05-29 17:02:43 +09005082 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005083 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
5084 // This can never run if the code above runs because shouldDestroyNativeNetwork is
5085 // false if the network was never created.
5086 // TODO: delete when S is no longer supported.
5087 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005088 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08005089 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005090 }
5091
Chalard Jean1e4c2182023-10-06 18:45:53 +09005092 private void maybeDisableForwardRulesForDisconnectingNai(
5093 @NonNull final NetworkAgentInfo disconnecting) {
5094 // Step 1 : maybe this network was the upstream for one or more local networks.
5095 for (final NetworkAgentInfo local : mNetworkAgentInfos) {
5096 if (!local.isLocalNetwork()) continue;
5097 final NetworkRequest selector = local.localNetworkConfig.getUpstreamSelector();
5098 if (null == selector) continue;
5099 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5100 // null == nri can happen while disconnecting a network, because destroyNetwork() is
5101 // called after removing all associated NRIs from mNetworkRequests.
5102 if (null == nri) continue;
5103 final NetworkAgentInfo satisfier = nri.getSatisfier();
5104 if (disconnecting != satisfier) continue;
5105 removeLocalNetworkUpstream(local, disconnecting);
5106 }
5107
5108 // Step 2 : maybe this is a local network that had an upstream.
5109 if (!disconnecting.isLocalNetwork()) return;
5110 final NetworkRequest selector = disconnecting.localNetworkConfig.getUpstreamSelector();
5111 if (null == selector) return;
5112 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5113 // As above null == nri can happen while disconnecting a network, because destroyNetwork()
5114 // is called after removing all associated NRIs from mNetworkRequests.
5115 if (null == nri) return;
5116 final NetworkAgentInfo satisfier = nri.getSatisfier();
5117 if (null == satisfier) return;
5118 removeLocalNetworkUpstream(disconnecting, satisfier);
5119 }
5120
5121 private void removeLocalNetworkUpstream(@NonNull final NetworkAgentInfo localAgent,
5122 @NonNull final NetworkAgentInfo upstream) {
5123 try {
5124 mRoutingCoordinatorService.removeInterfaceForward(
5125 localAgent.linkProperties.getInterfaceName(),
5126 upstream.linkProperties.getInterfaceName());
5127 } catch (RemoteException e) {
5128 loge("Couldn't remove interface forward for "
5129 + localAgent.linkProperties.getInterfaceName() + " to "
5130 + upstream.linkProperties.getInterfaceName() + " while disconnecting");
5131 }
5132 }
5133
Ken Chen6df7a902021-04-09 15:08:42 +08005134 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08005135 try {
5136 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005137 final NativeNetworkConfig config;
5138 if (nai.isVPN()) {
5139 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005140 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005141 return false;
5142 }
5143 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5144 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005145 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005146 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005147 } else {
Chalard Jeane0aaca52023-10-17 13:23:07 +09005148 config = new NativeNetworkConfig(nai.network.getNetId(),
Chalard Jean1e4c2182023-10-06 18:45:53 +09005149 nai.isLocalNetwork() ? NativeNetworkType.PHYSICAL_LOCAL
5150 : NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005151 getNetworkPermission(nai.networkCapabilities),
5152 false /* secure */,
5153 VpnManager.TYPE_VPN_NONE,
5154 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005155 }
Ken Chen6df7a902021-04-09 15:08:42 +08005156 mNetd.networkCreate(config);
5157 mDnsResolver.createNetworkCache(nai.network.getNetId());
Ken Chen6b134f12023-10-07 07:46:47 +08005158 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(),
5159 nai.networkCapabilities);
Luke Huangfdd11f82019-04-09 18:41:49 +08005160 return true;
5161 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005162 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005163 return false;
5164 }
5165 }
5166
Ken Chen6df7a902021-04-09 15:08:42 +08005167 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005168 if (mDscpPolicyTracker != null) {
5169 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5170 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005171 // Remove any forwarding rules to and from the interface for this network, since
5172 // the interface is going to go away.
5173 maybeDisableForwardRulesForDisconnectingNai(nai);
Luke Huangfdd11f82019-04-09 18:41:49 +08005174 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005175 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005176 } catch (RemoteException | ServiceSpecificException e) {
5177 loge("Exception destroying network(networkDestroy): " + e);
5178 }
5179 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005180 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005181 } catch (RemoteException | ServiceSpecificException e) {
5182 loge("Exception destroying network: " + e);
5183 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005184 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5185 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5186 // gets created, could add data to DnsManager data structures that will never get deleted.
5187 mDnsManager.removeNetwork(nai.network);
5188
5189 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005190 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005191 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5192 }
5193
Chalard Jean254bd162022-08-25 13:04:51 +09005194 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005195 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005196 }
5197
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005198 // If this method proves to be too slow then we can maintain a separate
5199 // pendingIntent => NetworkRequestInfo map.
5200 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5201 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005202 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5203 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5204 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005205 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005206 return entry.getValue();
5207 }
5208 }
5209 return null;
5210 }
5211
Chalard Jean524f0b12021-10-25 21:11:56 +09005212 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005213 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005214 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5215 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5216 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5217 // bug is fixed.
5218 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005219 throw new IllegalStateException("This NRI is already registered. New : " + nri
5220 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005221 }
5222 }
5223 }
5224 }
5225
Chalard Jeanac9ace02022-01-26 16:54:05 +09005226 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5227 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005228 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09005229 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
5230 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005231 }
5232 return false;
5233 }
5234
James Mattisf7027322020-12-13 16:28:14 -08005235 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005236 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005237 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5238 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5239 final NetworkRequestInfo existingRequest =
5240 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005241 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005242 if (DBG) {
5243 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5244 + nri.mRequests.get(0) + " because their intents matched.");
5245 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005246 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005247 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005248 }
Erik Kline05f2b402015-04-30 12:58:40 +09005249 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005250 }
5251
James Mattisf7027322020-12-13 16:28:14 -08005252 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005253 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005254 }
5255
James Mattis3ce3d3c2021-02-09 18:18:28 -08005256 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005257 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005258 for (final NetworkRequestInfo nri : nris) {
5259 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005260 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005261 for (final NetworkRequest req : nri.mRequests) {
5262 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005263 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005264 if (req.isListen()) {
5265 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5266 if (req.networkCapabilities.hasSignalStrength()
5267 && network.satisfiesImmutableCapabilitiesOf(req)) {
5268 updateSignalStrengthThresholds(network, "REGISTER", req);
5269 }
James Mattisf7027322020-12-13 16:28:14 -08005270 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005271 }
5272 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005273
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005274 // If this NRI has a satisfier already, it is replacing an older request that
5275 // has been removed. Track it.
5276 final NetworkRequest activeRequest = nri.getActiveRequest();
5277 if (null != activeRequest) {
5278 // If there is an active request, then for sure there is a satisfier.
5279 nri.getSatisfier().addRequest(activeRequest);
5280 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005281 }
James Mattisf7027322020-12-13 16:28:14 -08005282
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005283 if (mFlags.noRematchAllRequestsOnRegister()) {
5284 rematchNetworksAndRequests(nris);
5285 } else {
5286 rematchAllNetworksAndRequests();
5287 }
James Mattis45d81842021-01-10 14:24:24 -08005288
Chalard Jean0354d8c2021-01-12 10:58:56 +09005289 // Requests that have not been matched to a network will not have been sent to the
5290 // providers, because the old satisfier and the new satisfier are the same (null in this
5291 // case). Send these requests to the providers.
5292 for (final NetworkRequestInfo nri : nris) {
5293 for (final NetworkOfferInfo noi : mNetworkOffers) {
5294 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005295 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005296 }
5297 }
5298
James Mattisf7027322020-12-13 16:28:14 -08005299 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5300 final int callingUid) {
5301 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005302 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005303 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5304 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5305 handleReleaseNetworkRequest(
5306 nri.mRequests.get(0),
5307 callingUid,
5308 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005309 }
5310 }
5311
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005312 // Determines whether the network is the best (or could become the best, if it validated), for
5313 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5314 // on the value of reason:
5315 //
5316 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5317 // then it should be torn down.
5318 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5319 // then it should be lingered.
5320 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005321 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005322
Chalard Jean254bd162022-08-25 13:04:51 +09005323 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005324 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5325 return false;
5326 }
5327
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005328 final int numRequests;
5329 switch (reason) {
5330 case TEARDOWN:
5331 numRequests = nai.numRequestNetworkRequests();
5332 break;
5333 case LINGER:
5334 numRequests = nai.numForegroundNetworkRequests();
5335 break;
5336 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005337 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005338 return true;
5339 }
5340
Chalard Jean947acd42021-03-08 22:29:27 +09005341 if (numRequests > 0) return false;
5342
Paul Jensende49eb12015-06-25 15:30:08 -04005343 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005344 if (reason == UnneededFor.LINGER
5345 && !nri.isMultilayerRequest()
5346 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005347 // Background requests don't affect lingering.
5348 continue;
5349 }
5350
James Mattis3d229892020-11-16 16:46:28 -08005351 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005352 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005353 }
5354 }
Paul Jensende49eb12015-06-25 15:30:08 -04005355 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005356 }
5357
James Mattis3d229892020-11-16 16:46:28 -08005358 private boolean isNetworkPotentialSatisfier(
5359 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
Chalard Jean80685f42023-10-30 18:31:27 +09005360 // While destroyed network sometimes satisfy requests (including occasionally newly
5361 // satisfying requests), *potential* satisfiers are networks that might beat a current
5362 // champion if they validate. As such, a destroyed network is never a potential satisfier,
5363 // because it's never a good idea to keep a destroyed network in case it validates.
5364 // For example, declaring it a potential satisfier would keep an unvalidated destroyed
5365 // candidate after it's been replaced by another unvalidated network.
5366 if (candidate.isDestroyed()) return false;
5367 // Listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005368 // request, return immediately. For multilayer requests, check to see if any of the
5369 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005370 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5371 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005372 return false;
5373 }
5374 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005375 // This multilayer listen request is satisfied therefore no further requests need to be
5376 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005377 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005378 return false;
5379 }
James Mattis3d229892020-11-16 16:46:28 -08005380 // As non-multilayer listen requests have already returned, the below would only happen
5381 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005382 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005383 continue;
5384 }
Chalard Jean80685f42023-10-30 18:31:27 +09005385 // If there is hope for this network might validate and subsequently become the best
5386 // network for that request, then it is needed. Note that this network can't already
5387 // be the best for this request, or it would be the current satisfier, and therefore
5388 // there would be no need to call this method to find out if it is a *potential*
5389 // satisfier ("unneeded", the only caller, only calls this if this network currently
5390 // satisfies no request).
James Mattis3d229892020-11-16 16:46:28 -08005391 if (candidate.satisfies(req)) {
5392 // As soon as a network is found that satisfies a request, return. Specifically for
5393 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5394 // is important so as to not evaluate lower priority requests further in
5395 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005396 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5397 ? nri.getSatisfier() : null;
5398 // Note that this catches two important cases:
5399 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5400 // is currently satisfying the request. This is desirable when
5401 // cellular ends up validating but WiFi does not.
5402 // 2. Unvalidated WiFi will not be reaped when validated cellular
5403 // is currently satisfying the request. This is desirable when
5404 // WiFi ends up validating and out scoring cellular.
5405 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005406 }
5407 }
5408
5409 return false;
5410 }
5411
Erik Kline0c04b742016-07-07 16:50:58 +09005412 private NetworkRequestInfo getNriForAppRequest(
5413 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005414 // Looking up the app passed param request in mRequests isn't possible since it may return
5415 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5416 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005417 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5418 // to avoid potential race conditions when validating a package->uid mapping when sending
5419 // the callback on the very low-chance that an application shuts down prior to the callback
5420 // being sent.
5421 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5422 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005423
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005424 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005425 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005426 log(String.format("UID %d attempted to %s for unowned request %s",
5427 callingUid, requestedOperation, nri));
5428 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005429 }
Erik Kline0c04b742016-07-07 16:50:58 +09005430 }
5431
5432 return nri;
5433 }
5434
James Mattisf7027322020-12-13 16:28:14 -08005435 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5436 final String callingMethod) {
5437 if (nri.isMultilayerRequest()) {
5438 throw new IllegalStateException(
5439 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005440 }
5441 }
5442
James Mattisf7027322020-12-13 16:28:14 -08005443 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005444 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005445 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5446 // single NetworkRequest and thus does not apply to multilayer requests.
5447 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5448 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005449 return;
5450 }
James Mattis2516da32021-01-31 17:06:19 -08005451 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005452 return;
5453 }
James Mattisf7027322020-12-13 16:28:14 -08005454 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5455 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005456 }
5457 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005458 callCallbackForRequest(
5459 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005460 }
5461
James Mattisf7027322020-12-13 16:28:14 -08005462 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5463 final int callingUid,
5464 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005465 final NetworkRequestInfo nri =
5466 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5467 if (nri == null) {
5468 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005469 }
James Mattisf7027322020-12-13 16:28:14 -08005470 if (VDBG || (DBG && request.isRequest())) {
5471 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005472 }
5473 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005474 if (callOnUnavailable) {
5475 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5476 }
Erik Kline155a59a2015-11-25 12:49:38 +09005477 }
Erik Kline0c04b742016-07-07 16:50:58 +09005478
James Mattisa076c532020-12-02 14:12:41 -08005479 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005480 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005481 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005482 if (null == mNetworkRequests.remove(req)) {
5483 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5484 continue;
5485 }
James Mattisa076c532020-12-02 14:12:41 -08005486 if (req.isListen()) {
5487 removeListenRequestFromNetworks(req);
5488 }
5489 }
James Mattis8f036802021-06-20 16:26:01 -07005490 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005491 if (mDefaultNetworkRequests.remove(nri)) {
5492 // If this request was one of the defaults, then the UID rules need to be updated
5493 // WARNING : if the app(s) for which this network request is the default are doing
5494 // traffic, this will kill their connected sockets, even if an equivalent request
5495 // is going to be reinstated right away ; unconnected traffic will go on the default
5496 // until the new default is set, which will happen very soon.
5497 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5498 // remove ranges for those requests that won't have a replacement
5499 final NetworkAgentInfo satisfier = nri.getSatisfier();
5500 if (null != satisfier) {
5501 try {
paulhu0e79d952021-06-09 16:11:35 +08005502 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5503 satisfier.network.getNetId(),
5504 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005505 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005506 } catch (RemoteException e) {
5507 loge("Exception setting network preference default network", e);
5508 }
5509 }
5510 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005511
Junyu Lai00d92df2022-07-05 11:01:52 +08005512 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005513 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005514 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005515
5516 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005517 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005518 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005519 }
5520 }
5521
Chalard Jean0354d8c2021-01-12 10:58:56 +09005522 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5523 // needed for this offer.
5524 for (final NetworkOfferInfo noi : mNetworkOffers) {
5525 for (final NetworkRequest req : nri.mRequests) {
5526 if (req.isRequest() && noi.offer.neededFor(req)) {
5527 noi.offer.onNetworkUnneeded(req);
5528 }
5529 }
5530 }
James Mattisa076c532020-12-02 14:12:41 -08005531 }
5532
James Mattis3ce3d3c2021-02-09 18:18:28 -08005533 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5534 for (final NetworkRequestInfo nri : nris) {
5535 if (mDefaultRequest == nri) {
5536 // Make sure we never remove the default request.
5537 continue;
5538 }
5539 handleRemoveNetworkRequest(nri);
5540 }
5541 }
5542
James Mattisa076c532020-12-02 14:12:41 -08005543 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5544 // listens don't have a singular affected Network. Check all networks to see
5545 // if this listen request applies and remove it.
5546 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5547 nai.removeRequest(req.requestId);
5548 if (req.networkCapabilities.hasSignalStrength()
5549 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5550 updateSignalStrengthThresholds(nai, "RELEASE", req);
5551 }
5552 }
5553 }
5554
5555 /**
5556 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5557 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5558 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5559 */
5560 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5561 boolean wasKept = false;
5562 final NetworkAgentInfo nai = nri.getSatisfier();
5563 if (nai != null) {
5564 final int requestLegacyType = nri.getActiveRequest().legacyType;
5565 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5566 nai.removeRequest(nri.getActiveRequest().requestId);
5567 if (VDBG || DDBG) {
5568 log(" Removing from current network " + nai.toShortString()
5569 + ", leaving " + nai.numNetworkRequests() + " requests.");
5570 }
5571 // If there are still lingered requests on this network, don't tear it down,
5572 // but resume lingering instead.
5573 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005574 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005575 notifyNetworkLosing(nai, now);
5576 }
5577 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5578 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5579 teardownUnneededNetwork(nai);
5580 } else {
5581 wasKept = true;
5582 }
James Mattisa076c532020-12-02 14:12:41 -08005583 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5584 // Went from foreground to background.
5585 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005586 }
5587
Erik Kline0c04b742016-07-07 16:50:58 +09005588 // Maintain the illusion. When this request arrived, we might have pretended
5589 // that a network connected to serve it, even though the network was already
5590 // connected. Now that this request has gone away, we might have to pretend
5591 // that the network disconnected. LegacyTypeTracker will generate that
5592 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005593 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005594 boolean doRemove = true;
5595 if (wasKept) {
5596 // check if any of the remaining requests for this network are for the
5597 // same legacy type - if so, don't remove the nai
5598 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5599 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005600 if (otherRequest.legacyType == requestLegacyType
5601 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005602 if (DBG) log(" still have other legacy request - leaving");
5603 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005604 }
5605 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005606 }
5607
Erik Kline0c04b742016-07-07 16:50:58 +09005608 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005609 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005610 }
5611 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005612 }
5613 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005614
Junyu Lai00d92df2022-07-05 11:01:52 +08005615 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005616 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005617 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5618 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5619 }
5620
Lorenzo Colittid6459092016-07-04 12:55:44 +09005621 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005622 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005623 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005624 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005625 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005626 }
5627
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005628 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005629 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5630 enforceNetworkStackSettingsOrSetup();
5631 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5632 encodeBool(accept), encodeBool(always), network));
5633 }
5634
5635 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005636 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005637 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005638 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5639 }
5640
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005641 @Override
5642 public void setTestAllowBadWifiUntil(long timeMs) {
5643 enforceSettingsPermission();
5644 if (!Build.isDebuggable()) {
5645 throw new IllegalStateException("Does not support in non-debuggable build");
5646 }
5647
5648 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5649 throw new IllegalArgumentException("It should not exceed "
5650 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5651 }
5652
5653 mHandler.sendMessage(
5654 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5655 }
5656
chiachangwange0192a72023-02-06 13:25:01 +00005657 @Override
5658 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5659 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005660
5661 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5662 throw new IllegalArgumentException("Argument should not exceed "
5663 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5664 }
5665
5666 mHandler.sendMessage(
5667 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5668 }
5669
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005670 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5671 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5672 " accept=" + accept + " always=" + always);
5673
5674 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5675 if (nai == null) {
5676 // Nothing to do.
5677 return;
5678 }
5679
Chalard Jean254bd162022-08-25 13:04:51 +09005680 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005681 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005682 return;
5683 }
5684
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005685 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005686 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005687 }
5688
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005689 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5690 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005691 // If network becomes partial connectivity and user already accepted to use this
5692 // network, we should respect the user's option and don't need to popup the
5693 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005694 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005695 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005696 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005697 }
5698
5699 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005700 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005701 }
5702
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005703 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005704 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005705 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005706 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005707 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005708 }
5709
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005710 }
5711
lucaslin2240ef62019-03-12 13:08:03 +08005712 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5713 boolean always) {
5714 if (DBG) {
5715 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5716 + " always=" + always);
5717 }
5718
5719 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5720 if (nai == null) {
5721 // Nothing to do.
5722 return;
5723 }
5724
Chalard Jean254bd162022-08-25 13:04:51 +09005725 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005726 // The network validated while the dialog box was up. Take no action.
5727 return;
5728 }
5729
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005730 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5731 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005732 }
5733
5734 // TODO: Use the current design or save the user choice into IpMemoryStore.
5735 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005736 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005737 }
5738
5739 if (!accept) {
5740 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005741 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005742 // Tear down the network.
5743 teardownUnneededNetwork(nai);
5744 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005745 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5746 // result in a partial connectivity result which will be processed by
5747 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005748 //
5749 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5750 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005751 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005752 }
5753 }
5754
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005755 private void handleSetAvoidUnvalidated(Network network) {
5756 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005757 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005758 // Nothing to do. The network either disconnected or revalidated.
5759 return;
5760 }
Chalard Jean254bd162022-08-25 13:04:51 +09005761 if (0L == nai.getAvoidUnvalidated()) {
5762 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005763 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005764 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005765 }
5766 }
5767
Chalard Jean5fb43c72022-09-08 19:03:14 +09005768 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005769 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005770 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005771 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005772 }
5773
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005774 @Override
5775 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005776 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005777 mHandler.post(() -> {
5778 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5779 if (nai == null) return;
5780 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005781 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005782 });
5783 }
5784
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005785 /**
5786 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5787 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005788 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005789 * @param appExtras Bundle to use as intent extras for the captive portal application.
5790 * Must be treated as opaque to avoid preventing the captive portal app to
5791 * update its arguments.
5792 */
5793 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005794 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005795 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5796 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005797
5798 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5799 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005800 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5801 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005802 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5803
lucaslin75ff7022020-12-17 04:14:35 +08005804 final long token = Binder.clearCallingIdentity();
5805 try {
5806 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5807 } finally {
5808 Binder.restoreCallingIdentity(token);
5809 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005810 }
5811
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005812 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5813 private final Network mNetwork;
5814
5815 private CaptivePortalImpl(Network network) {
5816 mNetwork = network;
5817 }
5818
5819 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005820 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005821 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5822 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005823 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5824 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5825 // Since the network will be disconnected, skip notifying NetworkMonitor
5826 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005827 }
5828
Chiachang Wang938bfba2020-01-09 13:50:55 +08005829 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005830 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005831 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005832 }
5833
5834 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005835 public void appRequest(final int request) {
5836 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5837 if (nm == null) return;
5838
5839 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005840 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005841 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005842 }
5843 }
5844
5845 @Nullable
5846 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5847 // getNetworkAgentInfoForNetwork is thread-safe
5848 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5849 if (nai == null) return null;
5850
5851 // nai.networkMonitor() is thread-safe
5852 return nai.networkMonitor();
5853 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005854 }
5855
Hugo Benichic9048bc2016-09-14 23:23:08 +00005856 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005857 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005858 }
5859
Chalard Jean020b93a2022-09-01 13:20:14 +09005860 private boolean activelyPreferBadWifi() {
5861 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5862 }
5863
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005864 /**
5865 * Return whether the device should maintain continuous, working connectivity by switching away
5866 * from WiFi networks having no connectivity.
5867 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5868 */
5869 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005870 if (!checkNetworkStackPermission()) {
5871 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5872 }
5873 return avoidBadWifi();
5874 }
5875
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005876 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005877 ensureRunningOnConnectivityServiceThread();
5878 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005879 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005880 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005881 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005882 if (avoidBadWifi) {
5883 // If the device is now avoiding bad wifi, remove notifications that might have
5884 // been put up when the device didn't.
5885 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5886 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005887 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005888 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5889 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5890 for (final NetworkOfferInfo noi : offersToUpdate) {
5891 updateOfferScore(noi.offer);
5892 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005893 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005894 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005895 }
5896
Erik Kline95ecfee2016-10-02 18:02:14 +09005897 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005898 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005899 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005900 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005901 if (!configRestrict) {
5902 pw.println("Bad Wi-Fi avoidance: unrestricted");
5903 return;
5904 }
5905
5906 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5907 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005908 pw.println("Config restrict: " + configRestrict);
5909 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005910
Chalard Jeane0fdea32022-09-14 21:44:22 +09005911 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005912 String description;
5913 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005914 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005915 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005916 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005917 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005918 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005919 description = "avoid";
5920 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005921 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005922 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005923 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005924
5925 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5926 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005927 if (null == configValue) {
5928 description = "unset";
5929 } else if (configValue) {
5930 description = "force true";
5931 } else {
5932 description = "force false";
5933 }
5934 pw.println("Actively prefer bad wifi conf: " + description);
5935 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005936 pw.println("Network overrides:");
5937 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005938 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005939 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005940 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005941 }
5942 }
5943 pw.decreaseIndent();
5944 pw.decreaseIndent();
5945 }
5946
paulhu7746e4e2020-06-09 19:07:03 +08005947 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5948 // unify the method.
5949 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5950 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5951 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5952 return settingsComponent != null
5953 ? settingsComponent.getPackageName() : "com.android.settings";
5954 }
5955
lucaslinb1e8e382019-01-24 15:55:30 +08005956 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005957 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005958 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005959 switch (type) {
5960 case NO_INTERNET:
5961 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005962 // High priority because it is only displayed for explicitly selected networks.
5963 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005964 break;
lucasline117e2e2019-10-22 18:27:33 +08005965 case PRIVATE_DNS_BROKEN:
5966 action = Settings.ACTION_WIRELESS_SETTINGS;
5967 // High priority because we should let user know why there is no internet.
5968 highPriority = true;
5969 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005970 case LOST_INTERNET:
5971 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005972 // High priority because it could help the user avoid unexpected data usage.
5973 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005974 break;
lucaslin2240ef62019-03-12 13:08:03 +08005975 case PARTIAL_CONNECTIVITY:
5976 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005977 // Don't bother the user with a high-priority notification if the network was not
5978 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005979 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005980 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005981 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005982 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005983 return;
5984 }
5985
5986 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005987 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005988 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005989 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005990 // Some OEMs have their own Settings package. Thus, need to get the current using
5991 // Settings package name instead of just use default name "com.android.settings".
5992 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5993 intent.setClassName(settingsPkgName,
5994 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005995 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005996
paulhu2af50222020-10-11 22:52:27 +08005997 PendingIntent pendingIntent = PendingIntent.getActivity(
5998 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005999 0 /* requestCode */,
6000 intent,
paulhu2af50222020-10-11 22:52:27 +08006001 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006002
Serik Beketayevec8ad212020-12-07 22:43:07 -08006003 mNotifier.showNotification(
6004 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006005 }
6006
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006007 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
6008 // Don't prompt if the network is validated, and don't prompt on captive portals
6009 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09006010 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006011 return false;
6012 }
6013
6014 // If a network has partial connectivity, always prompt unless the user has already accepted
6015 // partial connectivity and selected don't ask again. This ensures that if the device
6016 // automatically connects to a network that has partial Internet access, the user will
6017 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09006018 // because we have prompted them.
6019 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006020 return true;
6021 }
6022
6023 // If a network has no Internet access, only prompt if the network was explicitly selected
6024 // and if the user has not already told us to use the network regardless of whether it
6025 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006026 if (nai.networkAgentConfig.explicitlySelected
6027 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006028 return true;
6029 }
6030
6031 return false;
6032 }
6033
Chalard Jean5fb43c72022-09-08 19:03:14 +09006034 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
6035 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006036
Chalard Jean5fb43c72022-09-08 19:03:14 +09006037 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6038 if (null == nai) return;
6039
6040 if (nai.setEvaluated()) {
6041 // If setEvaluated() returned true, the network never had any form of connectivity.
6042 // This may have an impact on request matching if bad WiFi avoidance is off and the
6043 // network was found not to have Internet access.
6044 nai.updateScoreForNetworkAgentUpdate();
6045 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09006046
6047 // Also, if this is WiFi and it should be preferred actively, now is the time to
6048 // prompt the user that they walked past and connected to a bad WiFi.
6049 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
6050 && !avoidBadWifi()
6051 && activelyPreferBadWifi()) {
6052 // The notification will be removed if the network validates or disconnects.
6053 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
6054 return;
6055 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006056 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006057
Chalard Jean5fb43c72022-09-08 19:03:14 +09006058 if (!shouldPromptUnvalidated(nai)) return;
6059
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006060 // Stop automatically reconnecting to this network in the future. Automatically connecting
6061 // to a network that provides no or limited connectivity is not useful, because the user
6062 // cannot use that network except through the notification shown by this method, and the
6063 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006064 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006065
Chalard Jean254bd162022-08-25 13:04:51 +09006066 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08006067 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08006068 } else {
6069 showNetworkNotification(nai, NotificationType.NO_INTERNET);
6070 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006071 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006072
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006073 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
6074 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09006075 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07006076
lucaslin2240ef62019-03-12 13:08:03 +08006077 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6078 return;
6079 }
6080
6081 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08006082 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006083 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006084 }
6085
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006086 @Override
6087 public int getMultipathPreference(Network network) {
6088 enforceAccessPermission();
6089
6090 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06006091 if (nai != null && nai.networkCapabilities
6092 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006093 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
6094 }
6095
Aaron Huang9a57acf2020-12-08 10:03:29 +08006096 final NetworkPolicyManager netPolicyManager =
6097 mContext.getSystemService(NetworkPolicyManager.class);
6098
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09006099 final long token = Binder.clearCallingIdentity();
6100 final int networkPreference;
6101 try {
6102 networkPreference = netPolicyManager.getMultipathPreference(network);
6103 } finally {
6104 Binder.restoreCallingIdentity(token);
6105 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08006106 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09006107 return networkPreference;
6108 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006109 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
6110 }
6111
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006112 @Override
6113 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09006114 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006115 }
6116
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006117 private class InternalHandler extends Handler {
6118 public InternalHandler(Looper looper) {
6119 super(looper);
6120 }
6121
6122 @Override
6123 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006124 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07006125 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006126 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006127 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07006128 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006129 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006130 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09006131 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07006132 break;
6133 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08006134 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08006135 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08006136 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04006137 break;
6138 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006139 case EVENT_REGISTER_NETWORK_PROVIDER: {
6140 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006141 break;
6142 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006143 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
6144 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006145 break;
6146 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006147 case EVENT_REGISTER_NETWORK_OFFER: {
6148 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
6149 break;
6150 }
6151 case EVENT_UNREGISTER_NETWORK_OFFER: {
6152 final NetworkOfferInfo offer =
6153 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6154 if (null != offer) {
6155 handleUnregisterNetworkOffer(offer);
6156 }
6157 break;
6158 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006159 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006160 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6161 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6162 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006163 break;
6164 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006165 case EVENT_REGISTER_NETWORK_REQUEST:
6166 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006167 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006168 break;
6169 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006170 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6171 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006172 handleRegisterNetworkRequestWithIntent(msg);
6173 break;
6174 }
Erik Kline155a59a2015-11-25 12:49:38 +09006175 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6176 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6177 handleTimedOutNetworkRequest(nri);
6178 break;
6179 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006180 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6181 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6182 break;
6183 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006184 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006185 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6186 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006187 break;
6188 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006189 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006190 Network network = (Network) msg.obj;
6191 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006192 break;
6193 }
lucaslin2240ef62019-03-12 13:08:03 +08006194 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6195 Network network = (Network) msg.obj;
6196 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6197 toBool(msg.arg2));
6198 break;
6199 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006200 case EVENT_SET_AVOID_UNVALIDATED: {
6201 handleSetAvoidUnvalidated((Network) msg.obj);
6202 break;
6203 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006204 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6205 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006206 break;
6207 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006208 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6209 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006210 break;
6211 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006212 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6213 // handler thread.
6214 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006215 mKeepaliveTracker.handleStartKeepalive(msg);
6216 break;
6217 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006218 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006219 final AutomaticOnOffKeepalive ki =
6220 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6221 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006222
chiachangwang676c84e2023-02-14 09:22:05 +00006223 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006224 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006225 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006226 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006227 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6228 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006229 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6230 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006231 }
6232 }
6233
6234 // If the network no longer exists, then the keepalive should have been
6235 // cleaned up already. There is no point trying to resume keepalives.
6236 if (!networkFound) return;
6237
chiachangwang676c84e2023-02-14 09:22:05 +00006238 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006239 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang676c84e2023-02-14 09:22:05 +00006240 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006241 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006242 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006243 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006244 }
6245 break;
6246 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006247 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006248 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006249 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6250 (IBinder) msg.obj);
6251 if (ki == null) {
6252 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006253 return;
6254 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006255 final int reason = msg.arg2;
6256 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006257 break;
6258 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006259 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6260 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6261 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006262 break;
6263 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006264 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6265 handlePrivateDnsSettingsChanged();
6266 break;
dalyk1720e542018-03-05 12:42:22 -05006267 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6268 handlePrivateDnsValidationUpdate(
6269 (PrivateDnsValidationUpdate) msg.obj);
6270 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006271 case EVENT_UID_BLOCKED_REASON_CHANGED:
6272 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006273 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006274 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6275 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6276 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006277 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006278 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6279 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006280 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006281 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006282 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006283 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006284 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6285 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006286 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006287 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006288 }
lucaslin1193a5d2021-01-21 02:04:15 +08006289 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006290 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006291 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006292 break;
paulhu51f77dc2021-06-07 02:34:20 +00006293 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6294 handleMobileDataPreferredUidsChanged();
6295 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006296 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6297 final long timeMs = ((Long) msg.obj).longValue();
6298 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6299 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006300 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6301 handleIngressRateLimitChanged();
6302 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006303 case EVENT_USER_DOES_NOT_WANT:
6304 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6305 if (nai == null) break;
6306 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006307 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006308 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006309 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6310 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6311 break;
chiachangwange0192a72023-02-06 13:25:01 +00006312 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6313 final long time = ((Long) msg.obj).longValue();
6314 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6315 break;
6316 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006317 case EVENT_UID_FROZEN_STATE_CHANGED:
6318 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6319 handleFrozenUids(args.mUids, args.mFrozenStates);
6320 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006321 }
6322 }
6323 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006324
Lorenzo Colittid6459092016-07-04 12:55:44 +09006325 @Override
markchien5776f962019-12-16 20:15:20 +08006326 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006327 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006328 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006329 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6330 Context.TETHERING_SERVICE);
6331 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006332 }
6333
Lorenzo Colittid6459092016-07-04 12:55:44 +09006334 @Override
markchien5776f962019-12-16 20:15:20 +08006335 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006336 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006337 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006338 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6339 Context.TETHERING_SERVICE);
6340 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006341 }
6342
Lorenzo Colittid6459092016-07-04 12:55:44 +09006343 @Override
markchien5776f962019-12-16 20:15:20 +08006344 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006345 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006346 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006347 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6348 Context.TETHERING_SERVICE);
6349 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006350 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006351
markchien5776f962019-12-16 20:15:20 +08006352
Lorenzo Colittid6459092016-07-04 12:55:44 +09006353 @Override
markchien5776f962019-12-16 20:15:20 +08006354 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006355 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006356 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006357 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6358 Context.TETHERING_SERVICE);
6359
6360 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006361 }
6362
Lorenzo Colittid6459092016-07-04 12:55:44 +09006363 @Override
markchien5776f962019-12-16 20:15:20 +08006364 @Deprecated
6365 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006366 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006367 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6368 Context.TETHERING_SERVICE);
6369
6370 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006371 }
6372
Udam Saini8f7d6a72017-06-07 12:06:28 -07006373 @Override
markchien5776f962019-12-16 20:15:20 +08006374 @Deprecated
6375 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006376 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006377 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6378 Context.TETHERING_SERVICE);
6379 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006380 }
6381
Robert Greenwalte0b00512014-07-02 09:59:16 -07006382 // Called when we lose the default network and have no replacement yet.
6383 // This will automatically be cleared after X seconds or a new default network
6384 // becomes CONNECTED, whichever happens first. The timer is started by the
6385 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006386 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006387 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006388 if (mNetTransitionWakeLock.isHeld()) {
6389 return;
6390 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006391 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006392 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6393 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006394 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006395 mWakelockLogs.log("ACQUIRE for " + forWhom);
6396 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006397 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006398 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006399 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006400 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006401
Hugo Benichi471b62a2017-03-30 23:18:10 +09006402 // Called when we gain a new default network to release the network transition wakelock in a
6403 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6404 // message is cancelled.
6405 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006406 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006407 if (!mNetTransitionWakeLock.isHeld()) {
6408 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006409 }
6410 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006411 // Cancel self timeout on wakelock hold.
6412 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6413 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6414 mHandler.sendMessageDelayed(msg, 1000);
6415 }
6416
6417 // Called when either message of ensureNetworkTransitionWakelock or
6418 // scheduleReleaseNetworkTransitionWakelock is processed.
6419 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6420 String event = eventName(eventId);
6421 synchronized (this) {
6422 if (!mNetTransitionWakeLock.isHeld()) {
6423 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006424 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006425 return;
6426 }
6427 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006428 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6429 mTotalWakelockDurationMs += lockDuration;
6430 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6431 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006432 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006433 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006434 }
6435
Robert Greenwalt986c7412010-09-08 15:24:47 -07006436 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006437 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006438 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006439 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006440 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006441 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006442 }
6443
Lorenzo Colittid6459092016-07-04 12:55:44 +09006444 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006445 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006446 enforceAccessPermission();
6447 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006448 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006449 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006450
6451 final NetworkAgentInfo nai;
6452 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006453 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006454 } else {
6455 nai = getNetworkAgentInfoForNetwork(network);
6456 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006457
6458 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006459 mHandler.obtainMessage(
6460 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006461 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006462
Hugo Benichid6b510a2017-04-06 17:22:18 +09006463 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006464 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006465 if (nai == null
6466 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006467 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006468 return;
6469 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006470 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006471 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006472 mConnectivityDiagnosticsHandler.sendMessage(
6473 mConnectivityDiagnosticsHandler.obtainMessage(
6474 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6475 new ReportedNetworkConnectivityInfo(
6476 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006477 return;
6478 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006479 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006480 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006481 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006482 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006483 // Validating a network that has not yet connected could result in a call to
6484 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006485 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006486 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006487 }
paulhu7aeba372020-12-30 00:42:19 +08006488 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6489 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006490 return;
6491 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006492
6493 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6494 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6495 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6496 // completed.
6497 mConnectivityDiagnosticsHandler.sendMessage(
6498 mConnectivityDiagnosticsHandler.obtainMessage(
6499 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6500 new ReportedNetworkConnectivityInfo(
6501 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006502 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006503 }
6504
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006505 // TODO: call into netd.
6506 private boolean queryUserAccess(int uid, Network network) {
6507 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6508 if (nai == null) return false;
6509
6510 // Any UID can use its default network.
6511 if (nai == getDefaultNetworkForUid(uid)) return true;
6512
6513 // Privileged apps can use any network.
6514 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6515 return true;
6516 }
6517
6518 // An unprivileged UID can use a VPN iff the VPN applies to it.
6519 if (nai.isVPN()) {
6520 return nai.networkCapabilities.appliesToUid(uid);
6521 }
6522
6523 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6524 // sockets, i.e., if it is the owner.
6525 final NetworkAgentInfo vpn = getVpnForUid(uid);
6526 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6527 && uid != vpn.networkCapabilities.getOwnerUid()) {
6528 return false;
6529 }
6530
6531 // The UID's permission must be at least sufficient for the network. Since the restricted
6532 // permission was already checked above, that just leaves background networks.
6533 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6534 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6535 }
6536
6537 // Unrestricted network. Anyone gets to use it.
6538 return true;
6539 }
6540
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006541 /**
6542 * Returns information about the proxy a certain network is using. If given a null network, it
6543 * it will return the proxy for the bound network for the caller app or the default proxy if
6544 * none.
6545 *
6546 * @param network the network we want to get the proxy information for.
6547 * @return Proxy information if a network has a proxy configured, or otherwise null.
6548 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006549 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006550 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006551 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006552 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006553 if (network == null) {
6554 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006555 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006556 true);
6557 if (activeNetwork == null) {
6558 return null;
6559 }
6560 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006561 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006562 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6563 // caller may not have.
6564 return getLinkPropertiesProxyInfo(network);
6565 }
6566 // No proxy info available if the calling UID does not have network access.
6567 return null;
6568 }
6569
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006570
6571 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006572 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6573 if (nai == null) return null;
6574 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006575 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6576 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006577 }
6578 }
6579
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006580 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006581 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006582 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006583 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006584 }
6585
Chalard Jean777e2e52018-06-07 18:02:37 +09006586 @Override
6587 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006588 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006589 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006590 }
6591
Aaron Huang9fe47be2021-06-08 13:11:45 +08006592 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006593 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006594 final NetworkAgentInfo nai = getDefaultNetwork();
6595 // TODO : this method should check that net == nai.network, unfortunately at this point
6596 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6597 // is only ever installed on the default network so in practice this is okay.
6598 if (null == nai) return;
6599 // PAC proxies only work on the default network. Therefore, only the default network
6600 // should have its link properties fixed up for PAC proxies.
6601 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6602 if (nai.everConnected()) {
6603 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6604 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006605 }
6606
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006607 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6608 // when any network changes proxy.
6609 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6610 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006611 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6612 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006613 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6614
Chalard Jean7d97afc2018-06-07 17:41:29 +09006615 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006616 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006617 }
6618 }
6619
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006620 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006621 final private HashMap<Uri, Integer> mUriEventMap;
6622 final private Context mContext;
6623 final private Handler mHandler;
6624
6625 SettingsObserver(Context context, Handler handler) {
6626 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006627 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006628 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006629 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006630 }
6631
Erik Kline05f2b402015-04-30 12:58:40 +09006632 void observe(Uri uri, int what) {
6633 mUriEventMap.put(uri, what);
6634 final ContentResolver resolver = mContext.getContentResolver();
6635 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006636 }
6637
6638 @Override
6639 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006640 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006641 }
6642
6643 @Override
6644 public void onChange(boolean selfChange, Uri uri) {
6645 final Integer what = mUriEventMap.get(uri);
6646 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006647 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006648 } else {
6649 loge("No matching event to send for URI=" + uri);
6650 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006651 }
6652 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006653
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006654 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006655 Log.d(TAG, s);
6656 }
6657
6658 private static void logw(String s) {
6659 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006660 }
6661
Daniel Brightf9e945b2020-06-15 16:10:01 -07006662 private static void logwtf(String s) {
6663 Log.wtf(TAG, s);
6664 }
6665
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006666 private static void logwtf(String s, Throwable t) {
6667 Log.wtf(TAG, s, t);
6668 }
6669
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006670 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006671 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006672 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006673
Hugo Benichi39621362017-02-11 17:04:43 +09006674 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006675 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006676 }
6677
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006678 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006679 * Return the information of all ongoing VPNs.
6680 *
6681 * <p>This method is used to update NetworkStatsService.
6682 *
6683 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006684 */
junyulai2050bed2021-01-23 09:46:34 +08006685 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006686 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006687 if (mLockdownEnabled) {
6688 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006689 }
junyulai2050bed2021-01-23 09:46:34 +08006690 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006691 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006692 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006693 if (info != null) {
6694 infoList.add(info);
6695 }
6696 }
junyulai2050bed2021-01-23 09:46:34 +08006697 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006698 }
6699
6700 /**
6701 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006702 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006703 */
junyulai2050bed2021-01-23 09:46:34 +08006704 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006705 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006706 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6707 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006708 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6709 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6710 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006711 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6712 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006713 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006714 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006715 }
6716 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006717
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006718 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006719
6720 List<String> interfaces = new ArrayList<>();
6721 for (Network network : underlyingNetworks) {
6722 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6723 if (underlyingNai == null) continue;
6724 LinkProperties lp = underlyingNai.linkProperties;
6725 for (String iface : lp.getAllInterfaceNames()) {
6726 if (!TextUtils.isEmpty(iface)) {
6727 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006728 }
6729 }
Benedict Wong34857f82019-06-12 17:46:15 +00006730 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006731
6732 if (interfaces.isEmpty()) return null;
6733
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006734 // Must be non-null or NetworkStatsService will crash.
6735 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6736 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006737 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006738 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006739
junyulai2050bed2021-01-23 09:46:34 +08006740 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6741 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006742 }
6743
James Mattisd31bdfa2020-12-23 16:37:26 -08006744 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006745 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6746 Network[] underlyingNetworks) {
6747 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006748 if (underlyingNetworks == null && defaultNetwork != null) {
6749 // null underlying networks means to track the default.
6750 underlyingNetworks = new Network[] { defaultNetwork };
6751 }
6752 return underlyingNetworks;
6753 }
6754
6755 // Returns true iff |network| is an underlying network of |nai|.
6756 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6757 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6758 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006759 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006760 final Network[] underlying = underlyingNetworksOrDefault(
6761 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006762 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006763 }
6764
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006765 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006766 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006767 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006768 * When underlying networks change, such networks may have to update capabilities to reflect
6769 * things like the metered bit, their transports, and so on. The capabilities are calculated
6770 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006771 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006772 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006773 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006774 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006775 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006776 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006777 }
6778 }
6779 }
6780
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006781 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6782 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6783 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6784 // a VPN is not up.
6785 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6786 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6787 for (UidRange range : blockedUidRanges) {
6788 if (range.contains(uid)) return true;
6789 }
6790 return false;
6791 }
6792
6793 @Override
6794 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006795 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006796 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6797 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6798 }
6799
6800 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6801 if (DBG) {
6802 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6803 + Arrays.toString(ranges));
6804 }
6805 // Cannot use a Set since the list of UID ranges might contain duplicates.
6806 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6807 for (int i = 0; i < ranges.length; i++) {
6808 if (requireVpn) {
6809 newVpnBlockedUidRanges.add(ranges[i]);
6810 } else {
6811 newVpnBlockedUidRanges.remove(ranges[i]);
6812 }
6813 }
6814
6815 try {
6816 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6817 } catch (RemoteException | ServiceSpecificException e) {
6818 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6819 + Arrays.toString(ranges) + "): netd command failed: " + e);
6820 }
6821
Chalard Jeandf29a852023-05-29 17:02:43 +09006822 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006823 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6824 }
6825
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006826 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6827 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006828 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6829 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006830 }
6831
6832 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6833 }
6834
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006835 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006836 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006837 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006838 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006839 }
6840
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006841 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6842 return mLockdownEnabled
6843 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6844 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006845 }
6846
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006847 private NetworkAgentInfo getLegacyLockdownNai() {
6848 if (!mLockdownEnabled) {
6849 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006850 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006851 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006852 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6853 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006854
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006855 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006856 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6857 // a local variable. There is no need to make a copy because its contents cannot change.
6858 final Network[] underlying = nai.declaredUnderlyingNetworks;
6859 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006860 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006861 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006862
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006863 // The legacy lockdown VPN always uses the default network.
6864 // If the VPN's underlying network is no longer the current default network, it means that
6865 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006866 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6867 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006868 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006869 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006870 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006871 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006872
6873 return nai;
6874 };
6875
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006876 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6877 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6878 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006879 private DetailedState getLegacyLockdownState(DetailedState origState) {
6880 if (origState != DetailedState.CONNECTED) {
6881 return origState;
6882 }
6883 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6884 ? DetailedState.CONNECTING
6885 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006886 }
6887
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006888 private void filterForLegacyLockdown(NetworkInfo ni) {
6889 if (!mLockdownEnabled || !ni.isConnected()) return;
6890 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6891 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6892 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6893 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6894 // network, this time with a state of CONNECTED.
6895 //
6896 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6897 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6898 // is not too far off the truth, since an always-on VPN, when not connected, is always
6899 // trying to reconnect.
6900 if (getLegacyLockdownNai() == null) {
6901 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6902 }
6903 }
6904
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006905 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006906 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006907 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006908 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006909 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6910 return;
6911 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006912 final long ident = Binder.clearCallingIdentity();
6913 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006914 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006915 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006916 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006917 } finally {
6918 Binder.restoreCallingIdentity(ident);
6919 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006920 }
Wink Savillecb117d32013-08-29 14:57:08 -07006921
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006922 @Override
6923 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006924 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006925 final long ident = Binder.clearCallingIdentity();
6926 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006927 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006928 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006929 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6930 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006931 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006932 } finally {
6933 Binder.restoreCallingIdentity(ident);
6934 }
6935 }
6936
James Mattis02220e22021-03-13 19:27:21 -08006937 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006938 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6939 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6940 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006941 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006942 }
6943
James Mattis02220e22021-03-13 19:27:21 -08006944 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006945 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006946 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006947 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6948 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006949 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006950 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6951 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6952 }
junyulaid91e7052020-08-28 13:44:33 +08006953 }
6954
James Mattis02220e22021-03-13 19:27:21 -08006955 private void onPackageChanged(@NonNull final String packageName) {
6956 // This is necessary in case a package is added or removed, but also when it's replaced to
6957 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6958 // as one in the preferences, then it should follow the same routing as that other package,
6959 // which means updating the rules is never to be needed in this case (whether it joins or
6960 // leaves a UID with a preference).
6961 if (isMappedInOemNetworkPreference(packageName)) {
6962 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6963 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006964
6965 // Invalidates cache entry when the package is updated.
6966 synchronized (mSelfCertifiedCapabilityCache) {
6967 mSelfCertifiedCapabilityCache.remove(packageName);
6968 }
James Mattis02220e22021-03-13 19:27:21 -08006969 }
6970
6971 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006972 @Override
6973 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006974 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006975 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006976 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006977
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006978 // User should be filled for below intents, check the existence.
6979 if (user == null) {
6980 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6981 return;
6982 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006983
Lorenzo Colitticd675292021-02-04 17:32:07 +09006984 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006985 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006986 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006987 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006988 } else {
junyulaid91e7052020-08-28 13:44:33 +08006989 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006990 }
6991 }
6992 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006993
James Mattis02220e22021-03-13 19:27:21 -08006994 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6995 @Override
6996 public void onReceive(Context context, Intent intent) {
6997 ensureRunningOnConnectivityServiceThread();
6998 switch (intent.getAction()) {
6999 case Intent.ACTION_PACKAGE_ADDED:
7000 case Intent.ACTION_PACKAGE_REMOVED:
7001 case Intent.ACTION_PACKAGE_REPLACED:
7002 onPackageChanged(intent.getData().getSchemeSpecificPart());
7003 break;
7004 default:
7005 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7006 }
7007 }
7008 };
7009
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007010 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007011 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007012
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007013 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007014 public final String name;
7015 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007016 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007017 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007018
lifraf3a3492021-03-10 13:58:14 +08007019 NetworkProviderInfo(String name, Messenger messenger, int providerId,
7020 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007021 this.name = name;
7022 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007023 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007024 mDeathRecipient = deathRecipient;
7025
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007026 if (mDeathRecipient == null) {
7027 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007028 }
7029 }
7030
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007031 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007032 try {
7033 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
7034 } catch (RemoteException e) {
7035 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007036 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007037 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007038 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007039
James Mattis4fce5d12020-11-12 15:53:42 -08007040 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
7041 for (int i = 0; i < requests.size(); i++) {
7042 ensureNetworkRequestHasType(requests.get(i));
7043 }
7044 }
7045
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007046 private void ensureNetworkRequestHasType(NetworkRequest request) {
7047 if (request.type == NetworkRequest.Type.NONE) {
7048 throw new IllegalArgumentException(
7049 "All NetworkRequests in ConnectivityService must have a type");
7050 }
7051 }
7052
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007053 /**
7054 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08007055 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007056 */
James Mattis258ea3c2020-11-15 15:04:40 -08007057 @VisibleForTesting
7058 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08007059 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
7060 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08007061 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08007062
James Mattisa076c532020-12-02 14:12:41 -08007063 // mSatisfier and mActiveRequest rely on one another therefore set them together.
7064 void setSatisfier(
7065 @Nullable final NetworkAgentInfo satisfier,
7066 @Nullable final NetworkRequest activeRequest) {
7067 mSatisfier = satisfier;
7068 mActiveRequest = activeRequest;
7069 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007070
James Mattisd31bdfa2020-12-23 16:37:26 -08007071 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007072 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09007073 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08007074 private NetworkAgentInfo mSatisfier;
7075 NetworkAgentInfo getSatisfier() {
7076 return mSatisfier;
7077 }
7078
7079 // The request in mRequests assigned to a network agent. This is null if none of the
7080 // requests in mRequests can be satisfied. This member has the constraint of only being
7081 // accessible on the handler thread.
7082 @Nullable
7083 private NetworkRequest mActiveRequest;
7084 NetworkRequest getActiveRequest() {
7085 return mActiveRequest;
7086 }
7087
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007088 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007089 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08007090 @Nullable
7091 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007092
7093 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08007094 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007095 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007096 final int mPid;
7097 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08007098 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007099 @Nullable
7100 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007101
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007102 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08007103 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007104
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007105 // Effective UID of this request. This is different from mUid when a privileged process
7106 // files a request on behalf of another UID. This UID is used to determine blocked status,
7107 // UID matching, and so on. mUid above is used for permission checks and to enforce the
7108 // maximum limit of registered callbacks per UID.
7109 final int mAsUid;
7110
paulhu48291862021-07-14 14:53:57 +08007111 // Preference order of this request.
7112 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08007113
James Mattis3ce3d3c2021-02-09 18:18:28 -08007114 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
7115 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
7116 // maintained for keying off of. This is only a concern when the original nri
7117 // mNetworkRequests changes which happens currently for apps that register callbacks to
7118 // track the default network. In those cases, the nri is updated to have mNetworkRequests
7119 // that match the per-app default nri that currently tracks the calling app's uid so that
7120 // callbacks are fired at the appropriate time. When the callbacks fire,
7121 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
7122 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
7123 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7124 @NonNull
7125 private final NetworkRequest mNetworkRequestForCallback;
7126 NetworkRequest getNetworkRequestForCallback() {
7127 return mNetworkRequestForCallback;
7128 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007129
James Mattisd31bdfa2020-12-23 16:37:26 -08007130 /**
7131 * Get the list of UIDs this nri applies to.
7132 */
7133 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00007134 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08007135 // networkCapabilities.getUids() returns a defensive copy.
7136 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007137 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
7138 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08007139 }
7140
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007141 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
7142 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08007143 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08007144 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007145 }
7146
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007147 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007148 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007149 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007150 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007151 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007152 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007153 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007154 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007155 mBinder = null;
7156 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007157 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007158 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007159 mPerUidCounter = getRequestCounter(this);
7160 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007161 /**
7162 * Location sensitive data not included in pending intent. Only included in
7163 * {@link NetworkCallback}.
7164 */
7165 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007166 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007167 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007168 }
7169
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007170 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007171 @Nullable final IBinder binder,
7172 @NetworkCallback.Flag int callbackFlags,
7173 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007174 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7175 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007176 }
7177
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007178 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007179 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007180 @Nullable final IBinder binder,
7181 @NetworkCallback.Flag int callbackFlags,
7182 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007183 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007184 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007185 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007186 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007187 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007188 mBinder = binder;
7189 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007190 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007191 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007192 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007193 mPerUidCounter = getRequestCounter(this);
7194 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007195 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007196 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007197 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007198 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007199 }
7200
James Mattis3ce3d3c2021-02-09 18:18:28 -08007201 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7202 @NonNull final List<NetworkRequest> r) {
7203 super();
7204 ensureAllNetworkRequestsHaveType(r);
7205 mRequests = initializeRequests(r);
7206 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007207 final NetworkAgentInfo satisfier = nri.getSatisfier();
7208 if (null != satisfier) {
7209 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7210 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007211 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007212 // As this code creates a new NRI with a new set of requests, figure out which of
7213 // the list of requests should be the active request. It is always the first
7214 // request of the list that can be satisfied by the satisfier since the order of
7215 // requests is a priority order.
7216 // Note even in the presence of a satisfier there may not be an active request,
7217 // when the satisfier is the no-service network.
7218 NetworkRequest activeRequest = null;
7219 for (final NetworkRequest candidate : r) {
7220 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7221 activeRequest = candidate;
7222 break;
7223 }
7224 }
7225 setSatisfier(satisfier, activeRequest);
7226 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007227 mMessenger = nri.mMessenger;
7228 mBinder = nri.mBinder;
7229 mPid = nri.mPid;
7230 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007231 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007232 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007233 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007234 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007235 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007236 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007237 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007238 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007239 }
7240
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007241 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007242 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007243 }
7244
paulhue9913722021-05-26 15:19:20 +08007245 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007246 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007247 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007248 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007249 }
7250
James Mattis2516da32021-01-31 17:06:19 -08007251 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7252 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7253 // false.
7254 boolean isBeingSatisfied() {
7255 return (null != mSatisfier && null != mActiveRequest);
7256 }
7257
James Mattis3d229892020-11-16 16:46:28 -08007258 boolean isMultilayerRequest() {
7259 return mRequests.size() > 1;
7260 }
7261
James Mattis45d81842021-01-10 14:24:24 -08007262 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7263 // Creating a defensive copy to prevent the sender from modifying the list being
7264 // reflected in the return value of this method.
7265 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007266 return Collections.unmodifiableList(tempRequests);
7267 }
7268
James Mattisb1392002021-03-31 13:57:52 -07007269 void linkDeathRecipient() {
7270 if (null != mBinder) {
7271 try {
7272 mBinder.linkToDeath(this, 0);
7273 } catch (RemoteException e) {
7274 binderDied();
7275 }
7276 }
7277 }
7278
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007279 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007280 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007281 try {
7282 mBinder.unlinkToDeath(this, 0);
7283 } catch (NoSuchElementException e) {
7284 // Temporary workaround for b/194394697 pending analysis of additional logs
7285 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7286 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007287 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007288 }
7289
paulhu48291862021-07-14 14:53:57 +08007290 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7291 // Compare two preference orders.
7292 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007293 }
7294
paulhu48291862021-07-14 14:53:57 +08007295 int getPreferenceOrderForNetd() {
7296 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7297 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7298 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007299 }
paulhu48291862021-07-14 14:53:57 +08007300 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007301 }
7302
James Mattis4fce5d12020-11-12 15:53:42 -08007303 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007304 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007305 // As an immutable collection, mRequests cannot change by the time the
7306 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7307 // is acceptable. Use handleReleaseNetworkRequest and not directly
7308 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7309 // the app already unregistered the request.
7310 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7311 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007312 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007313
James Mattis4fce5d12020-11-12 15:53:42 -08007314 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007315 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007316 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7317 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007318 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007319 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007320 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007321 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007322 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007323 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007324 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007325 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007326 }
7327
Junyu Lai00d92df2022-07-05 11:01:52 +08007328 // Keep backward compatibility since the ServiceSpecificException is used by
7329 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7330 public static class RequestInfoPerUidCounter extends PerUidCounter {
7331 RequestInfoPerUidCounter(int maxCountPerUid) {
7332 super(maxCountPerUid);
7333 }
7334
7335 @Override
7336 public synchronized void incrementCountOrThrow(int uid) {
7337 try {
7338 super.incrementCountOrThrow(uid);
7339 } catch (IllegalStateException e) {
7340 throw new ServiceSpecificException(
7341 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7342 "Uid " + uid + " exceeded its allotted requests limit");
7343 }
7344 }
7345
7346 @Override
7347 public synchronized void decrementCountOrThrow(int uid) {
7348 throw new UnsupportedOperationException("Use decrementCount instead.");
7349 }
7350
7351 public synchronized void decrementCount(int uid) {
7352 try {
7353 super.decrementCountOrThrow(uid);
7354 } catch (IllegalStateException e) {
7355 logwtf("Exception when decrement per uid request count: ", e);
7356 }
7357 }
7358 }
7359
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007360 // This checks that the passed capabilities either do not request a
7361 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007362 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007363 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007364 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007365 throw new SecurityException("Insufficient permissions to request a specific SSID");
7366 }
paulhu1a407652019-03-22 16:35:06 +08007367
7368 if (nc.hasSignalStrength()
7369 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7370 throw new SecurityException(
7371 "Insufficient permissions to request a specific signal strength");
7372 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007373 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007374
junyulai2217bec2021-04-14 23:33:31 +08007375 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007376 enforceNetworkFactoryPermission();
7377 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007378 }
7379
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007380 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007381 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007382 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007383 // mNetworkRequests may contain the same value multiple times in case of
7384 // multilayer requests. It won't matter in this case because the thresholds
7385 // will then be the same and be deduplicated as they enter the `thresholds` set.
7386 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007387 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7388 for (final NetworkRequest req : nri.mRequests) {
7389 if (req.networkCapabilities.hasSignalStrength()
7390 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7391 thresholds.add(req.networkCapabilities.getSignalStrength());
7392 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007393 }
7394 }
7395 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007396 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007397 }
7398
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007399 private void updateSignalStrengthThresholds(
7400 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007401 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007402
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007403 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007404 String detail;
7405 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7406 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7407 } else {
7408 detail = reason;
7409 }
7410 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007411 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007412 }
7413
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007414 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007415 }
7416
Chalard Jeandd421992021-12-16 23:16:02 +09007417 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007418 if (nc == null) {
7419 return;
7420 }
7421 NetworkSpecifier ns = nc.getNetworkSpecifier();
7422 if (ns == null) {
7423 return;
7424 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007425 if (ns instanceof MatchAllNetworkSpecifier) {
7426 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7427 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007428 }
7429
Chalard Jeandd421992021-12-16 23:16:02 +09007430 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007431 ensureValidNetworkSpecifier(nc);
7432 if (nc.isPrivateDnsBroken()) {
7433 throw new IllegalArgumentException("Can't request broken private DNS");
7434 }
Chalard Jeande665262022-02-25 16:12:12 +09007435 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007436 throw new IllegalArgumentException("Can't request access UIDs");
7437 }
lucasline117e2e2019-10-22 18:27:33 +08007438 }
7439
Chalard Jeandd421992021-12-16 23:16:02 +09007440 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7441 ensureListenableCapabilities(nc);
7442 final String badCapability = nc.describeFirstNonRequestableCapability();
7443 if (badCapability != null) {
7444 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7445 }
7446 }
7447
Chiachang Wang3bc52762021-11-25 14:17:57 +08007448 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7449 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007450 private boolean isTargetSdkAtleast(int version, int callingUid,
7451 @NonNull String callingPackageName) {
7452 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007453 final PackageManager pm =
7454 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007455 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007456 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007457 if (callingVersion < version) return false;
7458 } catch (PackageManager.NameNotFoundException e) { }
7459 return true;
7460 }
7461
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007462 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007463 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007464 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007465 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007466 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007467 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007468 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7469 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007470 throw new SecurityException("Insufficient permissions to specify legacy type");
7471 }
markchienfac84a22020-03-18 21:16:15 +08007472 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007473 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007474 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007475 // Privileged callers can track the default network of another UID by passing in a UID.
7476 if (asUid != Process.INVALID_UID) {
7477 enforceSettingsPermission();
7478 } else {
7479 asUid = callingUid;
7480 }
junyulaiad010792021-01-11 16:53:38 +08007481 final NetworkRequest.Type reqType;
7482 try {
7483 reqType = NetworkRequest.Type.values()[reqTypeInt];
7484 } catch (ArrayIndexOutOfBoundsException e) {
7485 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7486 }
7487 switch (reqType) {
7488 case TRACK_DEFAULT:
7489 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007490 // is unused and will be replaced by ones appropriate for the UID (usually, the
7491 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007492 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007493 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007494 enforceAccessPermission();
7495 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007496 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007497 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007498 networkCapabilities = new NetworkCapabilities(defaultNc);
7499 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007500 case BACKGROUND_REQUEST:
7501 enforceNetworkStackOrSettingsPermission();
7502 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007503 case REQUEST:
7504 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7505 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007506 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007507 // TODO: this is incorrect. We mark the request as metered or not depending on
7508 // the state of the app when the request is filed, but we never change the
7509 // request if the app changes network state. http://b/29964605
7510 enforceMeteredApnPolicy(networkCapabilities);
7511 break;
junyulai1b1c8742021-03-12 20:05:08 +08007512 case LISTEN_FOR_BEST:
7513 enforceAccessPermission();
7514 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7515 break;
junyulaiad010792021-01-11 16:53:38 +08007516 default:
7517 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007518 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007519 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007520 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007521 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007522
junyulai1b1c8742021-03-12 20:05:08 +08007523 // Enforce FOREGROUND if the caller does not have permission to use background network.
7524 if (reqType == LISTEN_FOR_BEST) {
7525 restrictBackgroundRequestForCaller(networkCapabilities);
7526 }
7527
7528 // Set the UID range for this request to the single UID of the requester, unless the
7529 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007530 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7531 // are no visible methods to set the UIDs, an app could use reflection to try and get
7532 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007533 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007534 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7535 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007536
Etan Cohen85000162017-02-05 10:42:27 -08007537 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007538 throw new IllegalArgumentException("Bad timeout specified");
7539 }
Etan Cohen9786d922015-11-18 10:56:15 -08007540
James Mattis3ce3d3c2021-02-09 18:18:28 -08007541 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007542 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007543 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007544 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007545 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007546 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007547
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007548 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7549 // copied from the default request above. (This is necessary to ensure, for example, that
7550 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7551 // changes don't alter request matching.
7552 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7553 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007554 throw new IllegalStateException(
7555 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007556 + networkCapabilities + " vs. " + defaultNc);
7557 }
7558
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007559 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007560 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007561 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007562 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007563 }
7564 return networkRequest;
7565 }
7566
James Mattis3ce3d3c2021-02-09 18:18:28 -08007567 /**
7568 * Return the nri to be used when registering a network request. Specifically, this is used with
7569 * requests registered to track the default request. If there is currently a per-app default
7570 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7571 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007572 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7573 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007574 * @param nr the network request for the nri.
7575 * @param msgr the messenger for the nri.
7576 * @param binder the binder for the nri.
7577 * @param callingAttributionTag the calling attribution tag for the nri.
7578 * @return the nri to register.
7579 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007580 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007581 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007582 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007583 @Nullable String callingAttributionTag) {
7584 final List<NetworkRequest> requests;
7585 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7586 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007587 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007588 } else {
7589 requests = Collections.singletonList(nr);
7590 }
Roshan Pius951c0032020-12-22 15:10:42 -08007591 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007592 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007593 }
7594
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007595 private boolean shouldCheckCapabilitiesDeclaration(
7596 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7597 @NonNull final String callingPackageName) {
7598 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7599 // Only run the check if the change is enabled.
7600 if (!mDeps.isChangeEnabled(
7601 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7602 callingPackageName, user)) {
7603 return false;
7604 }
7605
7606 return networkCapabilities.hasCapability(
7607 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7608 || networkCapabilities.hasCapability(
7609 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7610 }
7611
7612 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
7613 @NonNull final NetworkCapabilities networkCapabilities) {
7614 // This check is added to fix the linter error for "current min is 30", which is not going
7615 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007616 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007617 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7618 return;
7619 }
7620 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007621 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007622 try {
7623 synchronized (mSelfCertifiedCapabilityCache) {
7624 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7625 callerPackageName);
7626 if (applicationNetworkCapabilities == null) {
7627 final PackageManager packageManager = mContext.getPackageManager();
7628 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7629 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7630 callerPackageName
7631 );
7632 final XmlResourceParser parser = packageManager
7633 .getResourcesForApplication(callerPackageName)
7634 .getXml(networkSliceProperty.getResourceId());
7635 applicationNetworkCapabilities =
7636 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7637 mSelfCertifiedCapabilityCache.put(callerPackageName,
7638 applicationNetworkCapabilities);
7639 }
7640
7641 }
7642 } catch (PackageManager.NameNotFoundException ne) {
7643 throw new SecurityException(
7644 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7645 + " property");
7646 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7647 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007648 } finally {
7649 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007650 }
7651
7652 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7653 networkCapabilities);
7654 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007655 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007656 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007657 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7658 callingPackageName)) {
7659 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7660 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007661 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007662 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7663 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7664 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7665 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007666 }
junyulai96bd9fe2022-03-08 17:36:42 +08007667 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007668 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007669 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007670 }
7671 }
7672
fenglu3f357402015-03-20 11:29:56 -07007673 @Override
fenglub00f4882015-04-21 17:12:05 -07007674 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007675 enforceAccessPermission();
7676 NetworkAgentInfo nai = null;
7677 if (network == null) {
7678 return false;
7679 }
7680 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007681 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007682 }
7683 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007684 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007685 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007686 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007687 Integer uidReqs = mBandwidthRequests.get(uid);
7688 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007689 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007690 }
7691 mBandwidthRequests.put(uid, ++uidReqs);
7692 }
fenglu3f357402015-03-20 11:29:56 -07007693 return true;
7694 }
7695 return false;
7696 }
7697
Felipe Leme0a5ae422016-06-20 16:36:29 -07007698 private boolean isSystem(int uid) {
7699 return uid < Process.FIRST_APPLICATION_UID;
7700 }
fenglu3f357402015-03-20 11:29:56 -07007701
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007702 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007703 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007704 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007705 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007706 return;
7707 }
Hugo Benichi39621362017-02-11 17:04:43 +09007708 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7709 // Policy already enforced.
7710 return;
7711 }
paulhuaf50d7d2020-12-24 19:47:34 +08007712 final long ident = Binder.clearCallingIdentity();
7713 try {
7714 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7715 // If UID is restricted, don't allow them to bring up metered APNs.
7716 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7717 }
7718 } finally {
7719 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007720 }
7721 }
7722
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007723 @Override
7724 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007725 PendingIntent operation, @NonNull String callingPackageName,
7726 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007727 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007728 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007729 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007730 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007731 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007732 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007733 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007734 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007735 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007736 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7737 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007738
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007739 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007740 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007741 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7742 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007743 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007744 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7745 nri));
7746 return networkRequest;
7747 }
7748
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007749 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7750 mHandler.sendMessageDelayed(
7751 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007752 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007753 }
7754
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007755 @Override
7756 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007757 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007758 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007759 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007760 }
7761
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007762 // In order to implement the compatibility measure for pre-M apps that call
7763 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7764 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7765 // This ensures it has permission to do so.
7766 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7767 if (nc == null) {
7768 return false;
7769 }
7770 int[] transportTypes = nc.getTransportTypes();
7771 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7772 return false;
7773 }
7774 try {
7775 mContext.enforceCallingOrSelfPermission(
7776 android.Manifest.permission.ACCESS_WIFI_STATE,
7777 "ConnectivityService");
7778 } catch (SecurityException e) {
7779 return false;
7780 }
7781 return true;
7782 }
7783
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007784 @Override
7785 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007786 Messenger messenger, IBinder binder,
7787 @NetworkCallback.Flag int callbackFlags,
7788 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007789 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007790 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7791 enforceAccessPermission();
7792 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007793
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007794 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007795 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007796 Binder.getCallingPid(), callingUid, callingPackageName);
7797 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007798 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7799 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7800 // onLost and onAvailable callbacks when networks move in and out of the background.
7801 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7802 // can't request networks.
7803 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007804 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007805
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007806 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007807 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007808 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007809 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007810 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007811 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007812
7813 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7814 return networkRequest;
7815 }
7816
7817 @Override
7818 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007819 PendingIntent operation, @NonNull String callingPackageName,
7820 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007821 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007822 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007823 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7824 enforceAccessPermission();
7825 }
Chalard Jeandd421992021-12-16 23:16:02 +09007826 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007827 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007828 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007829 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007830 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007831
7832 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007833 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007834 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7835 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007836 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007837
WeiZhang1cc3f172021-06-03 19:02:04 -05007838 mHandler.sendMessage(mHandler.obtainMessage(
7839 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007840 }
7841
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007842 /** Returns the next Network provider ID. */
7843 public final int nextNetworkProviderId() {
7844 return mNextNetworkProviderId.getAndIncrement();
7845 }
7846
Erik Kline0c04b742016-07-07 16:50:58 +09007847 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007848 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007849 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007850 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007851 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007852 }
7853
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007854 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7855 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007856 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7857 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7858 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007859 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007860 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007861 return;
7862 }
7863
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007864 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7865 mNetworkProviderInfos.put(npi.messenger, npi);
7866 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007867 }
7868
7869 @Override
7870 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007871 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007872 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007873 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007874 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007875 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7876 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007877 }
7878
7879 @Override
7880 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007881 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007882 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007883 }
7884
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007885 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007886 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007887 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7888 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007889 Objects.requireNonNull(score);
7890 Objects.requireNonNull(caps);
7891 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007892 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007893 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007894 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7895 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007896 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7897 }
7898
Chalard Jeanbb902a52021-08-18 01:35:19 +09007899 private void updateOfferScore(final NetworkOffer offer) {
7900 final boolean yieldToBadWiFi =
7901 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7902 final NetworkOffer newOffer = new NetworkOffer(
7903 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7904 offer.caps, offer.callback, offer.providerId);
7905 if (offer.equals(newOffer)) return;
7906 handleRegisterNetworkOffer(newOffer);
7907 }
7908
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007909 @Override
7910 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007911 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007912 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7913 }
7914
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007915 private void handleUnregisterNetworkProvider(Messenger messenger) {
7916 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7917 if (npi == null) {
7918 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007919 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007920 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007921 // Unregister all the offers from this provider
7922 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7923 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007924 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007925 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7926 toRemove.add(noi);
7927 }
7928 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007929 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007930 handleUnregisterNetworkOffer(noi);
7931 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007932 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007933 }
7934
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007935 @Override
James Mattisf7027322020-12-13 16:28:14 -08007936 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007937 if (request.hasTransport(TRANSPORT_TEST)) {
7938 enforceNetworkFactoryOrTestNetworksPermission();
7939 } else {
7940 enforceNetworkFactoryPermission();
7941 }
James Mattisf7027322020-12-13 16:28:14 -08007942 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7943 if (nri != null) {
7944 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7945 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7946 mHandler.post(() -> handleReleaseNetworkRequest(
7947 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7948 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007949 }
7950
Paul Jensen1f567382015-02-13 14:18:39 -05007951 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7952 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007953 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007954 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007955 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007956 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007957 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007958
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007959 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007960 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007961 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007962
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007963 // UID ranges for users that are currently blocked by VPNs.
7964 // This array is accessed and iterated on multiple threads without holding locks, so its
7965 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7966 // (on the handler thread).
7967 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7968
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007969 // Must only be accessed on the handler thread
7970 @NonNull
7971 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7972
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007973 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007974 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007975
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007976 // Current OEM network preferences. This object must only be written to on the handler thread.
7977 // Since it is immutable and always non-null, other threads may read it if they only care
7978 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007979 @NonNull
7980 private OemNetworkPreferences mOemNetworkPreferences =
7981 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007982 // Current per-profile network preferences. This object follows the same threading rules as
7983 // the OEM network preferences above.
7984 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007985 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7986 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007987
lucaslin3ba7cc22022-12-19 02:35:33 +00007988 // Current VPN network preferences. This object follows the same threading rules as the OEM
7989 // network preferences above.
7990 @NonNull
7991 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7992 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7993
paulhu51f77dc2021-06-07 02:34:20 +00007994 // A set of UIDs that should use mobile data preferentially if available. This object follows
7995 // the same threading rules as the OEM network preferences above.
7996 @NonNull
7997 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7998
James Mattiscb1e0362021-04-06 17:07:42 -07007999 // OemNetworkPreferences activity String log entries.
8000 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
8001 @NonNull
8002 private final LocalLog mOemNetworkPreferencesLogs =
8003 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
8004
James Mattis02220e22021-03-13 19:27:21 -08008005 /**
8006 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
8007 * @param packageName the package name to check existence of a mapping for.
8008 * @return true if a mapping exists, false otherwise
8009 */
8010 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
8011 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
8012 }
8013
James Mattise3ef1912020-12-20 11:09:58 -08008014 // The always-on request for an Internet-capable network that apps without a specific default
8015 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08008016 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09008017 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008018 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08008019 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08008020 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08008021 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008022 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09008023
James Mattisd31bdfa2020-12-23 16:37:26 -08008024 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
8025 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
8026 }
8027
8028 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08008029 * Return the default network request currently tracking the given uid.
8030 * @param uid the uid to check.
8031 * @return the NetworkRequestInfo tracking the given uid.
8032 */
8033 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08008034 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008035 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008036 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008037 // Checking the first request is sufficient as only multilayer requests will have more
8038 // than one request and for multilayer, all requests will track the same uids.
8039 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08008040 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08008041 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008042 highestPriorityNri = nri;
8043 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08008044 }
8045 }
paulhuaa0743d2021-05-26 21:56:03 +08008046 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008047 }
8048
8049 /**
8050 * Get a copy of the network requests of the default request that is currently tracking the
8051 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008052 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8053 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008054 * @param requestorUid the uid to check the default for.
8055 * @param requestorPackageName the requestor's package name.
8056 * @return a copy of the default's NetworkRequest that is tracking the given uid.
8057 */
8058 @NonNull
8059 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008060 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008061 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008062 getDefaultRequestTrackingUid(asUid).mRequests,
8063 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008064 }
8065
8066 /**
8067 * Copy the given nri's NetworkRequest collection.
8068 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008069 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8070 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008071 * @param requestorUid the uid to set on the copied collection.
8072 * @param requestorPackageName the package name to set on the copied collection.
8073 * @return the copied NetworkRequest collection.
8074 */
8075 @NonNull
8076 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008077 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
8078 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008079 final List<NetworkRequest> requests = new ArrayList<>();
8080 for (final NetworkRequest nr : requestsToCopy) {
8081 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008082 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08008083 nr.legacyType, nextNetworkRequestId(), nr.type));
8084 }
8085 return requests;
8086 }
8087
8088 @NonNull
8089 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008090 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
8091 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09008092 // These capabilities are for a TRACK_DEFAULT callback, so:
8093 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
8094 // mDefaultRequest and a per-UID default request.
8095 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008096 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09008097 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008098 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
8099 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008100 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008101 restrictRequestUidsForCallerAndSetRequestorInfo(
8102 netCap, requestorUid, requestorPackageName);
8103 return netCap;
8104 }
8105
8106 /**
8107 * Get the nri that is currently being tracked for callbacks by per-app defaults.
8108 * @param nr the network request to check for equality against.
8109 * @return the nri if one exists, null otherwise.
8110 */
8111 @Nullable
8112 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
8113 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8114 if (nri.getNetworkRequestForCallback().equals(nr)) {
8115 return nri;
8116 }
8117 }
8118 return null;
8119 }
8120
8121 /**
8122 * Check if an nri is currently being managed by per-app default networking.
8123 * @param nri the nri to check.
8124 * @return true if this nri is currently being managed by per-app default networking.
8125 */
8126 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
8127 // nri.mRequests.get(0) is only different from the original request filed in
8128 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
8129 // functionality therefore if these two don't match, it means this particular nri is
8130 // currently being managed by a per-app default.
8131 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
8132 }
8133
8134 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008135 * Determine if an nri is a managed default request that disallows default networking.
8136 * @param nri the request to evaluate
8137 * @return true if device-default networking is disallowed
8138 */
8139 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
8140 // Check if this nri is a managed default that supports the default network at its
8141 // lowest priority request.
8142 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
8143 final NetworkCapabilities lowestPriorityNetCap =
8144 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
8145 return isPerAppDefaultRequest(nri)
8146 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8147 lowestPriorityNetCap));
8148 }
8149
Erik Kline05f2b402015-04-30 12:58:40 +09008150 // Request used to optionally keep mobile data active even when higher
8151 // priority networks like Wi-Fi are active.
8152 private final NetworkRequest mDefaultMobileDataRequest;
8153
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008154 // Request used to optionally keep wifi data active even when higher
8155 // priority networks like ethernet are active.
8156 private final NetworkRequest mDefaultWifiRequest;
8157
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008158 // Request used to optionally keep vehicle internal network always active
8159 private final NetworkRequest mDefaultVehicleRequest;
8160
James Mattisd31bdfa2020-12-23 16:37:26 -08008161 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8162 // network with no service. This NAI should never be matched against, nor should any public API
8163 // ever return the associated network. For this reason, this NAI is not in the list of available
8164 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8165 // default requests that don't support using the device default network which will ultimately
8166 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8167 @VisibleForTesting
8168 final NetworkAgentInfo mNoServiceNetwork;
8169
Chalard Jean5b409c72021-02-04 13:12:59 +09008170 // The NetworkAgentInfo currently satisfying the default request, if any.
8171 private NetworkAgentInfo getDefaultNetwork() {
8172 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008173 }
8174
James Mattis2516da32021-01-31 17:06:19 -08008175 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008176 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008177 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8178 // Currently, all network requests will have the same uids therefore checking the first
8179 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008180 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008181 if (null == uids) {
8182 continue;
8183 }
8184 for (final UidRange range : uids) {
8185 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008186 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008187 highestPriorityNri = nri;
8188 }
James Mattis2516da32021-01-31 17:06:19 -08008189 }
8190 }
8191 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008192 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008193 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008194 }
8195
Varun Ananddf569952019-02-06 10:13:38 -08008196 @Nullable
8197 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8198 return nai != null ? nai.network : null;
8199 }
8200
8201 private void ensureRunningOnConnectivityServiceThread() {
8202 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8203 throw new IllegalStateException(
8204 "Not running on ConnectivityService thread: "
8205 + Thread.currentThread().getName());
8206 }
8207 }
8208
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008209 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008210 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8211 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008212 }
8213
Chalard Jean29d06db2018-05-02 21:14:54 +09008214 /**
Chalard Jeane0aaca52023-10-17 13:23:07 +09008215 * Returns whether local agents are supported on this device.
8216 *
8217 * Local agents are supported from U on TVs, and from V on all devices.
8218 */
8219 @VisibleForTesting
8220 public boolean areLocalAgentsSupported() {
8221 final PackageManager pm = mContext.getPackageManager();
8222 // Local agents are supported starting on U on TVs and on V on everything else.
8223 return mDeps.isAtLeastV() || (mDeps.isAtLeastU() && pm.hasSystemFeature(FEATURE_LEANBACK));
8224 }
8225
8226 /**
Chalard Jean29d06db2018-05-02 21:14:54 +09008227 * Register a new agent with ConnectivityService to handle a network.
8228 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008229 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008230 * @param networkInfo the initial info associated with this network. It can be updated later :
8231 * see {@link #updateNetworkInfo}.
8232 * @param linkProperties the initial link properties of this network. They can be updated
8233 * later : see {@link #updateLinkProperties}.
8234 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008235 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008236 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008237 * @param localNetworkConfig config about this local network, or null if not a local network
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008238 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008239 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008240 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008241 */
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008242 public Network registerNetworkAgent(INetworkAgent na,
8243 NetworkInfo networkInfo,
8244 LinkProperties linkProperties,
8245 NetworkCapabilities networkCapabilities,
8246 @NonNull NetworkScore initialScore,
8247 @Nullable LocalNetworkConfig localNetworkConfig,
8248 NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09008249 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008250 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8251 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8252 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008253 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008254 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008255 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008256 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008257 } else {
8258 enforceNetworkFactoryPermission();
8259 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09008260 final boolean hasLocalCap =
8261 networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
8262 if (hasLocalCap && !areLocalAgentsSupported()) {
8263 // Before U, netd doesn't support PHYSICAL_LOCAL networks so this can't work.
8264 throw new IllegalArgumentException("Local agents are not supported in this version");
8265 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008266 final boolean hasLocalNetworkConfig = null != localNetworkConfig;
8267 if (hasLocalCap != hasLocalNetworkConfig) {
8268 throw new IllegalArgumentException(null != localNetworkConfig
8269 ? "Only local network agents can have a LocalNetworkConfig"
8270 : "Local network agents must have a LocalNetworkConfig"
8271 );
8272 }
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008273
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008274 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008275 final long token = Binder.clearCallingIdentity();
8276 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008277 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008278 networkCapabilities, initialScore, networkAgentConfig, localNetworkConfig,
8279 providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008280 } finally {
8281 Binder.restoreCallingIdentity(token);
8282 }
8283 }
8284
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008285 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008286 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008287 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig,
8288 @Nullable LocalNetworkConfig localNetworkConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09008289 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008290
Chalard Jeandbc46952022-02-02 00:14:18 +09008291 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8292 // and mutate them at any time.
8293 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8294 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8295 final LinkProperties lpCopy = new LinkProperties(linkProperties);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008296 // No need to copy |localNetworkConfiguration| as it is immutable.
Chalard Jeandbc46952022-02-02 00:14:18 +09008297
Chalard Jean366c5252022-01-25 18:27:53 +09008298 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008299 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008300 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8301 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008302 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008303 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008304 localNetworkConfig, currentScore, mContext, mTrackerHandler,
8305 new NetworkAgentConfig(networkAgentConfig), this, mNetd, mDnsResolver, providerId,
8306 uid, mLingerDelayMs, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008307
Chalard Jeandbc46952022-02-02 00:14:18 +09008308 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008309 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008310 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008311 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008312 mDeps.getNetworkStack().makeNetworkMonitor(
8313 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008314 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8315 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008316 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008317 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008318 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008319 }
8320
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008321 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008322 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008323 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008324 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008325 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008326 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8327 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8328 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008329
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008330 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008331
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008332 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008333 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008334 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008335 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008336
8337 try {
8338 networkMonitor.start();
8339 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008340 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008341 }
Chalard Jean366c5252022-01-25 18:27:53 +09008342
Chalard Jean1e4c2182023-10-06 18:45:53 +09008343 if (nai.isLocalNetwork()) {
8344 updateLocalNetworkConfig(nai, null /* oldConfig */, nai.localNetworkConfig);
8345 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008346 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008347 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008348 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008349 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008350 }
8351
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008352 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8353 @NonNull public final NetworkOffer offer;
8354
8355 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8356 this.offer = offer;
8357 }
8358
8359 @Override
8360 public void binderDied() {
8361 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8362 }
8363 }
8364
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008365 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8366 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8367 if (npi.providerId == providerId) return true;
8368 }
8369 return false;
8370 }
8371
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008372 /**
8373 * Register or update a network offer.
8374 * @param newOffer The new offer. If the callback member is the same as an existing
8375 * offer, it is an update of that offer.
8376 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008377 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008378 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8379 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008380 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008381 // This may actually happen if a provider updates its score or registers and then
8382 // immediately unregisters. The offer would still be in the handler queue, but the
8383 // provider would have been removed.
8384 if (DBG) log("Received offer from an unregistered provider");
8385 return;
8386 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008387 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8388 if (null != existingOffer) {
8389 handleUnregisterNetworkOffer(existingOffer);
8390 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008391 if (DBG) {
8392 // handleUnregisterNetworkOffer has already logged the old offer
8393 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8394 }
8395 } else {
8396 if (DBG) {
8397 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8398 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008399 }
8400 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8401 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008402 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008403 } catch (RemoteException e) {
8404 noi.binderDied();
8405 return;
8406 }
8407 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008408 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008409 }
8410
8411 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8412 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008413 if (DBG) {
8414 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8415 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008416
8417 // If the provider removes the offer and dies immediately afterwards this
8418 // function may be called twice in a row, but the array will no longer contain
8419 // the offer.
8420 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008421 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008422 }
8423
8424 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8425 @NonNull final INetworkOfferCallback callback) {
8426 ensureRunningOnConnectivityServiceThread();
8427 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008428 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008429 }
8430 return null;
8431 }
8432
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008433 /**
8434 * Called when receiving LinkProperties directly from a NetworkAgent.
8435 * Stores into |nai| any data coming from the agent that might also be written to the network's
8436 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8437 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008438 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008439 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008440 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8441 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008442 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008443 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008444 }
8445
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008446 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008447 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008448 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008449
Lorenzo Colittid523d142020-04-01 20:16:30 +09008450 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8451 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8452 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008453 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008454
Suprabh Shukla1e312032023-01-24 03:36:37 -08008455 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008456
8457 // update filtering rules, need to happen after the interface update so netd knows about the
8458 // new interface (the interface name -> index map becomes initialized)
8459 updateVpnFiltering(newLp, oldLp, networkAgent);
8460
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008461 updateMtu(newLp, oldLp);
8462 // TODO - figure out what to do for clat
8463// for (LinkProperties lp : newLp.getStackedLinks()) {
8464// updateMtu(lp, null);
8465// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008466 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008467 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008468 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8469 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008470
Erik Klineb9888902016-04-05 13:30:49 +09008471 updateRoutes(newLp, oldLp, netId);
8472 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008473 // Make sure LinkProperties represents the latest private DNS status.
8474 // This does not need to be done before updateDnses because the
8475 // LinkProperties are not the source of the private DNS configuration.
8476 // updateDnses will fetch the private DNS configuration from DnsManager.
8477 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008478
Chalard Jean5b409c72021-02-04 13:12:59 +09008479 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008480 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008481 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008482 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008483 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008484
8485 updateWakeOnLan(newLp);
8486
Hai Shalome58bdc62021-01-11 18:45:34 -08008487 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8488 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8489 // does, it needs to be merged here.
8490 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8491 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008492
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008493 // TODO - move this check to cover the whole function
8494 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008495 synchronized (networkAgent) {
8496 networkAgent.linkProperties = newLp;
8497 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008498 // Start or stop DNS64 detection and 464xlat according to network state.
8499 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008500 // Notify NSS when relevant events happened. Currently, NSS only cares about
8501 // interface changed to update clat interfaces accounting.
8502 final boolean interfacesChanged = oldLp == null
8503 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8504 if (interfacesChanged) {
8505 notifyIfacesChangedForNetworkStats();
8506 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008507 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8508 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008509 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008510 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008511
8512 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008513 }
8514
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008515 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8516 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8517 }
8518
Hai Shalome58bdc62021-01-11 18:45:34 -08008519 /**
8520 * @param naData captive portal data from NetworkAgent
8521 * @param apiData captive portal data from capport API
8522 */
8523 @Nullable
8524 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8525 CaptivePortalData apiData) {
8526 if (naData == null || apiData == null) {
8527 return naData == null ? apiData : naData;
8528 }
8529 final CaptivePortalData.Builder captivePortalBuilder =
8530 new CaptivePortalData.Builder(naData);
8531
8532 if (apiData.isCaptive()) {
8533 captivePortalBuilder.setCaptive(true);
8534 }
8535 if (apiData.isSessionExtendable()) {
8536 captivePortalBuilder.setSessionExtendable(true);
8537 }
8538 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8539 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8540 // otherwise data would be inconsistent. Prefer the capport API info if present,
8541 // as it can generally be refreshed more often.
8542 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8543 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8544 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8545 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8546 // No source has time / bytes remaining information: surface the newest refresh time
8547 // for other fields
8548 captivePortalBuilder.setRefreshTime(
8549 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8550 }
8551
Hai Shalom7c6ab402021-02-04 19:34:06 -08008552 // Prioritize the user portal URL from the network agent if the source is authenticated.
8553 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8554 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8555 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8556 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008557 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008558 // Prioritize the venue information URL from the network agent if the source is
8559 // authenticated.
8560 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8561 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8562 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8563 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008564 }
8565 return captivePortalBuilder.build();
8566 }
8567
Suprabh Shukla53e16392023-04-26 18:47:36 -07008568 @VisibleForTesting
8569 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008570 // This needs to be kept in sync and backwards compatible with the decoding logic in
8571 // NetdEventListenerService, which is non-mainline code.
8572 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8573 }
8574
Suprabh Shukla75642282023-04-25 23:15:43 -07008575 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8576 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8577 return true;
8578 }
8579 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8580 return true;
8581 }
8582 return false;
8583 }
8584
Suprabh Shukla1e312032023-01-24 03:36:37 -08008585 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008586 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008587 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008588 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008589 return;
8590 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008591
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008592 // Mask/mark of zero will not detect anything interesting.
8593 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008594 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008595 return;
8596 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008597
Suprabh Shukla1e312032023-01-24 03:36:37 -08008598 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008599 try {
8600 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008601 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008602 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008603 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008604 }
8605 } catch (Exception e) {
8606 loge("Exception modifying wakeup packet monitoring: " + e);
8607 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008608 }
8609
Junyu Lai970963e2022-10-25 15:46:47 +08008610 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008611 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008612 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008613 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008614 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008615 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008616 for (final String iface : interfaceDiff.added) {
8617 try {
8618 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008619 mRoutingCoordinatorService.addInterfaceToNetwork(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008620 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008621 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008622 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008623 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008624 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008625 }
Paul Jensenbff73492014-04-28 10:33:11 -04008626 }
8627 }
Chalard Jean9589e722019-11-19 19:03:53 +09008628 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008629 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008630 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008631 wakeupModifyInterface(iface, nai, false);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008632 mRoutingCoordinatorService.removeInterfaceFromNetwork(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008633 } catch (Exception e) {
8634 loge("Exception removing interface: " + e);
8635 }
8636 }
8637 }
8638
Paul Jensene0fd4a82014-08-06 15:51:33 -04008639 /**
8640 * Have netd update routes from oldLp to newLp.
8641 * @return true if routes changed between oldLp and newLp
8642 */
Junyu Lai970963e2022-10-25 15:46:47 +08008643 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8644 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008645 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008646 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8647 new CompareOrUpdateResult<>(
8648 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008649 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008650 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008651
8652 // add routes before removing old in case it helps with continuous connectivity
8653
Chalard Jean9dd11612018-06-04 16:52:49 +09008654 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008655 for (RouteInfo route : routeDiff.added) {
8656 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008657 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008658 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008659 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008660 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008661 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008662 loge("Exception in addRoute for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008663 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008664 }
8665 }
8666 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008667 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008668 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008669 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008670 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008671 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008672 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008673 loge("Exception in addRoute for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008674 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008675 }
8676 }
8677
8678 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008679 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008680 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008681 mRoutingCoordinatorService.removeRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008682 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008683 loge("Exception in removeRoute: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008684 }
8685 }
Tyler Weare4314862019-12-05 14:55:30 -08008686
8687 for (RouteInfo route : routeDiff.updated) {
8688 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8689 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008690 mRoutingCoordinatorService.updateRoute(netId, route);
Tyler Weare4314862019-12-05 14:55:30 -08008691 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008692 loge("Exception in updateRoute: " + e);
Tyler Weare4314862019-12-05 14:55:30 -08008693 }
8694 }
8695 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8696 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008697 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008698
Junyu Lai970963e2022-10-25 15:46:47 +08008699 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8700 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008701 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8702 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008703 }
Erik Klineb9888902016-04-05 13:30:49 +09008704
Erik Kline31b4a9e2018-01-11 21:07:29 +09008705 if (DBG) {
8706 final Collection<InetAddress> dnses = newLp.getDnsServers();
8707 log("Setting DNS servers for network " + netId + " to " + dnses);
8708 }
Erik Klineb9888902016-04-05 13:30:49 +09008709 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008710 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008711 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008712 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008713 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008714 }
Erik Kline54e35c02017-04-07 15:29:29 +09008715 }
8716
Junyu Lai970963e2022-10-25 15:46:47 +08008717 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8718 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008719 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8720 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008721 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8722 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008723
8724 if (!wasFiltering && !needsFiltering) {
8725 // Nothing to do.
8726 return;
8727 }
8728
8729 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8730 // Nothing changed.
8731 return;
8732 }
8733
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008734 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008735 if (ranges == null || ranges.isEmpty()) {
8736 return;
8737 }
8738
Qingxi Libb8da982020-01-17 17:54:27 -08008739 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008740 // TODO: this create a window of opportunity for apps to receive traffic between the time
8741 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008742 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008743 // old rules are being removed.
8744 if (wasFiltering) {
8745 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8746 }
8747 if (needsFiltering) {
8748 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8749 }
8750 }
8751
Valentin Iftime9fa35092019-09-24 13:32:13 +02008752 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008753 if (mWolSupportedInterfaces == null) {
8754 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008755 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008756 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008757 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8758 }
8759
Luke Huangb913c812018-08-24 20:33:16 +08008760 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008761 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008762 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008763 }
8764 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008765 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008766 }
Luke Huangb913c812018-08-24 20:33:16 +08008767 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008768 }
8769
Chalard Jean62edfd82019-12-02 18:39:29 +09008770 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8771 @NonNull final NetworkCapabilities newNc) {
8772 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8773 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008774 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008775 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008776 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008777 } catch (RemoteException | ServiceSpecificException e) {
8778 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008779 }
8780 }
8781 }
8782
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008783 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008784 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008785 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008786 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008787 underlyingNetworks = underlyingNetworksOrDefault(
8788 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008789 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008790 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8791 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008792 // metered if any underlying is metered, or originally declared metered by the agent.
8793 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008794 boolean roaming = false; // roaming if any underlying is roaming
8795 boolean congested = false; // congested if any underlying is congested
8796 boolean suspended = true; // suspended if all underlying are suspended
8797
8798 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008799 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008800 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008801 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008802 for (Network underlyingNetwork : underlyingNetworks) {
8803 final NetworkAgentInfo underlying =
8804 getNetworkAgentInfoForNetwork(underlyingNetwork);
8805 if (underlying == null) continue;
8806
8807 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8808 hadUnderlyingNetworks = true;
8809 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008810 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008811 }
8812
8813 // Merge capabilities of this underlying network. For bandwidth, assume the
8814 // worst case.
8815 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8816 underlyingCaps.getLinkDownstreamBandwidthKbps());
8817 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8818 underlyingCaps.getLinkUpstreamBandwidthKbps());
8819 // If this underlying network is metered, the VPN is metered (it may cost money
8820 // to send packets on this network).
8821 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8822 // If this underlying network is roaming, the VPN is roaming (the billing structure
8823 // is different than the usual, local one).
8824 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8825 // If this underlying network is congested, the VPN is congested (the current
8826 // condition of the network affects the performance of this network).
8827 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8828 // If this network is not suspended, the VPN is not suspended (the VPN
8829 // is able to transfer some data).
8830 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008831 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008832 }
8833 }
8834 if (!hadUnderlyingNetworks) {
8835 // No idea what the underlying networks are; assume reasonable defaults
8836 metered = true;
8837 roaming = false;
8838 congested = false;
8839 suspended = false;
8840 }
8841
Chalard Jean1d420b32022-10-12 16:39:37 +09008842 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008843 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8844 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8845 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8846 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8847 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8848 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008849 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008850 }
8851
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008852 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008853 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8854 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8855 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008856 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008857 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008858 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008859 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008860 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8861 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008862 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008863 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008864 if (nai.everConnected()
8865 && !nai.isVPN()
8866 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008867 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008868 // does not cause any request (that is not a listen) currently matching that agent to
8869 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008870 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008871 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008872 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008873 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008874 }
8875
Paul Jensen53f08952015-06-16 14:27:36 -04008876 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008877 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008878 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008879 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008880 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008881 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008882 }
Chalard Jean254bd162022-08-25 13:04:51 +09008883 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008884 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008885 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008886 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008887 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008888 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008889 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008890 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008891 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008892 }
Chalard Jean254bd162022-08-25 13:04:51 +09008893 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008894 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8895 } else {
8896 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8897 }
lucasline117e2e2019-10-22 18:27:33 +08008898 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008899
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008900 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008901 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8902 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008903 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008904 }
8905
Lorenzo Colittibd079452021-07-02 11:47:57 +09008906 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008907 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008908 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008909 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008910 }
8911
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008912 return newNc;
8913 }
8914
Lorenzo Colitti44840702021-01-11 22:27:57 +09008915 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8916 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8917 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8918 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8919 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8920 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8921 if (prevSuspended != suspended) {
8922 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8923 // onResumed have been removed.
8924 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8925 : ConnectivityManager.CALLBACK_RESUMED);
8926 }
8927 if (prevSuspended != suspended || prevRoaming != roaming) {
8928 // updateNetworkInfo will mix in the suspended info from the capabilities and
8929 // take appropriate action for the network having possibly changed state.
8930 updateNetworkInfo(nai, nai.networkInfo);
8931 }
8932 }
8933
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008934 /**
8935 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8936 *
8937 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8938 * capabilities we manage and store in {@code nai}, such as validated status and captive
8939 * portal status)
8940 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8941 * potentially triggers rematches.
8942 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8943 * change.)
8944 *
8945 * @param oldScore score of the network before any of the changes that prompted us
8946 * to call this function.
8947 * @param nai the network having its capabilities updated.
8948 * @param nc the new network capabilities.
8949 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008950 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008951 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008952 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008953 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008954 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8955 if (null != differences) {
8956 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8957 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008958 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008959 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008960
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008961 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008962 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008963 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008964
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008965 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008966 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8967 // the change we're processing can't affect any requests, it can only affect the listens
8968 // on this network. We might have been called by rematchNetworkAndRequests when a
8969 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008970 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008971 } else {
8972 // If the requestable capabilities have changed or the score changed, we can't have been
8973 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008974 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008975 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008976 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008977 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008978
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008979 final boolean oldMetered = prevNc.isMetered();
8980 final boolean newMetered = newNc.isMetered();
8981 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008982
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008983 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008984 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8985 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008986 }
junyulaif2c67e42018-08-07 19:50:45 +08008987
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008988 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8989 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008990
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008991 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008992 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008993 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008994 }
8995
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008996 // This network might have been underlying another network. Propagate its capabilities.
8997 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008998
Ken Chen5a35cf92023-10-07 07:54:22 +08008999 if (meteredChanged || !newNc.equalsTransportTypes(prevNc)) {
Ken Chen6b134f12023-10-07 07:46:47 +08009000 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(), newNc);
chenbruce7b2f8982020-02-20 14:28:31 +08009001 }
lucaslin53e8a262021-06-08 01:43:59 +08009002
9003 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009004 }
9005
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009006 /** Convenience method to update the capabilities for a given network. */
9007 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009008 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009009 }
9010
Chalard Jean1e4c2182023-10-06 18:45:53 +09009011 // oldConfig is null iff this is the original registration of the local network config
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009012 private void updateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
Chalard Jean1e4c2182023-10-06 18:45:53 +09009013 @Nullable final LocalNetworkConfig oldConfig,
9014 @NonNull final LocalNetworkConfig newConfig) {
9015 if (!nai.isLocalNetwork()) {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009016 Log.wtf(TAG, "Ignoring update of a local network info on non-local network " + nai);
9017 return;
9018 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009019
9020 final LocalNetworkConfig.Builder configBuilder = new LocalNetworkConfig.Builder();
9021 // TODO : apply the diff for multicast routing.
9022 configBuilder.setUpstreamMulticastRoutingConfig(
9023 newConfig.getUpstreamMulticastRoutingConfig());
9024 configBuilder.setDownstreamMulticastRoutingConfig(
9025 newConfig.getDownstreamMulticastRoutingConfig());
9026
9027 final NetworkRequest oldRequest =
9028 (null == oldConfig) ? null : oldConfig.getUpstreamSelector();
9029 final NetworkCapabilities oldCaps =
9030 (null == oldRequest) ? null : oldRequest.networkCapabilities;
9031 final NetworkRequestInfo oldNri =
9032 null == oldRequest ? null : mNetworkRequests.get(oldRequest);
9033 final NetworkAgentInfo oldSatisfier =
9034 null == oldNri ? null : oldNri.getSatisfier();
9035 final NetworkRequest newRequest = newConfig.getUpstreamSelector();
9036 final NetworkCapabilities newCaps =
9037 (null == newRequest) ? null : newRequest.networkCapabilities;
9038 final boolean requestUpdated = !Objects.equals(newCaps, oldCaps);
9039 if (null != oldRequest && requestUpdated) {
9040 handleRemoveNetworkRequest(mNetworkRequests.get(oldRequest));
9041 if (null == newRequest && null != oldSatisfier) {
9042 // If there is an old satisfier, but no new request, then remove the old upstream.
9043 removeLocalNetworkUpstream(nai, oldSatisfier);
9044 nai.localNetworkConfig = configBuilder.build();
9045 return;
9046 }
9047 }
9048 if (null != newRequest && requestUpdated) {
9049 // File the new request if :
9050 // - it has changed (requestUpdated), or
9051 // - it's the first time this local info (null == oldConfig)
9052 // is updated and the request has not been filed yet.
9053 // Requests for local info are always LISTEN_FOR_BEST, because they have at most one
9054 // upstream (the best) but never request it to be brought up.
9055 final NetworkRequest nr = new NetworkRequest(newCaps, ConnectivityManager.TYPE_NONE,
9056 nextNetworkRequestId(), LISTEN_FOR_BEST);
9057 configBuilder.setUpstreamSelector(nr);
9058 final NetworkRequestInfo nri = new NetworkRequestInfo(
9059 nai.creatorUid, nr, null /* messenger */, null /* binder */,
9060 0 /* callbackFlags */, null /* attributionTag */);
9061 if (null != oldSatisfier) {
9062 // Set the old satisfier in the new NRI so that the rematch will see any changes
9063 nri.setSatisfier(oldSatisfier, nr);
9064 }
9065 nai.localNetworkConfig = configBuilder.build();
9066 handleRegisterNetworkRequest(nri);
9067 } else {
9068 configBuilder.setUpstreamSelector(oldRequest);
9069 nai.localNetworkConfig = configBuilder.build();
9070 }
9071
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009072 }
9073
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009074 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00009075 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009076 *
9077 * Ingress interface filtering enforces that all apps under the given network can only receive
9078 * packets from the network's interface (and loopback). This is important for VPNs because
9079 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
9080 * non-VPN interfaces.
9081 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00009082 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009083 * 1. the network is an app VPN (not legacy VPN)
9084 * 2. the VPN does not allow bypass
9085 * 3. the VPN is fully-routed
9086 * 4. the VPN interface is non-null
9087 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09009088 * @see INetd#firewallAddUidInterfaceRules
9089 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009090 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00009091 @Nullable
9092 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009093 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009094 if (nc == null || lp == null) return null;
9095 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009096 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08009097 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009098 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08009099 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00009100 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00009101 && !lp.hasExcludeRoute()) {
9102 return lp.getInterfaceName();
9103 }
9104 return null;
9105 }
9106
9107 /**
9108 * Returns whether we need to set interface filtering rule or not
9109 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00009110 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00009111 String isolationIface) {
9112 // Allow rules are always needed if VPN isolation is enabled.
9113 if (isolationIface != null) return true;
9114
9115 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
9116 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
9117 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09009118 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009119 }
9120
Chiachang Wang28afaff2020-12-10 22:24:47 +08009121 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
9122 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
9123 int index = 0;
9124 for (UidRange range : ranges) {
9125 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
9126 index++;
9127 }
9128 return stableRanges;
9129 }
9130
Chalard Jeane6c95272022-01-25 21:04:21 +09009131 private static UidRangeParcel[] intsToUidRangeStableParcels(
9132 final @NonNull ArraySet<Integer> uids) {
9133 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
9134 int index = 0;
9135 for (int uid : uids) {
9136 stableRanges[index] = new UidRangeParcel(uid, uid);
9137 index++;
9138 }
9139 return stableRanges;
9140 }
9141
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009142 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
9143 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
9144 for (int i = 0; i < ranges.length; i++) {
9145 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
9146 }
9147 return stableRanges;
9148 }
9149
Motomu Utsumi93a22182023-03-16 17:04:21 +09009150 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09009151 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08009152 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
9153 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009154 if (mDeps.isAtLeastU()) {
9155 final Set<Integer> exemptUidSet = new ArraySet<>();
9156 for (final int uid: exemptUids) {
9157 exemptUidSet.add(uid);
9158 }
9159 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
9160 } else {
9161 mNetd.socketDestroy(uidRangeParcels, exemptUids);
9162 }
Ken Chen5e65a852020-12-24 12:59:10 +08009163 } catch (Exception e) {
9164 loge("Exception in socket destroy: ", e);
9165 }
9166 }
9167 }
9168
paulhuaa0743d2021-05-26 21:56:03 +08009169 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009170 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08009171 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
9172 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
9173 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09009174 exemptUids[0] = VPN_UID;
9175 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08009176 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
9177
Motomu Utsumi6345e462023-03-13 13:24:50 +09009178 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009179 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009180 try {
9181 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08009182 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009183 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009184 } else {
paulhu0e79d952021-06-09 16:11:35 +08009185 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009186 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009187 }
9188 } catch (Exception e) {
9189 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
9190 " on netId " + nai.network.netId + ". " + e);
9191 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09009192 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009193 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009194 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009195
lucaslin53e8a262021-06-08 01:43:59 +08009196 private boolean isProxySetOnAnyDefaultNetwork() {
9197 ensureRunningOnConnectivityServiceThread();
9198 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9199 final NetworkAgentInfo nai = nri.getSatisfier();
9200 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9201 return true;
9202 }
9203 }
9204 return false;
9205 }
9206
9207 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9208 NetworkCapabilities newNc) {
9209 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9210 // the proxy might be changed since the default network satisfied by the apps might also
9211 // changed.
9212 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9213 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009214 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9215 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009216 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009217 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9218 mProxyTracker.sendProxyBroadcast();
9219 }
9220 }
9221
Chalard Jeane6c95272022-01-25 21:04:21 +09009222 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9223 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009224 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9225 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009226 if (null == prevRanges) prevRanges = new ArraySet<>();
9227 if (null == newRanges) newRanges = new ArraySet<>();
9228 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9229
9230 prevRanges.removeAll(newRanges);
9231 newRanges.removeAll(prevRangesCopy);
9232
9233 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009234 // When updating the VPN uid routing rules, add the new range first then remove the old
9235 // range. If old range were removed first, there would be a window between the old
9236 // range being removed and the new range being added, during which UIDs contained
9237 // in both ranges are not subject to any VPN routing rules. Adding new range before
9238 // removing old range works because, unlike the filtering rules below, it's possible to
9239 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009240 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9241 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9242 // [1-5] & [1-2],[4-5] == [3]
9243 // Then we can do:
9244 // maybeCloseSockets([3])
9245 // mNetd.networkAddUidRanges([1-2],[4-5])
9246 // mNetd.networkRemoveUidRanges([1-5])
9247 // maybeCloseSockets([3])
9248 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9249 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009250 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009251 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009252 }
9253 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009254 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009255 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009256 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9257 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009258 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9259 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009260 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009261 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009262 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9263 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9264 // were added first and then newRanges got removed later, there would be only one uid
9265 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9266 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9267 // Note that this is in contrast with the (more robust) update of VPN routing rules
9268 // above, where the addition of new ranges happens before the removal of old ranges.
9269 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9270 // to be removed will never overlap with the new range to be added.
9271 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009272 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9273 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009274 }
9275 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009276 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009277 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009278 } catch (Exception e) {
9279 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009280 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009281 }
9282 }
9283
Chalard Jeande665262022-02-25 16:12:12 +09009284 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009285 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9286 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009287 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9288 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009289 if (prevEmpty && newEmpty) return;
9290
9291 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009292 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009293 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009294 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009295
9296 if (prevUids.equals(newUids)) return;
9297
9298 // This implementation is very simple and vastly faster for sets of Integers than
9299 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9300 // a key computed from the value and has storage for that.
9301 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9302 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9303 toRemove.removeAll(newUids);
9304 toAdd.removeAll(prevUids);
9305
9306 try {
9307 if (!toAdd.isEmpty()) {
9308 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9309 nai.network.netId,
9310 intsToUidRangeStableParcels(toAdd),
9311 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9312 }
9313 if (!toRemove.isEmpty()) {
9314 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9315 nai.network.netId,
9316 intsToUidRangeStableParcels(toRemove),
9317 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9318 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009319 } catch (ServiceSpecificException e) {
9320 // Has the interface disappeared since the network was built ?
9321 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009322 } catch (RemoteException e) {
9323 // Netd died. This usually causes a runtime restart anyway.
9324 }
9325 }
9326
Junyu Lai2ed7d412022-10-07 16:52:21 +08009327 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9328 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009329 ensureRunningOnConnectivityServiceThread();
9330
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009331 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009332 // Ignore updates for disconnected networks
9333 return;
9334 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009335 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009336 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009337 + "; created=" + nai.getCreatedTime()
9338 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009339 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009340 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9341 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009342 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009343 }
9344
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009345 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9346 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009347 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009348 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009349 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009350 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9351 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9352 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009353 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9354 // need to be sent as a separate extra.
9355 final NetworkRequest req = nri.isMultilayerRequest()
9356 ? nri.getActiveRequest()
9357 // Non-multilayer listen requests do not have an active request
9358 : nri.mRequests.get(0);
9359 if (req == null) {
9360 Log.wtf(TAG, "No request in NRI " + nri);
9361 }
9362 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009363 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009364 sendIntent(nri.mPendingIntent, intent);
9365 }
9366 // else not handled
9367 }
9368
Michael Groover73f69482023-01-27 11:01:25 -06009369 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9370 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009371 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9372 mPendingIntentWakeLock.acquire();
9373 try {
9374 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009375 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009376 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009377 // Explicitly disallow the receiver from starting activities, to prevent apps from
9378 // utilizing the PendingIntent as a backdoor to do this.
9379 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9380 }
9381 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9382 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009383 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009384 } catch (PendingIntent.CanceledException e) {
9385 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9386 mPendingIntentWakeLock.release();
9387 releasePendingNetworkRequest(pendingIntent);
9388 }
9389 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9390 }
9391
9392 @Override
9393 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9394 String resultData, Bundle resultExtras) {
9395 if (DBG) log("Finished sending " + pendingIntent);
9396 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009397 // Release with a delay so the receiving client has an opportunity to put in its
9398 // own request.
9399 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009400 }
9401
Chalard Jean46bfbf02022-02-02 00:56:25 +09009402 // networkAgent is only allowed to be null if notificationType is
9403 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9404 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009405 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009406 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009407 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009408 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009409 // Default request has no msgr. Also prevents callbacks from being invoked for
9410 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9411 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9412 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009413 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09009414 final Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009415 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009416 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009417 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009418 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009419 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009420 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9421 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009422 }
Roshan Pius951c0032020-12-22 15:10:42 -08009423 final boolean includeLocationSensitiveInfo =
9424 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009425 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009426 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009427 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009428 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009429 networkCapabilitiesRestrictedForCallerPermissions(
9430 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9431 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009432 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009433 nri.mCallingAttributionTag);
9434 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009435 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9436 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08009437 // For this notification, arg1 contains the blocked status.
9438 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009439 break;
9440 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009441 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009442 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009443 break;
9444 }
9445 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009446 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009447 final NetworkCapabilities netCap =
9448 networkCapabilitiesRestrictedForCallerPermissions(
9449 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9450 putParcelable(
9451 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009452 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009453 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009454 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009455 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009456 break;
9457 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009458 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009459 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9460 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009461 break;
9462 }
junyulaif2c67e42018-08-07 19:50:45 +08009463 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009464 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009465 msg.arg1 = arg1;
9466 break;
9467 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009468 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009469 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009470 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009471 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009472 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009473 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009474 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009475 }
James Mattis45d81842021-01-10 14:24:24 -08009476 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009477 } catch (RemoteException e) {
9478 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009479 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009480 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009481 }
9482
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009483 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9484 bundle.putParcelable(t.getClass().getSimpleName(), t);
9485 }
9486
Chalard Jean0702f982021-09-16 21:50:07 +09009487 /**
9488 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9489 *
9490 * When a request should be assigned to a new network, it is normally lingered to give
9491 * time for apps to gracefully migrate their connections. When both networks are on the same
9492 * radio, but that radio can't do time-sharing efficiently, this may end up being
9493 * counter-productive because any traffic on the old network may drastically reduce the
9494 * performance of the new network.
9495 * The stack supports a configuration to let modem vendors state that their radio can't
9496 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9497 * from one cell network to another can't be done gracefully.
9498 *
9499 * @param oldNai the old network serving the request
9500 * @param newNai the new network serving the request
9501 * @return whether the switch can be graceful
9502 */
9503 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9504 @NonNull final NetworkAgentInfo newSatisfier) {
9505 if (mCellularRadioTimesharingCapable) return true;
9506 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9507 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9508 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9509 }
9510
Paul Jensenaf94b982014-09-30 15:37:41 -04009511 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009512 if (nai.numRequestNetworkRequests() != 0) {
9513 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9514 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009515 // Ignore listening and track default requests.
9516 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009517 loge("Dead network still had at least " + nr);
9518 break;
9519 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009520 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009521 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009522 }
9523
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009524 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9525 if (oldNetwork == null) {
9526 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9527 return;
9528 }
Chalard Jean49707572019-12-10 21:07:02 +09009529 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009530
9531 // If we get here it means that the last linger timeout for this network expired. So there
9532 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009533 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009534
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009535 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009536 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009537 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009538 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009539 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009540 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009541 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009542 }
9543
James Mattise3ef1912020-12-20 11:09:58 -08009544 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9545 boolean isDefaultChanged = false;
9546 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9547 final NetworkReassignment.RequestReassignment reassignment =
9548 changes.getReassignment(defaultRequestInfo);
9549 if (null == reassignment) {
9550 continue;
9551 }
9552 // reassignment only contains those instances where the satisfying network changed.
9553 isDefaultChanged = true;
9554 // Notify system services of the new default.
9555 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9556 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009557
James Mattise3ef1912020-12-20 11:09:58 -08009558 if (isDefaultChanged) {
9559 // Hold a wakelock for a short time to help apps in migrating to a new default.
9560 scheduleReleaseNetworkTransitionWakelock();
9561 }
9562 }
9563
Aaron Huang9fe47be2021-06-08 13:11:45 +08009564 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9565 if (null == oldDefaultNetwork) return;
9566 // The network stopped being the default. If it was using a PAC proxy, then the
9567 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9568 // to the local proxy server, which would forward them over the newly default network.
9569 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9570 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9571 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9572 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9573 }
9574
James Mattise3ef1912020-12-20 11:09:58 -08009575 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9576 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9577 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9578 if (DBG) {
9579 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9580 }
Chalard Jean8e382112019-12-03 20:45:30 +09009581
James Mattisd31bdfa2020-12-23 16:37:26 -08009582 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9583 if (newDefaultNetwork != null) {
9584 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009585 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009586
James Mattisd31bdfa2020-12-23 16:37:26 -08009587 // Set an app level managed default and return since further processing only applies to the
9588 // default network.
9589 if (mDefaultRequest != nri) {
9590 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9591 return;
9592 }
9593
9594 makeDefaultNetwork(newDefaultNetwork);
9595
James Mattise3ef1912020-12-20 11:09:58 -08009596 if (oldDefaultNetwork != null) {
9597 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9598 }
9599 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009600 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009601 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009602 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009603 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009604 updateTcpBufferSizes(null != newDefaultNetwork
9605 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009606 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009607 }
9608
James Mattisd31bdfa2020-12-23 16:37:26 -08009609 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9610 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9611 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9612 try {
9613 if (VDBG) {
9614 log("Setting default network for " + nri
9615 + " using UIDs " + nri.getUids()
9616 + " with old network " + (oldDefaultNetwork != null
9617 ? oldDefaultNetwork.network().getNetId() : "null")
9618 + " and new network " + (newDefaultNetwork != null
9619 ? newDefaultNetwork.network().getNetId() : "null"));
9620 }
9621 if (nri.getUids().isEmpty()) {
9622 throw new IllegalStateException("makeDefaultForApps called without specifying"
9623 + " any applications to set as the default." + nri);
9624 }
9625 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009626 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009627 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009628 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009629 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009630 }
9631 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009632 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009633 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009634 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009635 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009636 }
9637 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009638 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009639 }
9640 }
9641
Junyu Lai35665cc2022-12-19 17:37:48 +08009642 /**
9643 * Collect restricted uid ranges for the given network and UserHandle, these uids
9644 * are not restricted for matched enterprise networks but being restricted for non-matched
9645 * enterprise networks and non-enterprise networks.
9646 */
9647 @NonNull
9648 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9649 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9650 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9651 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9652 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9653
9654 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9655 // The NC is built from a `ProfileNetworkPreference` which has only one
9656 // enterprise ID, so it's guaranteed to have exactly one.
9657 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9658 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9659 continue;
9660 }
9661 }
9662
9663 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9664 pref.capabilities.getUidRanges())) {
9665 throw new IllegalArgumentException(
9666 "Overlapping uid range in preference: " + pref);
9667 }
9668 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9669 }
9670 return restrictedUidRanges;
9671 }
9672
9673 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009674 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +09009675 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009676
Junyu Lai35665cc2022-12-19 17:37:48 +08009677 ensureRunningOnConnectivityServiceThread();
9678 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9679 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9680 .getUserHandles(true /* excludeDying */);
9681 if (users.isEmpty()) {
9682 throw new IllegalStateException("No user is available");
9683 }
9684
9685 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9686 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9687 for (final UserHandle user : users) {
9688 final ArraySet<UidRange> restrictedUidRanges =
9689 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9690 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9691 UidRange.createForUser(user), restrictedUidRanges));
9692 }
9693
9694 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9695 configs.add(new NativeUidRangeConfig(
9696 nai.network.netId, rangesParcel, 0 /* subPriority */));
9697 }
9698
9699 // The netd API replaces the previous configs with the current configs.
9700 // Thus, for network disconnection or preference removal, no need to
9701 // unset previous config. Instead, collecting all currently needed
9702 // configs and issue to netd.
9703 try {
9704 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9705 } catch (ServiceSpecificException e) {
9706 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009707 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009708 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009709 // Netd died. This will cause a runtime restart anyway.
9710 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009711 }
9712 }
9713
James Mattisd31bdfa2020-12-23 16:37:26 -08009714 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9715 try {
9716 if (null != newDefaultNetwork) {
9717 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9718 } else {
9719 mNetd.networkClearDefault();
9720 }
9721 } catch (RemoteException | ServiceSpecificException e) {
9722 loge("Exception setting default network :" + e);
9723 }
9724 }
9725
Chalard Jean05cbe972019-12-09 11:50:38 +09009726 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009727 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009728 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009729 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009730 processNewlySatisfiedListenRequests(nai);
9731 }
9732
9733 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009734 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9735 if (nri.isMultilayerRequest()) {
9736 continue;
9737 }
9738 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009739 if (!nr.isListen()) continue;
9740 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009741 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009742 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9743 }
9744 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009745 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009746
Chalard Jeancd397a22019-11-22 22:33:33 +09009747 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009748 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9749 if (nri.isMultilayerRequest()) {
9750 continue;
9751 }
9752 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009753 if (!nr.isListen()) continue;
9754 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9755 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009756 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009757 }
9758 }
9759 }
9760
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009761 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009762 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009763 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009764 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009765 @Nullable public final NetworkRequest mOldNetworkRequest;
9766 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009767 @Nullable public final NetworkAgentInfo mOldNetwork;
9768 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009769 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009770 @Nullable final NetworkRequest oldNetworkRequest,
9771 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009772 @Nullable final NetworkAgentInfo oldNetwork,
9773 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009774 mNetworkRequestInfo = networkRequestInfo;
9775 mOldNetworkRequest = oldNetworkRequest;
9776 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009777 mOldNetwork = oldNetwork;
9778 mNewNetwork = newNetwork;
9779 }
Chalard Jean49707572019-12-10 21:07:02 +09009780
9781 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009782 final NetworkRequest requestToShow = null != mNewNetworkRequest
9783 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9784 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009785 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9786 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009787 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009788 }
9789
Chalard Jean46a62372019-12-10 21:25:24 +09009790 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009791
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009792 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009793 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009794 }
9795
9796 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009797 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009798 // The code is never supposed to add two reassignments of the same request. Make
9799 // sure this stays true, but without imposing this expensive check on all
9800 // reassignments on all user devices.
9801 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009802 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009803 throw new IllegalStateException("Trying to reassign ["
9804 + reassignment + "] but already have ["
9805 + existing + "]");
9806 }
9807 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009808 }
Chalard Jean46a62372019-12-10 21:25:24 +09009809 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009810 }
9811
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009812 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009813 // the passed request.
9814 @Nullable
9815 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009816 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009817 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009818 }
9819 return null;
9820 }
Chalard Jean49707572019-12-10 21:07:02 +09009821
9822 public String toString() {
9823 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9824 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009825 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009826 for (final RequestReassignment rr : getRequestReassignments()) {
9827 sj.add(rr.toString());
9828 }
9829 return sj.toString();
9830 }
9831
9832 public String debugString() {
9833 final StringBuilder sb = new StringBuilder();
9834 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009835 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009836 for (final RequestReassignment rr : getRequestReassignments()) {
9837 sb.append("\n ").append(rr);
9838 }
9839 return sb.append("\n").toString();
9840 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009841 }
9842
Chalard Jean24344d72019-12-04 13:32:31 +09009843 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009844 @Nullable final NetworkRequest previousRequest,
9845 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009846 @Nullable final NetworkAgentInfo previousSatisfier,
9847 @Nullable final NetworkAgentInfo newSatisfier,
9848 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009849 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009850 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009851 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009852 if (VDBG || DDBG) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09009853 log(" accepting network in place of " + previousSatisfier.toShortString()
9854 + " for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009855 }
James Mattisa076c532020-12-02 14:12:41 -08009856 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009857 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009858 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009859 // If this network switch can't be supported gracefully, the request is not
9860 // lingered. This allows letting go of the network sooner to reclaim some
9861 // performance on the new network, since the radio can't do both at the same
9862 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009863 //
9864 // Also don't linger the request if the old network has been destroyed.
9865 // A destroyed network does not provide actual network connectivity, so
9866 // lingering it is not useful. In particular this ensures that a destroyed
9867 // network is outscored by its replacement,
9868 // then it is torn down immediately instead of being lingered, and any apps that
9869 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009870 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9871 }
Chalard Jean24344d72019-12-04 13:32:31 +09009872 } else {
Chalard Jean1e4c2182023-10-06 18:45:53 +09009873 if (VDBG || DDBG) log(" accepting network in place of null for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009874 }
junyulai0ac374f2020-12-14 18:41:52 +08009875
9876 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9877 // and immediately satisfies a request then remove the timer. This will happen for
9878 // all networks except in the case of an underlying network for a VCN.
9879 if (newSatisfier.isNascent()) {
9880 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009881 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009882 }
9883
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009884 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009885 newSatisfier.unlingerRequest(newRequest.requestId);
9886 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009887 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009888 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009889 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009890 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009891 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009892 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009893 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009894 }
James Mattisa076c532020-12-02 14:12:41 -08009895 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009896 }
James Mattisa076c532020-12-02 14:12:41 -08009897 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009898 }
9899
James Mattisa076c532020-12-02 14:12:41 -08009900 /**
9901 * This function is triggered when something can affect what network should satisfy what
9902 * request, and it computes the network reassignment from the passed collection of requests to
9903 * network match to the one that the system should now have. That data is encoded in an
9904 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9905 * satisfier.
9906 *
9907 * After the reassignment is computed, it is applied to the state objects.
9908 *
9909 * @param networkRequests the nri objects to evaluate for possible network reassignment
9910 * @return NetworkReassignment listing of proposed network assignment changes
9911 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009912 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009913 private NetworkReassignment computeNetworkReassignment(
9914 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009915 final NetworkReassignment changes = new NetworkReassignment();
9916
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009917 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009918 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009919 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009920 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009921 }
Chalard Jean857a1712019-12-10 21:08:07 +09009922
James Mattisa076c532020-12-02 14:12:41 -08009923 for (final NetworkRequestInfo nri : networkRequests) {
9924 // Non-multilayer listen requests can be ignored.
9925 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9926 continue;
9927 }
9928 NetworkAgentInfo bestNetwork = null;
9929 NetworkRequest bestRequest = null;
9930 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009931 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009932 // Stop evaluating as the highest possible priority request is satisfied.
9933 if (null != bestNetwork) {
9934 bestRequest = req;
9935 break;
9936 }
9937 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009938 if (null == bestNetwork && isDefaultBlocked(nri)) {
9939 // Remove default networking if disallowed for managed default requests.
9940 bestNetwork = mNoServiceNetwork;
9941 }
9942 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009943 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009944 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009945 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009946 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009947 }
9948 return changes;
9949 }
9950
James Mattisa076c532020-12-02 14:12:41 -08009951 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9952 return new HashSet<>(mNetworkRequests.values());
9953 }
9954
Paul Jensenc88b39b2015-06-16 14:27:36 -04009955 /**
James Mattisa076c532020-12-02 14:12:41 -08009956 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009957 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009958 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009959 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009960 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9961 }
9962
9963 /**
9964 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9965 * being disconnected.
9966 */
9967 private void rematchNetworksAndRequests(
9968 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9969 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009970 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009971 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009972 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009973 final long computed = SystemClock.elapsedRealtime();
9974 applyNetworkReassignment(changes, start);
9975 final long applied = SystemClock.elapsedRealtime();
9976 issueNetworkNeeds();
9977 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009978 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009979 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9980 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009981 log(changes.debugString());
9982 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009983 // Shorter form, only one line of log
9984 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9985 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009986 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009987 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009988
Chalard Jean1e4c2182023-10-06 18:45:53 +09009989 private boolean hasSameInterfaceName(@Nullable final NetworkAgentInfo nai1,
9990 @Nullable final NetworkAgentInfo nai2) {
9991 if (null == nai1) return null == nai2;
9992 if (null == nai2) return false;
9993 return nai1.linkProperties.getInterfaceName()
9994 .equals(nai2.linkProperties.getInterfaceName());
9995 }
9996
Chalard Jeand7f762d2019-12-10 19:01:29 +09009997 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009998 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009999 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +090010000
10001 // Since most of the time there are only 0 or 1 background networks, it would probably
10002 // be more efficient to just use an ArrayList here. TODO : measure performance
10003 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
10004 for (final NetworkAgentInfo nai : nais) {
10005 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
10006 }
10007
Chalard Jeand7f762d2019-12-10 19:01:29 +090010008 // First, update the lists of satisfied requests in the network agents. This is necessary
10009 // because some code later depends on this state to be correct, most prominently computing
10010 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +090010011 for (final NetworkReassignment.RequestReassignment event :
10012 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010013 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
10014 event.mOldNetworkRequest, event.mNewNetworkRequest,
10015 event.mOldNetwork, event.mNewNetwork,
10016 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +090010017 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010018
James Mattise3ef1912020-12-20 11:09:58 -080010019 // Process default network changes if applicable.
10020 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010021
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010022 // Notify requested networks are available after the default net is switched, but
10023 // before LegacyTypeTracker sends legacy broadcasts
10024 for (final NetworkReassignment.RequestReassignment event :
10025 changes.getRequestReassignments()) {
10026 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -080010027 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010028 } else {
James Mattisa076c532020-12-02 14:12:41 -080010029 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010030 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010031 }
10032 }
10033
junyulai0ac374f2020-12-14 18:41:52 +080010034 // Update the inactivity state before processing listen callbacks, because the background
10035 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010036 // just yet though, because they have to be sent after the listens are processed to keep
10037 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +080010038 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +090010039 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +080010040 // Rematching may have altered the inactivity state of some networks, so update all
10041 // inactivity timers. updateInactivityState reads the state from the network agent
10042 // and does nothing if the state has not changed : the source of truth is controlled
10043 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
10044 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +080010045 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +080010046 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010047 }
10048 }
10049
Chalard Jeanb10ab412019-12-11 14:12:30 +090010050 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010051 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010052 // Process listen requests and update capabilities if the background state has
10053 // changed for this network. For consistency with previous behavior, send onLost
10054 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +090010055 processNewlyLostListenRequests(nai);
10056 if (oldBackground != nai.isBackgroundNetwork()) {
10057 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010058 }
Chalard Jeanb10ab412019-12-11 14:12:30 +090010059 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010060 }
10061
junyulai0ac374f2020-12-14 18:41:52 +080010062 for (final NetworkAgentInfo nai : inactiveNetworks) {
10063 // For nascent networks, if connecting with no foreground request, skip broadcasting
10064 // LOSING for backward compatibility. This is typical when mobile data connected while
10065 // wifi connected with mobile data always-on enabled.
10066 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010067 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010068 }
10069
Chalard Jean1e4c2182023-10-06 18:45:53 +090010070 // Update forwarding rules for the upstreams of local networks. Do this after sending
10071 // onAvailable so that clients understand what network this is about.
10072 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
10073 if (!nai.isLocalNetwork()) continue;
10074 final NetworkRequest nr = nai.localNetworkConfig.getUpstreamSelector();
10075 if (null == nr) continue; // No upstream for this local network
10076 final NetworkRequestInfo nri = mNetworkRequests.get(nr);
10077 final NetworkReassignment.RequestReassignment change = changes.getReassignment(nri);
10078 if (null == change) continue; // No change in upstreams for this network
10079 final String fromIface = nai.linkProperties.getInterfaceName();
10080 if (!hasSameInterfaceName(change.mOldNetwork, change.mNewNetwork)
10081 || change.mOldNetwork.isDestroyed()) {
10082 // There can be a change with the same interface name if the new network is the
10083 // replacement for the old network that was unregisteredAfterReplacement.
10084 try {
10085 if (null != change.mOldNetwork) {
10086 mRoutingCoordinatorService.removeInterfaceForward(fromIface,
10087 change.mOldNetwork.linkProperties.getInterfaceName());
10088 }
10089 // If the new upstream is already destroyed, there is no point in setting up
10090 // a forward (in fact, it might forward to the interface for some new network !)
10091 // Later when the upstream disconnects CS will try to remove the forward, which
10092 // is ignored with a benign log by RoutingCoordinatorService.
10093 if (null != change.mNewNetwork && !change.mNewNetwork.isDestroyed()) {
10094 mRoutingCoordinatorService.addInterfaceForward(fromIface,
10095 change.mNewNetwork.linkProperties.getInterfaceName());
10096 }
10097 } catch (final RemoteException e) {
10098 loge("Can't update forwarding rules", e);
10099 }
10100 }
10101 }
10102
James Mattise3ef1912020-12-20 11:09:58 -080010103 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +090010104
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010105 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +000010106 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010107 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +080010108 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010109 // This network has active linger timers and no requests, but is not
10110 // lingering. Linger it.
10111 //
10112 // One way (the only way?) this can happen if this network is unvalidated
10113 // and became unneeded due to another network improving its score to the
10114 // point where this network will no longer be able to satisfy any requests
10115 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +080010116 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010117 notifyNetworkLosing(nai, now);
10118 }
Chalard Jean0a8afda2019-11-07 19:05:18 +090010119 } else {
Chalard Jean49707572019-12-10 21:07:02 +090010120 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +090010121 teardownUnneededNetwork(nai);
10122 }
10123 }
Paul Jensen05e85ee2014-09-11 11:00:39 -040010124 }
10125 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010126
Chalard Jean62edfd82019-12-02 18:39:29 +090010127 /**
10128 * Apply a change in background state resulting from rematching networks with requests.
10129 *
10130 * During rematch, a network may change background states by starting to satisfy or stopping
10131 * to satisfy a foreground request. Listens don't count for this. When a network changes
10132 * background states, its capabilities need to be updated and callbacks fired for the
10133 * capability change.
10134 *
10135 * @param nai The network that changed background states
10136 */
10137 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
10138 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
10139 if (Objects.equals(nai.networkCapabilities, newNc)) return;
10140 updateNetworkPermissions(nai, newNc);
10141 nai.getAndSetNetworkCapabilities(newNc);
10142 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
10143 }
10144
Chalard Jeanf0344532019-11-19 19:23:38 +090010145 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -080010146 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010147 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +090010148 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
10149 changes.getReassignment(mDefaultRequest);
10150 final NetworkAgentInfo oldDefaultNetwork =
10151 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
10152 final NetworkAgentInfo newDefaultNetwork =
10153 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -080010154
Chalard Jean5b409c72021-02-04 13:12:59 +090010155 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010156 // Maintain the illusion : since the legacy API only understands one network at a time,
10157 // if the default network changed, apps should see a disconnected broadcast for the
10158 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +090010159 if (oldDefaultNetwork != null) {
10160 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
10161 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010162 }
Chalard Jean5b409c72021-02-04 13:12:59 +090010163 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010164 // The new default network can be newly null if and only if the old default
10165 // network doesn't satisfy the default request any more because it lost a
10166 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +090010167 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -080010168 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +090010169 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010170 }
10171 }
10172
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010173 // Now that all the callbacks have been sent, send the legacy network broadcasts
10174 // as needed. This is necessary so that legacy requests correctly bind dns
10175 // requests to this network. The legacy users are listening for this broadcast
10176 // and will generally do a dns request so they can ensureRouteToHost and if
10177 // they do that before the callbacks happen they'll use the default network.
10178 //
10179 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
10180 // callbacks, but if apps can receive the broadcast before the callback, they still might
10181 // have an inconsistent view of networking.
10182 //
10183 // This *does* introduce a race where if the user uses the new api
10184 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
10185 // they may get old info. Reverse this after the old startUsing api is removed.
10186 // This is on top of the multiple intent sequencing referenced in the todo above.
10187 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +090010188 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010189 addNetworkToLegacyTypeTracker(nai);
10190 }
The Android Open Source Project28527d22009-03-03 19:31:44 -080010191 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010192 }
10193
Chalard Jean0354d8c2021-01-12 10:58:56 +090010194 private void issueNetworkNeeds() {
10195 ensureRunningOnConnectivityServiceThread();
10196 for (final NetworkOfferInfo noi : mNetworkOffers) {
10197 issueNetworkNeeds(noi);
10198 }
10199 }
10200
10201 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
10202 ensureRunningOnConnectivityServiceThread();
10203 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10204 informOffer(nri, noi.offer, mNetworkRanker);
10205 }
10206 }
10207
10208 /**
10209 * Inform a NetworkOffer about any new situation of a request.
10210 *
10211 * This function handles updates to offers. A number of events may happen that require
10212 * updating the registrant for this offer about the situation :
10213 * • The offer itself was updated. This may lead the offer to no longer being able
10214 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
10215 * or conversely being strengthened enough to beat the satisfier (and therefore
10216 * start being needed)
10217 * • The network satisfying a request changed (including cases where the request
10218 * starts or stops being satisfied). The new network may be a stronger or weaker
10219 * match than the old one, possibly affecting whether the offer is needed.
10220 * • The network satisfying a request updated their score. This may lead the offer
10221 * to no longer be able to beat it if the current satisfier got better, or
10222 * conversely start being a good choice if the current satisfier got weaker.
10223 *
10224 * @param nri The request
10225 * @param offer The offer. This may be an updated offer.
10226 */
10227 private static void informOffer(@NonNull NetworkRequestInfo nri,
10228 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
10229 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
10230 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090010231
10232 // Multi-layer requests have a currently active request, the one being satisfied.
10233 // Since the system will try to bring up a better network than is currently satisfying
10234 // the request, NetworkProviders need to be told the offers matching the requests *above*
10235 // the currently satisfied one are needed, that the ones *below* the satisfied one are
10236 // not needed, and the offer is needed for the active request iff the offer can beat
10237 // the satisfier.
10238 // For non-multilayer requests, the logic above gracefully degenerates to only the
10239 // last case.
10240 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10241 // providers that the offer is needed for this request, until the active request is found.
10242 // In a second phase, deal with the currently active request. In a third phase, inform
10243 // the providers that offer is unneeded for the remaining requests.
10244
10245 // First phase : inform providers of all requests above the active request.
10246 int i;
10247 for (i = 0; nri.mRequests.size() > i; ++i) {
10248 final NetworkRequest request = nri.mRequests.get(i);
10249 if (activeRequest == request) break; // Found the active request : go to phase 2
10250 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10251 // Since this request is higher-priority than the one currently satisfied, if the
10252 // offer can satisfy it, the provider should try and bring up the network for sure ;
10253 // no need to even ask the ranker – an offer that can satisfy is always better than
10254 // no network. Hence tell the provider so unless it already knew.
10255 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10256 offer.onNetworkNeeded(request);
10257 }
10258 }
10259
10260 // Second phase : deal with the active request (if any)
10261 if (null != activeRequest && activeRequest.isRequest()) {
10262 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010263 // If an offer can satisfy the request, it is considered needed if it is currently
10264 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010265 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010266 && satisfier.factorySerialNumber == offer.providerId
10267 && activeRequest.canBeSatisfiedBy(offer.caps);
10268 final boolean newNeeded = currentlyServing
10269 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010270 if (newNeeded != oldNeeded) {
10271 if (newNeeded) {
10272 offer.onNetworkNeeded(activeRequest);
10273 } else {
10274 // The offer used to be able to beat the satisfier. Now it can't.
10275 offer.onNetworkUnneeded(activeRequest);
10276 }
10277 }
10278 }
10279
10280 // Third phase : inform the providers that the offer isn't needed for any request
10281 // below the active one.
10282 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10283 final NetworkRequest request = nri.mRequests.get(i);
10284 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10285 // Since this request is lower-priority than the one currently satisfied, if the
10286 // offer can satisfy it, the provider should not try and bring up the network.
10287 // Hence tell the provider so unless it already knew.
10288 if (offer.neededFor(request)) {
10289 offer.onNetworkUnneeded(request);
10290 }
10291 }
10292 }
10293
Chalard Jean61c79252019-11-07 23:07:32 +090010294 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10295 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10296 NetworkRequest nr = nai.requestAt(i);
10297 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10298 // legacy type tracker filters out repeat adds
10299 mLegacyTypeTracker.add(nr.legacyType, nai);
10300 }
10301 }
10302
10303 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010304 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010305 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10306 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10307 if (nai.isVPN()) {
10308 mLegacyTypeTracker.add(TYPE_VPN, nai);
10309 }
10310 }
10311
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010312 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010313 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010314 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010315 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010316 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010317 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010318
Chalard Jean254bd162022-08-25 13:04:51 +090010319 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010320 // Don't repeat publish.
10321 if (newInetCondition == mDefaultInetConditionPublished) return;
10322
10323 mDefaultInetConditionPublished = newInetCondition;
10324 sendInetConditionBroadcast(nai.networkInfo);
10325 }
10326
Chalard Jeand61375d2020-01-14 22:46:36 +090010327 @NonNull
10328 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10329 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010330 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010331 final boolean suspended =
10332 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10333 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10334 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10335 // state. This is because the network could have been suspended before connecting,
10336 // or it could be disconnecting while being suspended, and in both these cases
10337 // the state should not be overridden. Note that the only detailed state that
10338 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10339 // worry about multiple different substates of CONNECTED.
10340 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10341 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010342 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10343 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10344 // network agent is created, then goes to suspended, then goes out of suspended without
10345 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010346 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010347 ? NetworkInfo.DetailedState.CONNECTED
10348 : NetworkInfo.DetailedState.CONNECTING,
10349 info.getReason(),
10350 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010351 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010352 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010353 return newInfo;
10354 }
10355
10356 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10357 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10358
Erik Kline99f301b2017-02-15 19:59:17 +090010359 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010360 NetworkInfo oldInfo = null;
10361 synchronized (networkAgent) {
10362 oldInfo = networkAgent.networkInfo;
10363 networkAgent.networkInfo = newInfo;
10364 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010365
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010366 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010367 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10368 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010369 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010370
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010371 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010372 // A network that has just connected has zero requests and is thus a foreground network.
10373 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10374
Luke Huangfdd11f82019-04-09 18:41:49 +080010375 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010376
10377 networkAgent.setCreated();
10378
10379 // If the network is created immediately on register, then apply the LinkProperties now.
10380 // Otherwise, this is done further down when the network goes into connected state.
10381 // Applying the LinkProperties means that the network is ready to carry traffic -
10382 // interfaces and routing rules have been added, DNS servers programmed, etc.
10383 // For VPNs, this must be done before the capabilities are updated, because as soon as
10384 // that happens, UIDs are routed to the network.
10385 if (shouldCreateNetworksImmediately()) {
10386 applyInitialLinkProperties(networkAgent);
10387 }
10388
10389 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10390 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010391 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010392 // Initialize the network's capabilities to their starting values according to the
10393 // underlying networks. This ensures that the capabilities are correct before
10394 // anything happens to the network.
10395 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010396 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010397 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010398 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010399 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010400 }
10401
Chalard Jean254bd162022-08-25 13:04:51 +090010402 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10403 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010404
lucaslin45e639b2019-04-03 17:09:28 +080010405 // NetworkCapabilities need to be set before sending the private DNS config to
10406 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010407 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10408
Erik Kline9a62f012018-03-21 07:18:33 -070010409 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010410 if (!shouldCreateNetworksImmediately()) {
10411 applyInitialLinkProperties(networkAgent);
10412 } else {
10413 // The network was created when the agent registered, and the LinkProperties are
10414 // already up-to-date. However, updateLinkProperties also makes some changes only
10415 // when the network connects. Apply those changes here. On T and below these are
10416 // handled by the applyInitialLinkProperties call just above.
10417 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10418 // If something depends on both LinkProperties and connected state, it should be in
10419 // this method as well.
10420 networkAgent.clatd.update();
10421 updateProxy(networkAgent.linkProperties, null);
10422 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010423
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010424 // If a rate limit has been configured and is applicable to this network (network
10425 // provides internet connectivity), apply it. The tc police filter cannot be attached
10426 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
Chalard Jean2fb66f12023-08-25 12:50:37 +090010427 // updateInterfaces -> RoutingCoordinatorManager#addInterfaceToNetwork
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010428 // Note: in case of a system server crash, the NetworkController constructor in netd
10429 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10430 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10431 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10432 mIngressRateLimit);
10433 }
10434
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010435 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10436 // command must be sent after updating LinkProperties to maximize chances of
10437 // NetworkMonitor seeing the correct LinkProperties when starting.
10438 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010439 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010440 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010441 }
Chalard Jeand4900722022-02-06 12:25:38 +090010442 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10443 params.networkAgentConfig = networkAgent.networkAgentConfig;
10444 params.networkCapabilities = networkAgent.networkCapabilities;
10445 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10446 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010447 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10448 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10449 // call that would cause a Log.wtf to be emitted from the system_server process, and
10450 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10451 // process to check the interface version, just use an SDK check. NetworkStack will
10452 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010453 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010454 networkAgent.networkMonitor().notifyNetworkConnected(params);
10455 } else {
10456 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10457 params.networkCapabilities);
10458 }
Chalard Jean0f141332023-06-05 19:26:17 +090010459 final long evaluationDelay;
10460 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10461 // If the network is anything other than pure wifi, use the default timeout.
10462 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10463 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10464 // If the network is explicitly selected, use the default timeout because it's
10465 // shorter and the user is likely staring at the screen expecting it to validate
10466 // right away.
10467 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10468 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10469 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10470 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10471 } else {
10472 // It's wifi, automatically connected, and bad wifi is preferred : use the
10473 // longer timeout to avoid the device switching to captive portals with bad
10474 // signal or very slow response.
10475 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10476 }
10477 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010478
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010479 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10480 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10481 // capabilities, so it only needs to be done once on initial connect, not every time the
10482 // network's capabilities change. Note that we do this before rematching the network,
10483 // so we could decide to tear it down immediately afterwards. That's fine though - on
10484 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10485 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010486 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010487
junyulai0ac374f2020-12-14 18:41:52 +080010488 // Before first rematching networks, put an inactivity timer without any request, this
10489 // allows {@code updateInactivityState} to update the state accordingly and prevent
10490 // tearing down for any {@code unneeded} evaluation in this period.
10491 // Note that the timer will not be rescheduled since the expiry time is
10492 // fixed after connection regardless of the network satisfying other requests or not.
10493 // But it will be removed as soon as the network satisfies a request for the first time.
10494 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10495 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010496 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010497
Paul Jensen05e85ee2014-09-11 11:00:39 -040010498 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010499 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010500
10501 // This has to happen after matching the requests, because callbacks are just requests.
10502 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010503 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010504 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010505 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010506 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010507 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010508 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010509 if (networkAgent.isVPN()) {
10510 // As the active or bound network changes for apps, broadcast the default proxy, as
10511 // apps may need to update their proxy data. This is called after disconnecting from
10512 // VPN to make sure we do not broadcast the old proxy data.
10513 // TODO(b/122649188): send the broadcast only to VPN users.
10514 mProxyTracker.sendProxyBroadcast();
10515 }
Chalard Jean254bd162022-08-25 13:04:51 +090010516 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10517 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010518 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010519 }
10520 }
10521
Chalard Jean28018572020-12-21 18:36:52 +090010522 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010523 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10524 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010525 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010526 }
10527
Erik Kline99f301b2017-02-15 19:59:17 +090010528 // Notify only this one new request of the current state. Transfer all the
10529 // current state by calling NetworkCapabilities and LinkProperties callbacks
10530 // so that callers can be guaranteed to have as close to atomicity in state
10531 // transfer as can be supported by this current API.
10532 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010533 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010534 if (nri.mPendingIntent != null) {
10535 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10536 // Attempt no subsequent state pushes where intents are involved.
10537 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010538 }
Erik Kline99f301b2017-02-15 19:59:17 +090010539
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010540 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010541 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010542 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10543 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10544 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010545 }
10546
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010547 // Notify the requests on this NAI that the network is now lingered.
10548 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010549 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010550 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10551 }
10552
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010553 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10554 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10555 return vpnBlocked
10556 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10557 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10558 }
10559
10560 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10561 if (blockedReasons == BLOCKED_REASON_NONE) {
10562 mUidBlockedReasons.delete(uid);
10563 } else {
10564 mUidBlockedReasons.put(uid, blockedReasons);
10565 }
10566 }
10567
junyulaif2c67e42018-08-07 19:50:45 +080010568 /**
10569 * Notify of the blocked state apps with a registered callback matching a given NAI.
10570 *
10571 * Unlike other callbacks, blocked status is different between each individual uid. So for
10572 * any given nai, all requests need to be considered according to the uid who filed it.
10573 *
10574 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010575 * @param oldMetered True if the previous network capabilities were metered.
10576 * @param newMetered True if the current network capabilities are metered.
10577 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10578 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010579 */
10580 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010581 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10582 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010583
10584 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10585 NetworkRequest nr = nai.requestAt(i);
10586 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010587
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010588 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10589 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10590 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010591 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010592 : oldVpnBlocked;
10593
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010594 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10595 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10596 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010597 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010598 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010599 }
10600 }
10601 }
10602
10603 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010604 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010605 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010606 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010607 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010608 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010609 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010610 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010611 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010612
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010613 final int oldBlockedState = getBlockedState(
10614 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10615 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10616 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010617 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010618 }
junyulaif2c67e42018-08-07 19:50:45 +080010619 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10620 NetworkRequest nr = nai.requestAt(i);
10621 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010622 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010623 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10624 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010625 }
10626 }
10627 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010628 }
10629
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010630 @VisibleForTesting
10631 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010632 // The NetworkInfo we actually send out has no bearing on the real
10633 // state of affairs. For example, if the default connection is mobile,
10634 // and a request for HIPRI has just gone away, we need to pretend that
10635 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10636 // the state to DISCONNECTED, even though the network is of type MOBILE
10637 // and is still connected.
10638 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10639 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010640 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010641 if (state != DetailedState.DISCONNECTED) {
10642 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010643 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010644 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010645 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010646 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10647 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10648 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10649 if (info.isFailover()) {
10650 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10651 nai.networkInfo.setFailover(false);
10652 }
10653 if (info.getReason() != null) {
10654 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10655 }
10656 if (info.getExtraInfo() != null) {
10657 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10658 }
10659 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010660 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010661 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010662 if (newDefaultAgent != null) {
10663 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10664 newDefaultAgent.networkInfo);
10665 } else {
10666 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10667 }
10668 }
10669 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10670 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010671 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010672 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010673 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010674 }
10675 }
10676 }
10677
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010678 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010679 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010680 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010681 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010682 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010683 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10684 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010685 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10686 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010687 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010688 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010689 } else {
10690 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10691 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010692 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010693 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010694
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010695 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10696 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10697 }
10698
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010699 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010700 * Returns the list of all interfaces that could be used by network traffic that does not
10701 * explicitly specify a network. This includes the default network, but also all VPNs that are
10702 * currently connected.
10703 *
10704 * Must be called on the handler thread.
10705 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010706 @NonNull
10707 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010708 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010709 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010710 final Set<Integer> activeNetIds = new ArraySet<>();
10711 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10712 if (nri.isBeingSatisfied()) {
10713 activeNetIds.add(nri.getSatisfier().network().netId);
10714 }
10715 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010716 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010717 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010718 defaultNetworks.add(nai.network);
10719 }
10720 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010721 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010722 }
10723
10724 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010725 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10726 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010727 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010728 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010729 ensureRunningOnConnectivityServiceThread();
10730 String activeIface = null;
10731 LinkProperties activeLinkProperties = getActiveLinkProperties();
10732 if (activeLinkProperties != null) {
10733 activeIface = activeLinkProperties.getInterfaceName();
10734 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010735
junyulai2050bed2021-01-23 09:46:34 +080010736 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010737 try {
junyulaide41fc22021-01-22 22:46:01 +080010738 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010739 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010740 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10741 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010742 } catch (Exception ignored) {
10743 }
10744 }
10745
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010746 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010747 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010748 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010749 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010750 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010751
10752 if (!TextUtils.isEmpty(settingUrl)) {
10753 return settingUrl;
10754 }
10755
10756 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010757 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010758 if (!TextUtils.isEmpty(settingUrl)) {
10759 return settingUrl;
10760 }
10761
10762 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010763 }
10764
10765 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010766 public void startNattKeepalive(Network network, int intervalSeconds,
10767 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010768 enforceKeepalivePermission();
10769 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010770 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010771 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10772 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010773 // false and set the underpinned network to null because there is no way and no
10774 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10775 // deprecated method.
10776 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010777 }
10778
10779 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010780 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010781 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010782 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010783 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010784 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010785 mKeepaliveTracker.startNattKeepalive(
10786 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010787 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10788 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010789 } finally {
10790 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10791 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010792 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10793 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010794 }
10795 }
junyulaid05a1922019-01-15 11:32:44 +080010796 }
10797
10798 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010799 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010800 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010801 try {
10802 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010803 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010804 mKeepaliveTracker.startTcpKeepalive(
10805 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10806 } finally {
10807 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10808 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010809 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10810 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010811 }
10812 }
junyulai0835a1e2019-01-08 20:04:33 +080010813 }
10814
10815 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010816 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010817 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010818 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10819 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010820 }
10821
10822 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090010823 public int[] getSupportedKeepalives() {
10824 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10825 // Backwards compatibility with CTS 13
10826 android.Manifest.permission.QUERY_ALL_PACKAGES);
10827
10828 return BinderUtils.withCleanCallingIdentity(() ->
10829 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10830 }
10831
10832 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010833 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010834 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010835
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010836 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010837 final long token = Binder.clearCallingIdentity();
10838 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010839 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10840 UserHandle.getUserHandleForUid(uid))) {
10841 return;
10842 }
10843
Heemin Seogdb8489d2019-06-12 09:21:44 -070010844 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10845 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010846
10847 // Turn airplane mode off
10848 setAirplaneMode(false);
10849
10850 // restore private DNS settings to default mode (opportunistic)
10851 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10852 UserHandle.getUserHandleForUid(uid))) {
10853 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10854 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10855 }
10856
10857 Settings.Global.putString(mContext.getContentResolver(),
10858 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010859 } finally {
10860 Binder.restoreCallingIdentity(token);
10861 }
Stuart Scottd5463642015-04-02 18:00:02 -070010862 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010863
Ricky Wai7097cc92018-01-23 04:09:45 +000010864 @Override
10865 public byte[] getNetworkWatchlistConfigHash() {
10866 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10867 if (nwm == null) {
10868 loge("Unable to get NetworkWatchlistManager");
10869 return null;
10870 }
10871 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10872 return nwm.getWatchlistConfigHash();
10873 }
10874
Hugo Benichibe0c7652016-05-31 16:28:06 +090010875 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010876 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010877 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010878 }
Hugo Benichif4210292017-04-21 15:07:12 +090010879
10880 private static boolean toBool(int encodedBoolean) {
10881 return encodedBoolean != 0; // Only 0 means false.
10882 }
10883
10884 private static int encodeBool(boolean b) {
10885 return b ? 1 : 0;
10886 }
mswest4632928412018-03-12 10:34:34 -070010887
10888 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010889 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10890 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10891 @NonNull String[] args) {
10892 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10893 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010894 }
10895
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010896 private Boolean parseBooleanArgument(final String arg) {
10897 if ("true".equals(arg)) {
10898 return true;
10899 } else if ("false".equals(arg)) {
10900 return false;
10901 } else {
10902 return null;
10903 }
10904 }
10905
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010906 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010907 @Override
10908 public int onCommand(String cmd) {
10909 if (cmd == null) {
10910 return handleDefaultCommands(cmd);
10911 }
10912 final PrintWriter pw = getOutPrintWriter();
10913 try {
10914 switch (cmd) {
10915 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010916 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
10917 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070010918 final String action = getNextArg();
10919 if ("enable".equals(action)) {
10920 setAirplaneMode(true);
10921 return 0;
10922 } else if ("disable".equals(action)) {
10923 setAirplaneMode(false);
10924 return 0;
10925 } else if (action == null) {
10926 final ContentResolver cr = mContext.getContentResolver();
10927 final int enabled = Settings.Global.getInt(cr,
10928 Settings.Global.AIRPLANE_MODE_ON);
10929 pw.println(enabled == 0 ? "disabled" : "enabled");
10930 return 0;
10931 } else {
10932 onHelp();
10933 return -1;
10934 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010935 case "set-chain3-enabled": {
10936 final Boolean enabled = parseBooleanArgument(getNextArg());
10937 if (null == enabled) {
10938 onHelp();
10939 return -1;
10940 }
10941 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
10942 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
10943 enabled);
10944 return 0;
10945 }
10946 case "get-chain3-enabled": {
10947 final boolean chainEnabled = getFirewallChainEnabled(
10948 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
10949 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
10950 return 0;
10951 }
10952 case "set-package-networking-enabled": {
10953 final Boolean enabled = parseBooleanArgument(getNextArg());
10954 final String packageName = getNextArg();
10955 if (null == enabled || null == packageName) {
10956 onHelp();
10957 return -1;
10958 }
10959 // Throws NameNotFound if the package doesn't exist.
10960 final int appId = setPackageFirewallRule(
10961 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
10962 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
10963 final String msg = (enabled ? "Enabled" : "Disabled")
10964 + " networking for " + packageName + ", appId " + appId;
10965 Log.i(TAG, msg);
10966 pw.println(msg);
10967 return 0;
10968 }
10969 case "get-package-networking-enabled": {
10970 final String packageName = getNextArg();
10971 final int rule = getPackageFirewallRule(
10972 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
10973 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
10974 pw.println(packageName + ":" + "allow");
10975 } else if (FIREWALL_RULE_DENY == rule) {
10976 pw.println(packageName + ":" + "deny");
10977 } else {
10978 throw new IllegalStateException("Unknown rule " + rule + " for package "
10979 + packageName);
10980 }
10981 return 0;
10982 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010983 case "reevaluate":
10984 // Usage : adb shell cmd connectivity reevaluate <netId>
10985 // If netId is omitted, then reevaluate the default network
10986 final String netId = getNextArg();
10987 final NetworkAgentInfo nai;
10988 if (null == netId) {
10989 // Note that the command is running on the wrong thread to call this,
10990 // so this could in principle return stale data. But it can't crash.
10991 nai = getDefaultNetwork();
10992 } else {
10993 // If netId can't be parsed, this throws NumberFormatException, which
10994 // is passed back to adb who prints it.
10995 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10996 }
10997 if (null == nai) {
10998 pw.println("Unknown network (net ID not found or no default network)");
10999 return 0;
11000 }
11001 Log.d(TAG, "Reevaluating network " + nai.network);
11002 reportNetworkConnectivity(nai.network, !nai.isValidated());
11003 return 0;
Junyu Lai452e4642023-10-05 17:21:19 +080011004 case "bpf-get-cgroup-program-id": {
11005 // Usage : adb shell cmd connectivity bpf-get-cgroup-program-id <type>
11006 // Get cgroup bpf program Id for the given type. See BpfUtils#getProgramId
11007 // for more detail.
11008 // If type can't be parsed, this throws NumberFormatException, which
11009 // is passed back to adb who prints it.
11010 final int type = Integer.parseInt(getNextArg());
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +000011011 final int ret = BpfUtils.getProgramId(type);
Junyu Lai452e4642023-10-05 17:21:19 +080011012 pw.println(ret);
11013 return 0;
11014 }
mswest4632928412018-03-12 10:34:34 -070011015 default:
11016 return handleDefaultCommands(cmd);
11017 }
11018 } catch (Exception e) {
11019 pw.println(e);
11020 }
11021 return -1;
11022 }
11023
11024 @Override
11025 public void onHelp() {
11026 PrintWriter pw = getOutPrintWriter();
11027 pw.println("Connectivity service commands:");
11028 pw.println(" help");
11029 pw.println(" Print this help text.");
11030 pw.println(" airplane-mode [enable|disable]");
11031 pw.println(" Turn airplane mode on or off.");
11032 pw.println(" airplane-mode");
11033 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011034 pw.println(" set-chain3-enabled [true|false]");
11035 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
11036 pw.println(" get-chain3-enabled");
11037 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
11038 pw.println(" set-package-networking-enabled [true|false] [package name]");
11039 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
11040 + " no effect if the chain is disabled.");
11041 pw.println(" get-package-networking-enabled [package name]");
11042 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
mswest4632928412018-03-12 10:34:34 -070011043 }
11044 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011045
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090011046 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011047 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
11048 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
11049 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080011050 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011051 }
11052
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090011053 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
11054 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090011055 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
11056 final TransportInfo newInfo = nc.getTransportInfo();
11057 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
11058 return;
11059 }
11060 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090011061 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090011062 }
11063 }
11064
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011065 /**
11066 * @param connectionInfo the connection to resolve.
11067 * @return {@code uid} if the connection is found and the app has permission to observe it
11068 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
11069 * connection is not found.
11070 */
11071 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011072 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
11073 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
11074 }
11075
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090011076 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011077 connectionInfo.local, connectionInfo.remote);
11078
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011079 if (uid == INVALID_UID) return uid; // Not found.
11080
11081 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
11082 // VPN, if any, that applies to the UID that owns the connection.
11083 if (checkNetworkStackPermission()) return uid;
11084
11085 final NetworkAgentInfo vpn = getVpnForUid(uid);
11086 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090011087 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011088 return INVALID_UID;
11089 }
11090
11091 return uid;
11092 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000011093
Benedict Wong493e04b2018-11-09 14:45:34 -080011094 /**
11095 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
11096 *
11097 * <p>The TestNetworkService must be run in the system server due to TUN creation.
11098 */
11099 @Override
11100 public IBinder startOrGetTestNetworkService() {
11101 synchronized (mTNSLock) {
11102 TestNetworkService.enforceTestNetworkPermissions(mContext);
11103
11104 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080011105 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080011106 }
11107
11108 return mTNS;
11109 }
11110 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080011111
Cody Kesting73708bf2019-12-18 10:57:50 -080011112 /**
11113 * Handler used for managing all Connectivity Diagnostics related functions.
11114 *
11115 * @see android.net.ConnectivityDiagnosticsManager
11116 *
11117 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
11118 */
11119 @VisibleForTesting
11120 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011121 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
11122
Cody Kesting73708bf2019-12-18 10:57:50 -080011123 /**
11124 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
11125 * android.net.ConnectivityDiagnosticsManager}.
11126 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
11127 * NetworkRequestInfo to be registered
11128 */
11129 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
11130
11131 /**
11132 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
11133 * android.net.ConnectivityDiagnosticsManager}.
11134 * obj = the IConnectivityDiagnosticsCallback to be unregistered
11135 * arg1 = the uid of the caller
11136 */
11137 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
11138
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011139 /**
11140 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011141 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011142 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
11143 * NetworkMonitor.
11144 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011145 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011146 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011147
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011148 /**
11149 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
11150 * been detected on the network.
11151 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
11152 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
11153 * arg2 = NetID.
11154 * data = PersistableBundle of extras passed from NetworkMonitor.
11155 */
11156 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
11157
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011158 /**
11159 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
11160 * the platform. This event will invoke {@link
11161 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
11162 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070011163 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011164 */
11165 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
11166
Cody Kesting73708bf2019-12-18 10:57:50 -080011167 private ConnectivityDiagnosticsHandler(Looper looper) {
11168 super(looper);
11169 }
11170
11171 @Override
11172 public void handleMessage(Message msg) {
11173 switch (msg.what) {
11174 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11175 handleRegisterConnectivityDiagnosticsCallback(
11176 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
11177 break;
11178 }
11179 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11180 handleUnregisterConnectivityDiagnosticsCallback(
11181 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
11182 break;
11183 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011184 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011185 final ConnectivityReportEvent reportEvent =
11186 (ConnectivityReportEvent) msg.obj;
11187
Aaron Huang959d3642021-01-21 15:47:41 +080011188 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011189 break;
11190 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011191 case EVENT_DATA_STALL_SUSPECTED: {
11192 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080011193 final Pair<Long, PersistableBundle> arg =
11194 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011195 if (nai == null) break;
11196
Aaron Huang959d3642021-01-21 15:47:41 +080011197 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011198 break;
11199 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011200 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070011201 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011202 break;
11203 }
11204 default: {
11205 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
11206 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011207 }
11208 }
11209 }
11210
11211 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
11212 @VisibleForTesting
11213 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
11214 @NonNull private final IConnectivityDiagnosticsCallback mCb;
11215 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011216 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011217
11218 @VisibleForTesting
11219 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011220 @NonNull IConnectivityDiagnosticsCallback cb,
11221 @NonNull NetworkRequestInfo nri,
11222 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011223 mCb = cb;
11224 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011225 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011226 }
11227
11228 @Override
11229 public void binderDied() {
11230 log("ConnectivityDiagnosticsCallback IBinder died.");
11231 unregisterConnectivityDiagnosticsCallback(mCb);
11232 }
11233 }
11234
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011235 /**
11236 * Class used for sending information from {@link
11237 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
11238 */
11239 private static class NetworkTestedResults {
11240 private final int mNetId;
11241 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011242 @Nullable private final String mRedirectUrl;
11243
11244 private NetworkTestedResults(
11245 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
11246 mNetId = netId;
11247 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011248 mRedirectUrl = redirectUrl;
11249 }
11250 }
11251
11252 /**
11253 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11254 * ConnectivityDiagnosticsHandler}.
11255 */
11256 private static class ConnectivityReportEvent {
11257 private final long mTimestampMillis;
11258 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011259 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011260
Aaron Huang959d3642021-01-21 15:47:41 +080011261 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11262 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011263 mTimestampMillis = timestampMillis;
11264 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011265 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011266 }
11267 }
11268
Cody Kestingf1120be2020-08-03 18:01:40 -070011269 /**
11270 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11271 * ConnectivityDiagnosticsHandler}.
11272 */
11273 private static class ReportedNetworkConnectivityInfo {
11274 public final boolean hasConnectivity;
11275 public final boolean isNetworkRevalidating;
11276 public final int reporterUid;
11277 @NonNull public final NetworkAgentInfo nai;
11278
11279 private ReportedNetworkConnectivityInfo(
11280 boolean hasConnectivity,
11281 boolean isNetworkRevalidating,
11282 int reporterUid,
11283 @NonNull NetworkAgentInfo nai) {
11284 this.hasConnectivity = hasConnectivity;
11285 this.isNetworkRevalidating = isNetworkRevalidating;
11286 this.reporterUid = reporterUid;
11287 this.nai = nai;
11288 }
11289 }
11290
Cody Kesting73708bf2019-12-18 10:57:50 -080011291 private void handleRegisterConnectivityDiagnosticsCallback(
11292 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11293 ensureRunningOnConnectivityServiceThread();
11294
11295 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011296 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011297 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11298
James Mattis64b8b0f2020-11-24 17:40:49 -080011299 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11300 // confusing for these networks to change when an NRI is satisfied in another layer.
11301 if (nri.isMultilayerRequest()) {
11302 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11303 + "network requests.");
11304 }
11305
Cody Kesting73708bf2019-12-18 10:57:50 -080011306 // This means that the client registered the same callback multiple times. Do
11307 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011308 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011309 if (VDBG) log("Diagnostics callback is already registered");
11310
11311 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11312 // incremented when the NetworkRequestInfo is created as part of
11313 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011314 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011315 return;
11316 }
11317
Cody Kesting31f1ff62020-03-05 10:46:02 -080011318 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011319
11320 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011321 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011322 } catch (RemoteException e) {
11323 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011324 return;
11325 }
11326
11327 // Once registered, provide ConnectivityReports for matching Networks
11328 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11329 synchronized (mNetworkForNetId) {
11330 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11331 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011332 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11333 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011334 matchingNetworks.add(nai);
11335 }
11336 }
11337 }
11338 for (final NetworkAgentInfo nai : matchingNetworks) {
11339 final ConnectivityReport report = nai.getConnectivityReport();
11340 if (report == null) {
11341 continue;
11342 }
11343 if (!checkConnectivityDiagnosticsPermissions(
11344 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11345 continue;
11346 }
11347
11348 try {
11349 cb.onConnectivityReportAvailable(report);
11350 } catch (RemoteException e) {
11351 // Exception while sending the ConnectivityReport. Move on to the next network.
11352 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011353 }
11354 }
11355
11356 private void handleUnregisterConnectivityDiagnosticsCallback(
11357 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11358 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011359 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011360
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011361 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11362 mConnectivityDiagnosticsCallbacks.remove(iCb);
11363 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011364 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11365 return;
11366 }
11367
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011368 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011369
Cody Kesting70fa2b22020-12-02 12:16:56 -080011370 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11371 // (if the Binder died)
11372 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11373 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011374 return;
11375 }
11376
Cody Kesting46cb1672020-03-04 13:35:20 -080011377 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11378 // incremented when the NetworkRequestInfo is created as part of
11379 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011380 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011381
Cody Kesting31f1ff62020-03-05 10:46:02 -080011382 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011383 }
11384
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011385 private void handleNetworkTestedWithExtras(
11386 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11387 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011388 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011389 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011390 final ConnectivityReport report =
11391 new ConnectivityReport(
11392 reportEvent.mNai.network,
11393 reportEvent.mTimestampMillis,
11394 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011395 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011396 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011397 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011398
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011399 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011400 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011401 for (final IConnectivityDiagnosticsCallback cb : results) {
11402 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011403 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011404 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011405 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011406 }
11407 }
11408 }
11409
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011410 private void handleDataStallSuspected(
11411 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11412 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011413 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011414 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011415 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011416 new DataStallReport(
11417 nai.network,
11418 timestampMillis,
11419 detectionMethod,
11420 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011421 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011422 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011423 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011424 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011425 for (final IConnectivityDiagnosticsCallback cb : results) {
11426 try {
11427 cb.onDataStallSuspected(report);
11428 } catch (RemoteException ex) {
11429 loge("Error invoking onDataStallSuspected", ex);
11430 }
11431 }
11432 }
11433
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011434 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011435 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11436 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11437 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11438
11439 // If the Network is being re-validated as a result of this call to
11440 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11441 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011442 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011443 getMatchingPermissionedCallbacks(
11444 nai,
11445 reportedNetworkConnectivityInfo.isNetworkRevalidating
11446 ? Process.INVALID_UID
11447 : reportedNetworkConnectivityInfo.reporterUid);
11448
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011449 for (final IConnectivityDiagnosticsCallback cb : results) {
11450 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011451 cb.onNetworkConnectivityReported(
11452 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011453 } catch (RemoteException ex) {
11454 loge("Error invoking onNetworkConnectivityReported", ex);
11455 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011456
11457 // If the Network isn't re-validating, also provide the cached report. If there is no
11458 // cached report, the Network is still being validated and a report will be sent once
11459 // validation is complete. Note that networks which never undergo validation will still
11460 // have a cached ConnectivityReport with RESULT_SKIPPED.
11461 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11462 try {
11463 cb.onConnectivityReportAvailable(cachedReport);
11464 } catch (RemoteException ex) {
11465 loge("Error invoking onConnectivityReportAvailable", ex);
11466 }
11467 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011468 }
11469 }
11470
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011471 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011472 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11473 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011474 sanitized.setUids(null);
11475 sanitized.setAdministratorUids(new int[0]);
11476 sanitized.setOwnerUid(Process.INVALID_UID);
11477 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011478 }
11479
Cody Kestingf1120be2020-08-03 18:01:40 -070011480 /**
11481 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11482 *
11483 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11484 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011485 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011486 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011487 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011488 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011489 mConnectivityDiagnosticsCallbacks.entrySet()) {
11490 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11491 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011492
James Mattis64b8b0f2020-11-24 17:40:49 -080011493 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011494 if (!nai.satisfies(nri.mRequests.get(0))) {
11495 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011496 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011497
11498 // UID for this callback must either be:
11499 // - INVALID_UID (which sends callbacks to all UIDs), or
11500 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11501 // notified as a result)
11502 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11503 continue;
11504 }
11505
11506 if (!checkConnectivityDiagnosticsPermissions(
11507 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11508 continue;
11509 }
11510
11511 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011512 }
11513 return results;
11514 }
11515
Cody Kesting7474f672021-05-11 14:22:40 -070011516 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11517 @NonNull NetworkAgentInfo nai) {
11518 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11519 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11520 }
11521
Cody Kesting160ef392021-05-05 13:17:22 -070011522 private boolean hasLocationPermission(String packageName, int uid) {
11523 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11524 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11525 // call in a try-catch.
11526 try {
11527 if (!mLocationPermissionChecker.checkLocationPermission(
11528 packageName, null /* featureId */, uid, null /* message */)) {
11529 return false;
11530 }
11531 } catch (SecurityException e) {
11532 return false;
11533 }
11534
11535 return true;
11536 }
11537
11538 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11539 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011540 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011541 && virtual.networkCapabilities.getOwnerUid() == uid
11542 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11543 return true;
11544 }
11545 }
11546
11547 return false;
11548 }
11549
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011550 @VisibleForTesting
11551 boolean checkConnectivityDiagnosticsPermissions(
11552 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
11553 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
11554 return true;
11555 }
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011556 if (mAllowSysUiConnectivityReports
Chris Göllnercc962022023-12-26 09:55:32 +000011557 && checkSystemBarServicePermission(callbackPid, callbackUid)) {
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011558 return true;
11559 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011560
Cody Kesting160ef392021-05-05 13:17:22 -070011561 // Administrator UIDs also contains the Owner UID
11562 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11563 if (!CollectionUtils.contains(administratorUids, callbackUid)
11564 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011565 return false;
11566 }
11567
Cody Kesting7474f672021-05-11 14:22:40 -070011568 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11569 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011570 }
11571
Cody Kestingd199a9d2019-12-17 12:55:28 -080011572 @Override
11573 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011574 @NonNull IConnectivityDiagnosticsCallback callback,
11575 @NonNull NetworkRequest request,
11576 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011577 Objects.requireNonNull(callback, "callback must not be null");
11578 Objects.requireNonNull(request, "request must not be null");
11579 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11580
Cody Kesting73708bf2019-12-18 10:57:50 -080011581 if (request.legacyType != TYPE_NONE) {
11582 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11583 + " Please use NetworkCapabilities instead.");
11584 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011585 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011586 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011587
11588 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11589 // and administrator uids to be safe.
11590 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011591 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011592
11593 final NetworkRequest requestWithId =
11594 new NetworkRequest(
11595 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11596
11597 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11598 //
11599 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11600 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11601 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011602 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011603 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011604 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011605
11606 mConnectivityDiagnosticsHandler.sendMessage(
11607 mConnectivityDiagnosticsHandler.obtainMessage(
11608 ConnectivityDiagnosticsHandler
11609 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11610 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011611 }
11612
11613 @Override
11614 public void unregisterConnectivityDiagnosticsCallback(
11615 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011616 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011617 mConnectivityDiagnosticsHandler.sendMessage(
11618 mConnectivityDiagnosticsHandler.obtainMessage(
11619 ConnectivityDiagnosticsHandler
11620 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011621 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011622 0,
11623 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011624 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011625
Yan Yanfe96dde2022-12-05 23:00:01 +000011626 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11627 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11628 if (underlyingNetworks == null) return false;
11629
11630 for (Network network : underlyingNetworks) {
11631 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11632 return true;
11633 }
11634 }
11635 return false;
11636 }
11637
Cody Kestingf53a0752020-04-15 12:33:28 -070011638 @Override
11639 public void simulateDataStall(int detectionMethod, long timestampMillis,
11640 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011641 Objects.requireNonNull(network, "network must not be null");
11642 Objects.requireNonNull(extras, "extras must not be null");
11643
paulhu3ffffe72021-09-16 10:15:22 +080011644 enforceAnyPermissionOf(mContext,
11645 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011646 android.Manifest.permission.NETWORK_STACK);
11647 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011648 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11649 throw new SecurityException(
11650 "Data Stall simulation is only possible for test networks or networks built on"
11651 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011652 }
11653
11654 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011655 if (nai == null
11656 || (nai.creatorUid != mDeps.getCallingUid()
11657 && nai.creatorUid != Process.SYSTEM_UID)) {
11658 throw new SecurityException(
11659 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011660 }
11661
Cody Kesting652e3ec2020-05-21 12:08:21 -070011662 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11663 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11664 // Data Stall information as a DataStallReportParcelable and passing to
11665 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11666 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011667 final DataStallReportParcelable p = new DataStallReportParcelable();
11668 p.timestampMillis = timestampMillis;
11669 p.detectionMethod = detectionMethod;
11670
11671 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11672 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11673 }
11674 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11675 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11676 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11677 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11678 }
11679
Serik Beketayevec8ad212020-12-07 22:43:07 -080011680 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011681 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011682
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011683 /**
11684 * Class to hold the information for network activity change event from idle timers
11685 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
11686 */
11687 private static final class NetworkActivityParams {
11688 public final boolean isActive;
11689 // Label used for idle timer. Transport type is used as label.
11690 // label is int since NMS was using the identifier as int, and it has not been changed
11691 public final int label;
11692 public final long timestampNs;
11693 // Uid represents the uid that was responsible for waking the radio.
11694 // -1 for no uid and uid is -1 if isActive is false.
11695 public final int uid;
11696
11697 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
11698 this.isActive = isActive;
11699 this.label = label;
11700 this.timestampNs = timestampNs;
11701 this.uid = uid;
11702 }
11703 }
11704
lucaslin66f44212021-02-23 01:12:55 +080011705 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11706 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011707 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080011708 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011709 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
11710 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080011711 }
lucaslin37a16d92021-01-21 19:48:09 +080011712
11713 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011714 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011715 mHandler.post(() -> {
11716 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011717 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011718 }
11719 });
lucaslin37a16d92021-01-21 19:48:09 +080011720 }
11721
11722 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011723 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011724 mHandler.post(() -> {
11725 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011726 nai.clatd.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011727 }
11728 });
lucaslin66f44212021-02-23 01:12:55 +080011729 }
11730 }
11731
lucaslin1a8b4c62021-01-21 02:02:55 +080011732 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11733
11734 /**
11735 * Class used for updating network activity tracking with netd and notify network activity
11736 * changes.
11737 */
11738 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011739 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011740 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011741 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011742 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080011743 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11744 new RemoteCallbackList<>();
11745 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090011746 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011747 // If there is no default network, default network is considered active to keep the existing
11748 // behavior. Initial value is used until first connect to the default network.
11749 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011750 // Key is netId. Value is configured idle timer information.
11751 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080011752
Chalard Jean46bfbf02022-02-02 00:56:25 +090011753 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011754 public final int timeout;
11755 public final int transportType;
11756
11757 IdleTimerParams(int timeout, int transport) {
11758 this.timeout = timeout;
11759 this.transportType = transport;
11760 }
11761 }
11762
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011763 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011764 @NonNull Handler handler) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011765 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011766 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011767 mHandler = handler;
11768 }
11769
11770 private void ensureRunningOnConnectivityServiceThread() {
11771 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
11772 throw new IllegalStateException("Not running on ConnectivityService thread: "
11773 + Thread.currentThread().getName());
11774 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011775 }
11776
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011777 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011778 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011779 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011780 // This activity change is not for the current default network.
11781 // This can happen if netd callback post activity change event message but
11782 // the default network is lost before processing this message.
11783 return;
11784 }
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011785 sendDataActivityBroadcast(transportTypeToLegacyType(activityParams.label),
11786 activityParams.isActive, activityParams.timestampNs);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011787 mIsDefaultNetworkActive = activityParams.isActive;
11788 if (mIsDefaultNetworkActive) {
11789 reportNetworkActive();
lucaslin66f44212021-02-23 01:12:55 +080011790 }
11791 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011792
lucaslin1193a5d2021-01-21 02:04:15 +080011793 private void reportNetworkActive() {
11794 final int length = mNetworkActivityListeners.beginBroadcast();
11795 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
11796 try {
11797 for (int i = 0; i < length; i++) {
11798 try {
11799 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
11800 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011801 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080011802 }
11803 }
11804 } finally {
11805 mNetworkActivityListeners.finishBroadcast();
11806 }
11807 }
11808
lucaslin1a8b4c62021-01-21 02:02:55 +080011809 // This is deprecated and only to support legacy use cases.
11810 private int transportTypeToLegacyType(int type) {
11811 switch (type) {
11812 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011813 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080011814 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011815 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080011816 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011817 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080011818 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011819 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080011820 default:
11821 loge("Unexpected transport in transportTypeToLegacyType: " + type);
11822 }
11823 return ConnectivityManager.TYPE_NONE;
11824 }
11825
11826 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
11827 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
11828 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
11829 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
11830 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
11831 final long ident = Binder.clearCallingIdentity();
11832 try {
11833 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
11834 RECEIVE_DATA_ACTIVITY_CHANGE,
11835 null /* resultReceiver */,
11836 null /* scheduler */,
11837 0 /* initialCode */,
11838 null /* initialData */,
11839 null /* initialExtra */);
11840 } finally {
11841 Binder.restoreCallingIdentity(ident);
11842 }
11843 }
11844
11845 /**
11846 * Setup data activity tracking for the given network.
11847 *
11848 * Every {@code setupDataActivityTracking} should be paired with a
11849 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090011850 *
11851 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080011852 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090011853 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011854 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011855 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080011856
11857 final int timeout;
11858 final int type;
11859
11860 if (networkAgent.networkCapabilities.hasTransport(
11861 NetworkCapabilities.TRANSPORT_CELLULAR)) {
11862 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011863 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080011864 10);
11865 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11866 } else if (networkAgent.networkCapabilities.hasTransport(
11867 NetworkCapabilities.TRANSPORT_WIFI)) {
11868 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011869 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080011870 15);
11871 type = NetworkCapabilities.TRANSPORT_WIFI;
11872 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011873 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080011874 }
11875
lucaslinb961efc2021-01-21 02:03:17 +080011876 updateRadioPowerState(true /* isActive */, type);
11877
lucaslin1a8b4c62021-01-21 02:02:55 +080011878 if (timeout > 0 && iface != null) {
11879 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011880 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, type));
Motomu Utsumic298cf02023-05-31 12:06:12 +090011881 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
Motomu Utsumi6225d572023-05-29 15:08:57 +090011882 return true;
lucaslin1a8b4c62021-01-21 02:02:55 +080011883 } catch (Exception e) {
11884 // You shall not crash!
11885 loge("Exception in setupDataActivityTracking " + e);
11886 }
11887 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011888 return false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011889 }
11890
11891 /**
11892 * Remove data activity tracking when network disconnects.
11893 */
11894 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
11895 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011896 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080011897 final NetworkCapabilities caps = networkAgent.networkCapabilities;
11898
lucaslinb961efc2021-01-21 02:03:17 +080011899 if (iface == null) return;
11900
11901 final int type;
11902 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
11903 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11904 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
11905 type = NetworkCapabilities.TRANSPORT_WIFI;
11906 } else {
11907 return; // do not track any other networks
11908 }
11909
11910 try {
11911 updateRadioPowerState(false /* isActive */, type);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011912 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011913 if (params == null) {
11914 // IdleTimer is not added if the configured timeout is 0 or negative value
11915 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080011916 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011917 mActiveIdleTimers.remove(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011918 // The call fails silently if no idle timer setup for this interface
11919 mNetd.idletimerRemoveInterface(iface, params.timeout,
11920 Integer.toString(params.transportType));
lucaslinb961efc2021-01-21 02:03:17 +080011921 } catch (Exception e) {
11922 // You shall not crash!
11923 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080011924 }
11925 }
11926
Motomu Utsumi6225d572023-05-29 15:08:57 +090011927 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
11928 boolean hasIdleTimer) {
11929 if (defaultNetwork != null) {
11930 mIsDefaultNetworkActive = true;
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011931 // Callbacks are called only when the network has the idle timer.
11932 if (hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011933 reportNetworkActive();
11934 }
11935 } else {
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011936 // If there is no default network, default network is considered active to keep the
11937 // existing behavior.
11938 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090011939 }
11940 }
11941
lucaslin1a8b4c62021-01-21 02:02:55 +080011942 /**
11943 * Update data activity tracking when network state is updated.
11944 */
11945 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
11946 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011947 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi6225d572023-05-29 15:08:57 +090011948 boolean hasIdleTimer = false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011949 if (newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011950 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080011951 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011952 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
lucaslin1a8b4c62021-01-21 02:02:55 +080011953 if (oldNetwork != null) {
11954 removeDataActivityTracking(oldNetwork);
11955 }
11956 }
lucaslinb961efc2021-01-21 02:03:17 +080011957
11958 private void updateRadioPowerState(boolean isActive, int transportType) {
11959 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
11960 switch (transportType) {
11961 case NetworkCapabilities.TRANSPORT_CELLULAR:
11962 bs.reportMobileRadioPowerState(isActive, NO_UID);
11963 break;
11964 case NetworkCapabilities.TRANSPORT_WIFI:
11965 bs.reportWifiRadioPowerState(isActive, NO_UID);
11966 break;
11967 default:
11968 logw("Untracked transport type:" + transportType);
11969 }
11970 }
lucaslin1193a5d2021-01-21 02:04:15 +080011971
11972 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011973 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080011974 }
11975
11976 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
11977 mNetworkActivityListeners.register(l);
11978 }
11979
11980 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
11981 mNetworkActivityListeners.unregister(l);
11982 }
lucaslin012f7a12021-01-21 02:04:35 +080011983
11984 public void dump(IndentingPrintWriter pw) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011985 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
11986 pw.println("Idle timers:");
11987 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011988 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
11989 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
11990 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080011991 pw.print(" timeout="); pw.print(params.timeout);
11992 pw.print(" type="); pw.println(params.transportType);
11993 }
Motomu Utsumic298cf02023-05-31 12:06:12 +090011994 } catch (Exception e) {
11995 // mActiveIdleTimers should only be accessed from handler thread, except dump().
11996 // As dump() is never called in normal usage, it would be needlessly expensive
11997 // to lock the collection only for its benefit.
11998 // Also, mActiveIdleTimers is not expected to be updated frequently.
11999 // So catching the exception and logging.
12000 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080012001 }
12002 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012003 }
James Mattis47db0582021-01-01 14:13:35 -080012004
Daniel Brightf9e945b2020-06-15 16:10:01 -070012005 /**
12006 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
12007 *
12008 * @param socketInfo the socket information
12009 * @param callback the callback to register
12010 */
12011 @Override
12012 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
12013 @NonNull final IQosCallback callback) {
12014 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
12015 if (nai == null || nai.networkCapabilities == null) {
12016 try {
12017 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
12018 } catch (final RemoteException ex) {
12019 loge("registerQosCallbackInternal: RemoteException", ex);
12020 }
12021 return;
12022 }
12023 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
12024 }
12025
12026 /**
12027 * Register a {@link IQosCallback} with base {@link QosFilter}.
12028 *
12029 * @param filter the filter to register
12030 * @param callback the callback to register
12031 * @param nai the agent information related to the filter's network
12032 */
12033 @VisibleForTesting
12034 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
12035 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012036 Objects.requireNonNull(filter, "filter must be non-null");
12037 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012038
12039 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080012040 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
12041 // on this network is unregistered when the app loses permission or b) no QoS
12042 // callbacks are sent for restricted networks unless the app currently has permission
12043 // to access restricted networks.
12044 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070012045 }
12046 mQosCallbackTracker.registerCallback(callback, filter, nai);
12047 }
12048
12049 /**
12050 * Unregisters the given callback.
12051 *
12052 * @param callback the callback to unregister
12053 */
12054 @Override
12055 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080012056 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012057 mQosCallbackTracker.unregisterCallback(callback);
12058 }
James Mattis47db0582021-01-01 14:13:35 -080012059
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012060 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
12061 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
12062 // Enterprise device can be fully managed like device owner and such use case
12063 // also should be supported. Calling app check for work profile and fully managed device
12064 // is already done in DevicePolicyManager.
12065 // This check is an extra caution to be sure device is fully managed or not.
12066 final UserManager um = mContext.getSystemService(UserManager.class);
12067 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
12068 if (um.isManagedProfile(profile.getIdentifier())) {
12069 return true;
12070 }
Chalard Jeandf29a852023-05-29 17:02:43 +090012071 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012072 return false;
12073 }
12074
James Mattis45d81842021-01-10 14:24:24 -080012075 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012076 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012077 *
12078 * See the documentation for the individual preferences for a description of the supported
12079 * behaviors.
12080 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012081 * @param profile If the device owner is set, any profile is allowed.
12082 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012083 * @param preferences the list of profile network preferences for the
12084 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012085 * @param listener an optional listener to listen for completion of the operation.
12086 */
12087 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012088 public void setProfileNetworkPreferences(
12089 @NonNull final UserHandle profile,
12090 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090012091 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012092 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012093 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012094
12095 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012096 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
12097 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
12098 .build();
12099 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012100 }
12101
paulhu3ffffe72021-09-16 10:15:22 +080012102 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012103 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012104 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012105 }
12106 if (profile.getIdentifier() < 0) {
12107 throw new IllegalArgumentException("Must explicitly specify a user handle ("
12108 + "UserHandle.CURRENT not supported)");
12109 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012110 if (!isNetworkPreferenceAllowedForProfile(profile)) {
12111 throw new IllegalArgumentException("Profile must be a managed profile "
12112 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012113 }
paulhuaa0743d2021-05-26 21:56:03 +080012114
Chalard Jean0606fc82022-12-14 20:34:43 +090012115 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012116 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012117 for (final ProfileNetworkPreference preference : preferences) {
12118 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012119 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080012120 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012121 switch (preference.getPreference()) {
12122 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
12123 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012124 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012125 if (preference.getPreferenceEnterpriseId() != 0) {
12126 throw new IllegalArgumentException(
12127 "Invalid enterprise identifier in setProfileNetworkPreferences");
12128 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012129 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080012130 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
12131 blockingNonEnterprise = true;
12132 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012133 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
12134 allowFallback = false;
12135 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012136 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012137 // This code is needed even though there is a check later on,
12138 // because isRangeAlreadyInPreferenceList assumes that every preference
12139 // has a UID list.
12140 if (hasDefaultPreference) {
12141 throw new IllegalArgumentException(
12142 "Default profile preference should not be set along with other "
12143 + "preference");
12144 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012145 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
12146 throw new IllegalArgumentException(
12147 "Invalid enterprise identifier in setProfileNetworkPreferences");
12148 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012149 final Set<UidRange> uidRangeSet =
12150 getUidListToBeAppliedForNetworkPreference(profile, preference);
12151 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
12152 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
12153 } else {
12154 throw new IllegalArgumentException(
12155 "Overlapping uid range in setProfileNetworkPreferences");
12156 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012157 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012158 nc.addEnterpriseId(
12159 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012160 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12161 break;
12162 default:
12163 throw new IllegalArgumentException(
12164 "Invalid preference in setProfileNetworkPreferences");
12165 }
Junyu Lai35665cc2022-12-19 17:37:48 +080012166 preferenceList.add(new ProfileNetworkPreferenceInfo(
12167 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012168 if (hasDefaultPreference && preferenceList.size() > 1) {
12169 throw new IllegalArgumentException(
12170 "Default profile preference should not be set along with other preference");
12171 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012172 }
12173 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012174 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012175 }
12176
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012177 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
12178 @NonNull final UserHandle profile,
12179 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
12180 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080012181 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
12182 profileNetworkPreference.getIncludedUids());
12183
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012184 if (uidRangeSet.size() > 0) {
12185 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
12186 throw new IllegalArgumentException(
12187 "Allow uid range is outside the uid range of profile.");
12188 }
12189 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080012190 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012191 profileNetworkPreference.getExcludedUids());
12192 if (disallowUidRangeSet.size() > 0) {
12193 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
12194 throw new IllegalArgumentException(
12195 "disallow uid range is outside the uid range of profile.");
12196 }
12197 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
12198 disallowUidRangeSet);
12199 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012200 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012201 uidRangeSet.add(profileUids);
12202 }
12203 }
12204 return uidRangeSet;
12205 }
12206
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012207 private boolean isEnterpriseIdentifierValid(
12208 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012209 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012210 return true;
12211 }
12212 return false;
12213 }
12214
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012215 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090012216 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012217 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090012218 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012219 // The NRI for a user should contain the request for capabilities.
12220 // If fallback to default network is needed then NRI should include
12221 // the request for the default network. Create an image of it to
12222 // have the correct UIDs in it (also a request can only be part of one NRI, because
12223 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012224 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
12225 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012226 if (pref.allowFallback) {
12227 nrs.add(createDefaultInternetRequestForTransport(
12228 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12229 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012230 if (VDBG) {
12231 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
12232 pref.capabilities.getUids()));
12233 }
12234
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012235 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080012236 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080012237 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012238 result.add(nri);
12239 }
12240 return result;
12241 }
12242
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012243 /**
12244 * Compare if the given UID range sets have the same UIDs.
12245 *
12246 */
12247 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090012248 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012249 @NonNull Set<UidRange> uidRangeSet) {
12250 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
12251 return false;
12252 }
Chalard Jean0606fc82022-12-14 20:34:43 +090012253 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012254 if (UidRangeUtils.doesRangeSetOverlap(
12255 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12256 return true;
12257 }
12258 }
12259 return false;
12260 }
12261
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012262 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012263 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012264 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012265 /*
12266 * handleSetProfileNetworkPreference is always called for single user.
12267 * preferenceList only contains preferences for different uids within the same user
12268 * (enforced by getUidListToBeAppliedForNetworkPreference).
12269 * Clear all the existing preferences for the user before applying new preferences.
12270 *
12271 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012272 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12273 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012274 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12275 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012276
paulhu74128522021-09-28 02:29:03 +000012277 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12278 addPerAppDefaultNetworkRequests(
12279 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012280 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012281
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012282 // Finally, rematch.
12283 rematchAllNetworksAndRequests();
12284
12285 if (null != listener) {
12286 try {
12287 listener.onComplete();
12288 } catch (RemoteException e) {
12289 loge("Listener for setProfileNetworkPreference has died");
12290 }
12291 }
12292 }
12293
paulhu51f77dc2021-06-07 02:34:20 +000012294 @VisibleForTesting
12295 @NonNull
12296 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12297 @NonNull final Set<Integer> uids) {
12298 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12299 if (uids.size() == 0) {
12300 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12301 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
12302 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
12303 return nris;
12304 }
12305
12306 final List<NetworkRequest> requests = new ArrayList<>();
12307 // The NRI should be comprised of two layers:
12308 // - The request for the mobile network preferred.
12309 // - The request for the default network, for fallback.
12310 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012311 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012312 requests.add(createDefaultInternetRequestForTransport(
12313 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12314 final Set<UidRange> ranges = new ArraySet<>();
12315 for (final int uid : uids) {
12316 ranges.add(new UidRange(uid, uid));
12317 }
12318 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080012319 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080012320 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000012321 return nris;
12322 }
12323
12324 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012325 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012326 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12327 addPerAppDefaultNetworkRequests(
12328 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012329 // Finally, rematch.
12330 rematchAllNetworksAndRequests();
12331 }
12332
Patrick Rohr2857ac42022-01-21 14:58:16 +010012333 private void handleIngressRateLimitChanged() {
12334 final long oldIngressRateLimit = mIngressRateLimit;
12335 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12336 mContext);
12337 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12338 if (canNetworkBeRateLimited(networkAgent)) {
12339 // If rate limit has previously been enabled, remove the old limit first.
12340 if (oldIngressRateLimit >= 0) {
12341 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12342 }
12343 if (mIngressRateLimit >= 0) {
12344 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12345 mIngressRateLimit);
12346 }
12347 }
12348 }
12349 }
12350
12351 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012352 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090012353 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012354
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012355 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12356 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12357 // internet connectivity can be rate limited.
12358 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12359 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012360 return false;
12361 }
12362
12363 final String iface = networkAgent.linkProperties.getInterfaceName();
12364 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012365 // This may happen in tests, but if there is no interface then there is nothing that
12366 // can be rate limited.
12367 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012368 return false;
12369 }
12370 return true;
12371 }
12372
James Mattis45d81842021-01-10 14:24:24 -080012373 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012374 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12375 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012376 }
12377
12378 /**
12379 * Used by automotive devices to set the network preferences used to direct traffic at an
12380 * application level as per the given OemNetworkPreferences. An example use-case would be an
12381 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12382 * vehicle via a particular network.
12383 *
12384 * Calling this will overwrite the existing preference.
12385 *
James Mattisda32cfe2021-01-26 16:23:52 -080012386 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012387 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012388 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012389 */
James Mattis47db0582021-01-01 14:13:35 -080012390 @Override
James Mattis45d81842021-01-10 14:24:24 -080012391 public void setOemNetworkPreference(
12392 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012393 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012394
James Mattisfa270db2021-05-31 17:11:10 -070012395 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12396 // Only bypass the permission/device checks if this is a valid test request.
12397 if (isValidTestOemNetworkPreference(preference)) {
12398 enforceManageTestNetworksPermission();
12399 } else {
12400 enforceAutomotiveDevice();
12401 enforceOemNetworkPreferencesPermission();
12402 validateOemNetworkPreferences(preference);
12403 }
James Mattis45d81842021-01-10 14:24:24 -080012404
James Mattis45d81842021-01-10 14:24:24 -080012405 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12406 new Pair<>(preference, listener)));
12407 }
12408
James Mattisfa270db2021-05-31 17:11:10 -070012409 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012410 * Sets the specified UIDs to get/receive the VPN as the only default network.
12411 *
12412 * Calling this will overwrite the existing network preference for this session, and the
12413 * specified UIDs won't get any default network when no VPN is connected.
12414 *
12415 * @param session The VPN session which manages the passed UIDs.
12416 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12417 * setting for this session if the array is empty. Null is not allowed, the
12418 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12419 * @hide
12420 */
12421 @Override
12422 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12423 Objects.requireNonNull(ranges);
12424 enforceNetworkStackOrSettingsPermission();
12425 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12426 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12427 throw new IllegalArgumentException(
12428 "setVpnNetworkPreference: Passed UID ranges overlap");
12429 }
12430
12431 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12432 new VpnNetworkPreferenceInfo(session,
12433 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12434 }
12435
12436 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12437 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12438
12439 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12440 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12441
12442 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12443 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12444 // Finally, rematch.
12445 rematchAllNetworksAndRequests();
12446 }
12447
12448 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12449 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12450 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12451 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
12452 final List<NetworkRequest> requests = new ArrayList<>();
12453 // Request VPN only, so other networks won't be the fallback options when VPN is not
12454 // connected temporarily.
12455 requests.add(createVpnRequest());
12456 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
12457 setNetworkRequestUids(requests, uidRanges);
12458 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
12459 }
12460 return nris;
12461 }
12462
12463 /**
James Mattisfa270db2021-05-31 17:11:10 -070012464 * Check the validity of an OEM network preference to be used for testing purposes.
12465 * @param preference the preference to validate
12466 * @return true if this is a valid OEM network preference test request.
12467 */
12468 private boolean isValidTestOemNetworkPreference(
12469 @NonNull final OemNetworkPreferences preference) {
12470 // Allow for clearing of an existing OemNetworkPreference used for testing.
12471 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
12472 // changes after this check is complete. This is an unlikely scenario as calling of this API
12473 // is controlled by the OEM therefore the added complexity is not worth adding given those
12474 // circumstances. That said, it is an edge case to be aware of hence this comment.
12475 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
12476 && isTestOemNetworkPreference(mOemNetworkPreferences);
12477 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
12478 }
12479
12480 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
12481 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
12482 return prefMap.size() == 1
12483 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
12484 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
12485 }
12486
James Mattis45d81842021-01-10 14:24:24 -080012487 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
12488 for (@OemNetworkPreferences.OemNetworkPreference final int pref
12489 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070012490 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
12491 throw new IllegalArgumentException(
12492 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
12493 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080012494 }
12495 }
12496 }
12497
12498 private void handleSetOemNetworkPreference(
12499 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012500 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080012501 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12502 if (DBG) {
12503 log("set OEM network preferences :" + preference.toString());
12504 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012505
James Mattiscb1e0362021-04-06 17:07:42 -070012506 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012507 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12508 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12509 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012510 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012511
12512 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012513 try {
12514 listener.onComplete();
12515 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012516 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012517 }
James Mattis45d81842021-01-10 14:24:24 -080012518 }
12519 }
12520
paulhu74128522021-09-28 02:29:03 +000012521 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012522 // Skip the requests which are set by other network preference. Because the uid range rules
12523 // should stay in netd.
12524 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012525 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012526 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012527 }
12528
James Mattis3ce3d3c2021-02-09 18:18:28 -080012529 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12530 ensureRunningOnConnectivityServiceThread();
12531 mDefaultNetworkRequests.addAll(nris);
12532 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12533 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012534 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012535 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12536 nrisToRegister.addAll(
12537 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12538 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012539 }
12540
12541 /**
12542 * All current requests that are tracking the default network need to be assessed as to whether
12543 * or not the current set of per-application default requests will be changing their default
12544 * network. If so, those requests will need to be updated so that they will send callbacks for
12545 * default network changes at the appropriate time. Additionally, those requests tracking the
12546 * default that were previously updated by this flow will need to be reassessed.
12547 * @return the nris which will need to be updated.
12548 */
12549 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12550 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12551 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12552 // same nri in the map's values for each of its NetworkRequest objects.
12553 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012554 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012555 // Include this nri if it is currently being tracked.
12556 if (isPerAppTrackedNri(nri)) {
12557 defaultCallbackRequests.add(nri);
12558 continue;
12559 }
12560 // We only track callbacks for requests tracking the default.
12561 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12562 continue;
12563 }
12564 // Include this nri if it will be tracked by the new per-app default requests.
12565 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012566 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012567 if (isNriGoingToBeTracked) {
12568 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012569 }
12570 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012571 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012572 }
12573
James Mattis3ce3d3c2021-02-09 18:18:28 -080012574 /**
12575 * Create nris for those network requests that are currently tracking the default network that
12576 * are being controlled by a per-application default.
12577 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12578 * foundation when creating the nri. Important items include the calling uid's original
12579 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12580 * requests are assumed to have already been validated as needing to be updated.
12581 * @return the Set of nris to use when registering network requests.
12582 */
12583 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12584 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12585 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12586 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12587 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012588 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012589
Chalard Jean9473c982021-07-29 20:03:04 +090012590 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012591 if (trackingNri == mDefaultRequest) {
12592 callbackRequestsToRegister.add(new NetworkRequestInfo(
12593 callbackRequest,
12594 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12595 continue;
12596 }
12597
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012598 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012599 callbackRequestsToRegister.add(new NetworkRequestInfo(
12600 callbackRequest,
12601 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012602 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012603 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012604 }
12605 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012606 }
12607
Chalard Jean17215832021-03-01 14:06:28 +090012608 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12609 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012610 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012611 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012612 }
12613 }
12614
James Mattis45d81842021-01-10 14:24:24 -080012615 /**
12616 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12617 */
12618 @VisibleForTesting
12619 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012620 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080012621 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012622 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080012623 final SparseArray<Set<Integer>> uids =
12624 createUidsFromOemNetworkPreferences(preference);
12625 for (int i = 0; i < uids.size(); i++) {
12626 final int key = uids.keyAt(i);
12627 final Set<Integer> value = uids.valueAt(i);
12628 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
12629 // No need to add an nri without any requests.
12630 if (0 == nri.mRequests.size()) {
12631 continue;
12632 }
12633 nris.add(nri);
12634 }
12635
12636 return nris;
12637 }
12638
12639 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
12640 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070012641 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080012642 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080012643 final List<UserHandle> users =
12644 mContext.getSystemService(UserManager.class).getUserHandles(true);
12645 if (null == users || users.size() == 0) {
12646 if (VDBG || DDBG) {
12647 log("No users currently available for setting the OEM network preference.");
12648 }
James Mattisb6b6a432021-06-01 22:30:36 -070012649 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080012650 }
James Mattis45d81842021-01-10 14:24:24 -080012651 for (final Map.Entry<String, Integer> entry :
12652 preference.getNetworkPreferences().entrySet()) {
12653 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070012654 // Add the rules for all users as this policy is device wide.
12655 for (final UserHandle user : users) {
12656 try {
12657 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
12658 if (!prefToUids.contains(pref)) {
12659 prefToUids.put(pref, new ArraySet<>());
12660 }
12661 prefToUids.get(pref).add(uid);
12662 } catch (PackageManager.NameNotFoundException e) {
12663 // Although this may seem like an error scenario, it is ok that uninstalled
12664 // packages are sent on a network preference as the system will watch for
12665 // package installations associated with this network preference and update
12666 // accordingly. This is done to minimize race conditions on app install.
12667 continue;
James Mattis45d81842021-01-10 14:24:24 -080012668 }
James Mattis45d81842021-01-10 14:24:24 -080012669 }
12670 }
James Mattisb6b6a432021-06-01 22:30:36 -070012671 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080012672 }
12673
12674 private NetworkRequestInfo createNriFromOemNetworkPreferences(
12675 @OemNetworkPreferences.OemNetworkPreference final int preference,
12676 @NonNull final Set<Integer> uids) {
12677 final List<NetworkRequest> requests = new ArrayList<>();
12678 // Requests will ultimately be evaluated by order of insertion therefore it matters.
12679 switch (preference) {
12680 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
12681 requests.add(createUnmeteredNetworkRequest());
12682 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070012683 requests.add(createDefaultInternetRequestForTransport(
12684 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080012685 break;
12686 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
12687 requests.add(createUnmeteredNetworkRequest());
12688 requests.add(createOemPaidNetworkRequest());
12689 break;
12690 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
12691 requests.add(createOemPaidNetworkRequest());
12692 break;
12693 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
12694 requests.add(createOemPrivateNetworkRequest());
12695 break;
James Mattisfa270db2021-05-31 17:11:10 -070012696 case OEM_NETWORK_PREFERENCE_TEST:
12697 requests.add(createUnmeteredNetworkRequest());
12698 requests.add(createTestNetworkRequest());
12699 requests.add(createDefaultRequest());
12700 break;
12701 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
12702 requests.add(createTestNetworkRequest());
12703 break;
James Mattis45d81842021-01-10 14:24:24 -080012704 default:
12705 // This should never happen.
12706 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
12707 + " called with invalid preference of " + preference);
12708 }
12709
James Mattisfa270db2021-05-31 17:11:10 -070012710 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090012711 for (final int uid : uids) {
12712 ranges.add(new UidRange(uid, uid));
12713 }
12714 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080012715 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080012716 }
12717
12718 private NetworkRequest createUnmeteredNetworkRequest() {
12719 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12720 .addCapability(NET_CAPABILITY_NOT_METERED)
12721 .addCapability(NET_CAPABILITY_VALIDATED);
12722 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
12723 }
12724
12725 private NetworkRequest createOemPaidNetworkRequest() {
12726 // NET_CAPABILITY_OEM_PAID is a restricted capability.
12727 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12728 .addCapability(NET_CAPABILITY_OEM_PAID)
12729 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12730 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12731 }
12732
12733 private NetworkRequest createOemPrivateNetworkRequest() {
12734 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
12735 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12736 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
12737 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12738 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12739 }
12740
12741 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070012742 final NetworkCapabilities netcap = new NetworkCapabilities();
12743 netcap.addCapability(NET_CAPABILITY_INTERNET);
12744 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
12745 return netcap;
12746 }
12747
12748 private NetworkRequest createTestNetworkRequest() {
12749 final NetworkCapabilities netcap = new NetworkCapabilities();
12750 netcap.clearAll();
12751 netcap.addTransportType(TRANSPORT_TEST);
12752 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080012753 }
James Mattis47db0582021-01-01 14:13:35 -080012754 }
markchien738ad912021-12-09 18:15:45 +080012755
Ken Chen24330172023-10-20 13:02:14 +080012756 @TargetApi(Build.VERSION_CODES.TIRAMISU)
markchien738ad912021-12-09 18:15:45 +080012757 @Override
Junyu Laidf210362023-10-24 02:47:50 +000012758 public void setDataSaverEnabled(final boolean enable) {
12759 enforceNetworkStackOrSettingsPermission();
12760 try {
12761 final boolean ret = mNetd.bandwidthEnableDataSaver(enable);
12762 if (!ret) {
12763 throw new IllegalStateException("Error when changing iptables: " + enable);
12764 }
12765 } catch (RemoteException e) {
12766 // Lack of permission or binder errors.
12767 throw new IllegalStateException(e);
12768 }
Ken Chen24330172023-10-20 13:02:14 +080012769
12770 try {
12771 mBpfNetMaps.setDataSaverEnabled(enable);
12772 } catch (ServiceSpecificException | UnsupportedOperationException e) {
12773 Log.e(TAG, "Failed to set data saver " + enable + " : " + e);
12774 }
Junyu Laidf210362023-10-24 02:47:50 +000012775 }
12776
12777 @Override
markchien738ad912021-12-09 18:15:45 +080012778 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
12779 enforceNetworkStackOrSettingsPermission();
12780
12781 try {
12782 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012783 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012784 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012785 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012786 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012787 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012788 throw new IllegalStateException(e);
12789 }
12790 }
12791
12792 @Override
12793 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
12794 enforceNetworkStackOrSettingsPermission();
12795
12796 try {
12797 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012798 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012799 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012800 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012801 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012802 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012803 throw new IllegalStateException(e);
12804 }
12805 }
markchiene1561fa2021-12-09 22:00:56 +080012806
Chalard Jeanc8fefb32023-09-05 21:41:13 +090012807 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
12808 throws PackageManager.NameNotFoundException {
12809 final PackageManager pm = mContext.getPackageManager();
12810 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
12811 if (appId < Process.FIRST_APPLICATION_UID) {
12812 throw new RuntimeException("Can't set package firewall rule for system app "
12813 + packageName + " with appId " + appId);
12814 }
12815 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
12816 final int uid = uh.getUid(appId);
12817 setUidFirewallRule(chain, uid, rule);
12818 }
12819 return appId;
12820 }
12821
markchiene1561fa2021-12-09 22:00:56 +080012822 @Override
markchien3c04e662022-03-22 16:29:56 +080012823 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080012824 enforceNetworkStackOrSettingsPermission();
12825
markchien3c04e662022-03-22 16:29:56 +080012826 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
12827 int firewallRule = getFirewallRuleType(chain, rule);
12828
12829 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
12830 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
12831 }
12832
markchiene1561fa2021-12-09 22:00:56 +080012833 try {
markchien3c04e662022-03-22 16:29:56 +080012834 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012835 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080012836 throw new IllegalStateException(e);
12837 }
12838 }
markchien98a6f952022-01-13 23:43:53 +080012839
Chalard Jeanc8fefb32023-09-05 21:41:13 +090012840 private int getPackageFirewallRule(final int chain, final String packageName)
12841 throws PackageManager.NameNotFoundException {
12842 final PackageManager pm = mContext.getPackageManager();
12843 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
12844 return getUidFirewallRule(chain, appId);
12845 }
12846
Motomu Utsumi900b8062023-01-19 16:16:49 +090012847 @Override
12848 public int getUidFirewallRule(final int chain, final int uid) {
12849 enforceNetworkStackOrSettingsPermission();
12850 return mBpfNetMaps.getUidRule(chain, uid);
12851 }
12852
markchien3c04e662022-03-22 16:29:56 +080012853 private int getFirewallRuleType(int chain, int rule) {
12854 final int defaultRule;
12855 switch (chain) {
12856 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000012857 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
12858 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000012859 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080012860 defaultRule = FIREWALL_RULE_ALLOW;
12861 break;
12862 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
12863 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
12864 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
12865 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
12866 defaultRule = FIREWALL_RULE_DENY;
12867 break;
12868 default:
12869 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
12870 }
12871 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
12872
12873 return rule;
12874 }
12875
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012876 private void closeSocketsForFirewallChainLocked(final int chain)
12877 throws ErrnoException, SocketException, InterruptedIOException {
Junyu Laie0031522023-08-29 18:32:57 +080012878 if (BpfNetMapsUtils.isFirewallAllowList(chain)) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012879 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
12880 // So, close all non-system socket owned by uids that are not explicitly allowed
12881 Set<Range<Integer>> ranges = new ArraySet<>();
12882 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
12883 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
12884 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
12885 } else {
12886 // Denylist means the firewall allows all by default, uids must be explicitly denied
12887 // So, close socket owned by uids that are explicitly denied
12888 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
12889 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
12890 }
12891 }
12892
markchien98a6f952022-01-13 23:43:53 +080012893 @Override
12894 public void setFirewallChainEnabled(final int chain, final boolean enable) {
12895 enforceNetworkStackOrSettingsPermission();
12896
12897 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012898 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012899 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080012900 throw new IllegalStateException(e);
12901 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012902
Chalard Jeandf29a852023-05-29 17:02:43 +090012903 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012904 try {
12905 closeSocketsForFirewallChainLocked(chain);
12906 } catch (ErrnoException | SocketException | InterruptedIOException e) {
12907 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
12908 }
12909 }
markchien98a6f952022-01-13 23:43:53 +080012910 }
12911
markchien00a0bed2022-01-13 23:46:13 +080012912 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012913 public boolean getFirewallChainEnabled(final int chain) {
12914 enforceNetworkStackOrSettingsPermission();
12915
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000012916 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012917 }
12918
12919 @Override
markchien00a0bed2022-01-13 23:46:13 +080012920 public void replaceFirewallChain(final int chain, final int[] uids) {
12921 enforceNetworkStackOrSettingsPermission();
12922
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000012923 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080012924 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080012925
12926 @Override
12927 public IBinder getCompanionDeviceManagerProxyService() {
12928 enforceNetworkStackPermission(mContext);
12929 return mCdmps;
12930 }
Chalard Jean2fb66f12023-08-25 12:50:37 +090012931
12932 @Override
12933 public IBinder getRoutingCoordinatorService() {
12934 enforceNetworkStackPermission(mContext);
12935 return mRoutingCoordinatorService;
12936 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070012937}