blob: da7229ce69afd154f8187636b429cf65c98c42aa [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000018
Haoyu Baib5da5752012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Mark Fasheh7c999d82023-05-04 20:23:11 +000020import static android.app.ActivityManager.UidFrozenStateChangedCallback.UID_FROZEN_STATE_FROZEN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090021import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
22import static android.content.pm.PackageManager.FEATURE_WATCH;
23import static android.content.pm.PackageManager.FEATURE_WIFI;
24import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
Chalard Jean9a396cc2018-02-21 18:43:54 +090025import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090026import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
27import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
28import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
29import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
33import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090034import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
35import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000036import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Aaron Huang9fe47be2021-06-08 13:11:45 +080037import static android.net.ConnectivityManager.CALLBACK_IP_CHANGED;
Jeff Sharkey971cd162011-08-29 16:02:57 -070038import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
markchien3c04e662022-03-22 16:29:56 +080039import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
40import static android.net.ConnectivityManager.FIREWALL_RULE_DEFAULT;
41import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090042import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090043import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090044import static android.net.ConnectivityManager.TYPE_MOBILE;
45import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
46import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
47import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
48import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
49import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
50import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
51import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
52import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
53import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070054import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090055import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070056import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090057import static android.net.ConnectivityManager.TYPE_WIFI;
58import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070059import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070060import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080061import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080062import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080063import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070064import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080065import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040066import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090067import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090068import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090070import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090071import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
72import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060073import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090074import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080075import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090076import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080077import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
78import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080079import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Chalard Jeanf95e2de2023-08-22 19:07:47 +090080import static android.net.NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090081import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080082import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
83import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080084import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
85import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
86import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090087import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090088import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060089import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070090import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080091import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090092import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070093import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
94import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070095import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080096import static android.os.Process.VPN_UID;
Patrick Rohr2857ac42022-01-21 14:58:16 +010097import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070098import static android.system.OsConstants.IPPROTO_TCP;
99import static android.system.OsConstants.IPPROTO_UDP;
Chalard Jeaneb663892023-10-07 15:17:07 +0900100
Xiao Ma60142372022-07-16 17:30:20 +0900101import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Junyu Lai4c6fe232023-04-11 11:33:46 +0800102import static com.android.net.module.util.PermissionUtils.checkAnyPermissionOf;
paulhu3ffffe72021-09-16 10:15:22 +0800103import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
104import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
105import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900106import static com.android.server.ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE;
Chalard Jeaneb663892023-10-07 15:17:07 +0900107
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800108import static java.util.Map.Entry;
109
Chalard Jean5b639762020-03-09 21:25:37 +0900110import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000111import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800112import android.annotation.Nullable;
Michael Groover73f69482023-01-27 11:01:25 -0600113import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800114import android.annotation.TargetApi;
Mark Fasheh7c999d82023-05-04 20:23:11 +0000115import android.app.ActivityManager;
116import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800117import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800118import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700119import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700120import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900121import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800122import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700123import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800124import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800125import android.content.ContentResolver;
126import android.content.Context;
127import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700128import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800129import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900130import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700131import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900132import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900133import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700134import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800135import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800136import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800137import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900138import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800139import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900140import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800141import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900142import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800143import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700144import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900145import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800146import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800147import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800148import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800149import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800150import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900151import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900152import android.net.INetworkMonitor;
153import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900154import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900155import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700156import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800157import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900158import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900159import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900160import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800161import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100162import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800163import android.net.NativeNetworkConfig;
164import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800165import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700166import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700167import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900168import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700169import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800170import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700171import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900172import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900173import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000174import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900175import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700176import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900177import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700178import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900179import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700180import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800181import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900182import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700183import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000184import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800185import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900186import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800187import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400188import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700189import android.net.QosCallbackException;
190import android.net.QosFilter;
191import android.net.QosSocketFilter;
192import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700193import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800194import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800195import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800196import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900197import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400198import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800199import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800200import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400201import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800202import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900203import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900204import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900205import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900206import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800207import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900208import android.net.networkstack.ModuleNetworkStackClient;
209import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900210import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800211import android.net.resolv.aidl.DnsHealthEventParcel;
212import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
213import android.net.resolv.aidl.Nat64PrefixEventParcel;
214import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900215import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900216import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800217import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800218import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800219import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700220import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000221import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800222import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700223import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700224import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800225import android.os.Looper;
226import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700227import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700228import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900229import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800230import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700231import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700232import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800233import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700234import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900235import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900236import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700237import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700238import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400239import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800240import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900241import android.stats.connectivity.MeteredState;
242import android.stats.connectivity.RequestType;
243import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900244import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700245import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700246import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700247import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800248import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900249import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000250import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600251import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900252import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900253import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700254import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700255import android.util.SparseIntArray;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900256import android.util.StatsEvent;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800257
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800258import androidx.annotation.RequiresApi;
259
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900260import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400261import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400262import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700263import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900264import com.android.internal.util.MessageUtils;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900265import com.android.metrics.ConnectionDurationForTransports;
266import com.android.metrics.ConnectionDurationPerTransports;
267import com.android.metrics.ConnectivitySampleMetricsHelper;
268import com.android.metrics.ConnectivityStateSample;
269import com.android.metrics.NetworkCountForTransports;
270import com.android.metrics.NetworkCountPerTransports;
271import com.android.metrics.NetworkDescription;
272import com.android.metrics.NetworkList;
273import com.android.metrics.NetworkRequestCount;
274import com.android.metrics.RequestCountForType;
Chiachang Wang62740142020-11-02 16:51:24 +0800275import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900276import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800277import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000278import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900279import com.android.net.module.util.BitUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900280import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900281import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100282import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900283import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
284import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900285import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800286import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800287import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100288import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000289import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800290import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
291import com.android.networkstack.apishim.ConstantsShim;
292import com.android.networkstack.apishim.common.BroadcastOptionsShim;
293import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900294import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900295import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000296import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900297import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800298import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800299import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900300import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900301import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900302import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500303import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700304import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900305import com.android.server.connectivity.FullScore;
Junyu Laif8dba342023-10-12 17:01:03 +0800306import com.android.server.connectivity.HandlerUtils;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900307import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900308import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000309import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100310import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700311import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900312import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700313import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600314import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900315import com.android.server.connectivity.NetworkNotificationManager;
316import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900317import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900318import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900319import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700320import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900321import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900322import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700323import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800324import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000325import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800326import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600327
Josh Gao461a1222020-06-16 15:58:11 -0700328import libcore.io.IoUtils;
329
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900330import org.xmlpull.v1.XmlPullParserException;
331
The Android Open Source Project28527d22009-03-03 19:31:44 -0800332import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100333import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900334import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800335import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900336import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700337import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700338import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900339import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900340import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700341import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700342import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700343import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700344import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800345import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900346import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800347import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700348import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700349import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700350import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700351import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900352import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700353import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900354import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600355import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900356import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600357import java.util.TreeSet;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900358import java.util.concurrent.TimeUnit;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900359import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800360
361/**
362 * @hide
363 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800364public class ConnectivityService extends IConnectivityManager.Stub
365 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900366 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800367
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900368 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900369 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900370 private static final String NETWORK_ARG = "networks";
371 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800372 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900373
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900374 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900375 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
376 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800377
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900378 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700379
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100380 /**
381 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
382 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800383 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100384 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
385 * (preferably via runtime resource overlays).
386 */
387 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
388 "http://connectivitycheck.gstatic.com/generate_204";
389
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700390 // TODO: create better separation between radio types and network types
391
Robert Greenwalt2034b912009-08-12 16:08:25 -0700392 // how long to wait before switching back to a radio's default network
393 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
394 // system property that can override the above value
395 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
396 "android.telephony.apn-restore";
397
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900398 // How long to wait before putting up a "This network doesn't have an Internet connection,
399 // connect anyway?" dialog after the user selects a network that doesn't validate.
400 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
401
Chalard Jean5fb43c72022-09-08 19:03:14 +0900402 // How long to wait before considering that a network is bad in the absence of any form
403 // of connectivity (valid, partial, captive portal). If none has been detected after this
404 // delay, the stack considers this network bad, which may affect how it's handled in ranking
405 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900406 // Timeout in case the "actively prefer bad wifi" feature is on
407 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
408 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900409 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900410
junyulai0ac374f2020-12-14 18:41:52 +0800411 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900412 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
413 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800414 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700415
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800416 // Delimiter used when creating the broadcast delivery group for sending
417 // CONNECTIVITY_ACTION broadcast.
418 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
419
he_won.hwang881307a2022-03-15 21:23:52 +0900420 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900421 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900422
Daniel Brightf9e945b2020-06-15 16:10:01 -0700423 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900424 @VisibleForTesting
425 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700426
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900427 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700428 @VisibleForTesting
429 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900430
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900431 @VisibleForTesting
432 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800433 @VisibleForTesting
434 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900435 // True if the cell radio of the device is capable of time-sharing.
436 @VisibleForTesting
437 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900438
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800439 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800440 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800441 private final int mReleasePendingIntentDelayMs;
442
Chalard Jean46bfbf02022-02-02 00:56:25 +0900443 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900444
Motomu Utsumif360aa62023-01-30 17:52:20 +0900445 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700446
Chalard Jean9473c982021-07-29 20:03:04 +0900447 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800448 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700449 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800450 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700451
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900452 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700453
junyulaif2c67e42018-08-07 19:50:45 +0800454 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000455 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
456 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800457 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900458 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800459
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900460 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900461 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000462 private final int mWakeUpMark;
463 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000464 // The Context is created for UserHandle.ALL.
465 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900466 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900467 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700468 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700469 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800470
Chenbo Feng15416292018-11-08 17:36:21 -0800471 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800472 protected IDnsResolver mDnsResolver;
473 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800474 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700475 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900476 private final NetworkStatsManager mStatsManager;
477 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800478 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700479
Benedict Wong493e04b2018-11-09 14:45:34 -0800480 /**
481 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
482 * instances.
483 */
484 @GuardedBy("mTNSLock")
485 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800486 private final CompanionDeviceManagerProxyService mCdmps;
Benedict Wong493e04b2018-11-09 14:45:34 -0800487
488 private final Object mTNSLock = new Object();
489
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700490 private String mCurrentTcpBufferSizes;
491
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900492 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000493 new Class[] {
494 ConnectivityService.class,
495 NetworkAgent.class,
496 NetworkAgentInfo.class,
497 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900498
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500499 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400500 // Tear down networks that have no chance (e.g. even if validated) of becoming
501 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500502 // all networks have been rematched against all NetworkRequests.
503 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400504 // Don't reap networks. This should be passed when some networks have not yet been
505 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500506 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900507 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500508
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900509 private enum UnneededFor {
510 LINGER, // Determine whether this network is unneeded and should be lingered.
511 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
512 }
513
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700514 /**
paulhuaa0743d2021-05-26 21:56:03 +0800515 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800516 * should have priority. The order is passed to netd which will use it together
517 * with UID ranges to generate the corresponding IP rule. This serves to
518 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800519 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800520 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000521 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800522 *
paulhu48291862021-07-14 14:53:57 +0800523 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
524 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800525 */
paulhu48291862021-07-14 14:53:57 +0800526 // Used when sending to netd to code for "no order".
527 static final int PREFERENCE_ORDER_NONE = 0;
528 // Order for requests that don't code for a per-app preference. As it is
529 // out of the valid range, the corresponding order should be
530 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800531 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800532 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800533 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800534 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
535 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800536 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800537 static final int PREFERENCE_ORDER_OEM = 10;
538 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800539 // See {@link #setProfileNetworkPreference}.
540 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800541 static final int PREFERENCE_ORDER_PROFILE = 20;
542 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800543 // better scores are connected.
544 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800545 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800546 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900547 // Preference order that signifies the network shouldn't be set as a default network for
548 // the UIDs, only give them access to it. TODO : replace this with a boolean
549 // in NativeUidRangeConfig
550 @VisibleForTesting
551 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
552 // Bound for the lowest valid preference order.
553 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800554
555 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700556 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700557 * from one net to another. Clear happens when we get a new
558 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
559 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700560 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700561 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700562
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700563 /**
564 * used internally to reload global proxy settings
565 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700566 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700567
Robert Greenwalt34848c02011-03-25 13:09:25 -0700568 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400569 * PAC manager has received new port.
570 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800571 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400572
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700573 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900574 * used internally when registering NetworkProviders
575 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700576 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900577 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700578
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700579 /**
580 * used internally when registering NetworkAgents
581 * obj = Messenger
582 */
583 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
584
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700585 /**
586 * used to add a network request
587 * includes a NetworkRequestInfo
588 */
589 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
590
591 /**
592 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900593 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700594 * cancel it.
595 * includes a NetworkRequestInfo
596 */
597 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
598
599 /**
600 * used to add a network listener - no request
601 * includes a NetworkRequestInfo
602 */
603 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
604
605 /**
606 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400607 * arg1 = UID of caller
608 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700609 */
610 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
611
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700612 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900613 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700614 * obj = Messenger
615 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900616 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700617
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700618 /**
619 * used internally to expire a wakelock when transitioning
620 * from one net to another. Expire happens when we fail to find
621 * a new network (typically after 1 minute) -
622 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
623 * a replacement network.
624 */
625 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
626
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700627 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800628 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400629 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800630 */
631 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
632
633 /**
634 * used to remove a pending intent and its associated network request.
635 * arg1 = UID of caller
636 * obj = PendingIntent
637 */
638 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
639
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900640 /**
641 * used to specify whether a network should be used even if unvalidated.
642 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
643 * arg2 = whether to remember this choice in the future (1 or 0)
644 * obj = network
645 */
646 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
647
648 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700649 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900650 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700651 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900652
Paul Jensenc8873fc2015-06-17 14:15:39 -0400653 /**
654 * used to add a network listener with a pending intent
655 * obj = NetworkRequestInfo
656 */
657 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
658
Hugo Benichid6b510a2017-04-06 17:22:18 +0900659 /**
660 * used to specify whether a network should not be penalized when it becomes unvalidated.
661 */
662 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
663
664 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700665 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900666 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700667 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900668
Erik Kline31b4a9e2018-01-11 21:07:29 +0900669 // Handle changes in Private DNS settings.
670 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
671
dalyk1720e542018-03-05 12:42:22 -0500672 // Handle private DNS validation status updates.
673 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
674
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900675 /**
676 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
677 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800678 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
679 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
680 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900681 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900682 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900683
684 /**
685 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
686 * config was resolved.
687 * obj = PrivateDnsConfig
688 * arg2 = netid
689 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900690 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900691
692 /**
693 * Request ConnectivityService display provisioning notification.
694 * arg1 = Whether to make the notification visible.
695 * arg2 = NetID.
696 * obj = Intent to be launched when notification selected by user, null if !arg1.
697 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900698 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900699
700 /**
lucaslin2240ef62019-03-12 13:08:03 +0800701 * Used to specify whether a network should be used even if connectivity is partial.
702 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
703 * false)
704 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
705 * obj = network
706 */
lucaslin444d43a2020-02-20 16:56:59 +0800707 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800708
709 /**
lucasline117e2e2019-10-22 18:27:33 +0800710 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
711 * Both of the arguments are bitmasks, and the value of bits come from
712 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900713 * arg1 = unused
714 * arg2 = netId
715 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800716 */
lucaslin444d43a2020-02-20 16:56:59 +0800717 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800718
719 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900720 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
721 * arg1 = unused
722 * arg2 = netId
723 * obj = captive portal data
724 */
lucaslin444d43a2020-02-20 16:56:59 +0800725 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900726
727 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900728 * Used by setRequireVpnForUids.
729 * arg1 = whether the specified UID ranges are required to use a VPN.
730 * obj = Array of UidRange objects.
731 */
732 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
733
734 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900735 * Used internally when setting the default networks for OemNetworkPreferences.
736 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800737 */
738 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
739
740 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800741 * Used to indicate the system default network becomes active.
742 */
743 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
744
745 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900746 * Used internally when setting a network preference for a user profile.
747 * obj = Pair<ProfileNetworkPreference, Listener>
748 */
749 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
750
751 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000752 * Event to specify that reasons for why an uid is blocked changed.
753 * arg1 = uid
754 * arg2 = blockedReasons
755 */
756 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
757
758 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900759 * Event to register a new network offer
760 * obj = NetworkOffer
761 */
762 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
763
764 /**
765 * Event to unregister an existing network offer
766 * obj = INetworkOfferCallback
767 */
768 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
769
770 /**
paulhu51f77dc2021-06-07 02:34:20 +0000771 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
772 */
773 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
774
775 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800776 * Event to set temporary allow bad wifi within a limited time to override
777 * {@code config_networkAvoidBadWifi}.
778 */
779 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
780
781 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100782 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
783 */
784 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
785
786 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900787 * The initial evaluation period is over for this network.
788 *
789 * If no form of connectivity has been found on this network (valid, partial, captive portal)
790 * then the stack will now consider it to have been determined bad.
791 */
792 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
793
794 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000795 * Used internally when the user does not want the network from captive portal app.
796 * obj = Network
797 */
798 private static final int EVENT_USER_DOES_NOT_WANT = 58;
799
800 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000801 * Event to set VPN as preferred network for specific apps.
802 * obj = VpnNetworkPreferenceInfo
803 */
804 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
805
806 /**
chiachangwange0192a72023-02-06 13:25:01 +0000807 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
808 */
809 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
810
811 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000812 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
813 */
814 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
815
816 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900817 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
818 * should be shown.
819 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900820 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900821
822 /**
823 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
824 * should be hidden.
825 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900826 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900827
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800828 /**
829 * The maximum alive time to allow bad wifi configuration for testing.
830 */
831 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
832
Patrick Rohr2857ac42022-01-21 14:58:16 +0100833 /**
chiachangwange0192a72023-02-06 13:25:01 +0000834 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
835 * testing.
836 */
837 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
838
839 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100840 * The priority of the tc police rate limiter -- smaller value is higher priority.
841 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
842 */
843 private static final short TC_PRIO_POLICE = 1;
844
845 /**
846 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
847 */
848 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700849 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100850
Hugo Benichi47011212017-03-30 10:46:05 +0900851 private static String eventName(int what) {
852 return sMagicDecoderRing.get(what, Integer.toString(what));
853 }
854
paulhua10d8212020-11-10 15:32:56 +0800855 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900856 final DnsResolverServiceManager dsm = context.getSystemService(
857 DnsResolverServiceManager.class);
858 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800859 }
860
Cody Kesting73708bf2019-12-18 10:57:50 -0800861 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900862 @VisibleForTesting
863 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700864 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700865 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700866 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700867 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800868 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
869 @VisibleForTesting
870 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
871
Erik Kline32120082017-12-13 19:40:49 +0900872 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900873 @VisibleForTesting
874 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700875
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400876 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800877 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400878
Chalard Jean46bfbf02022-02-02 00:56:25 +0900879 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800880 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700881
Chalard Jean5d70ba42018-06-07 16:44:04 +0900882 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
883 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800884 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400885
Erik Kline05f2b402015-04-30 12:58:40 +0900886 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700887
Chalard Jean46bfbf02022-02-02 00:56:25 +0900888 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400889
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700890 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900891 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700892
Valentin Iftime9fa35092019-09-24 13:32:13 +0200893 private Set<String> mWolSupportedInterfaces;
894
Roshan Pius08c94fb2020-01-16 12:17:17 -0800895 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800896 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800897 private final AppOpsManager mAppOpsManager;
898
899 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400900
chiachangwang3d60bac2023-01-17 14:38:08 +0000901 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900902 private final QosCallbackTracker mQosCallbackTracker;
903 private final NetworkNotificationManager mNotifier;
904 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900905
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700906 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800907 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700908
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900909 // Sequence number for NetworkProvider IDs.
910 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
911 NetworkProvider.FIRST_PROVIDER_ID);
912
Erik Klineedf878b2015-07-09 18:24:03 +0900913 // NetworkRequest activity String log entries.
914 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
915 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
916
Hugo Benichid159fdd2016-07-11 11:05:12 +0900917 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900918 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900919 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
920
Hugo Benichi47011212017-03-30 10:46:05 +0900921 private static final int MAX_WAKELOCK_LOGS = 20;
922 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900923 private int mTotalWakelockAcquisitions = 0;
924 private int mTotalWakelockReleases = 0;
925 private long mTotalWakelockDurationMs = 0;
926 private long mMaxWakelockDurationMs = 0;
927 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900928
Hugo Benichi208c0102016-07-28 17:53:06 +0900929 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900930
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700931 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900932 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700933
Erik Kline95ecfee2016-10-02 18:02:14 +0900934 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900935 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900936
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900937 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800938 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
939 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800940
Patrick Rohr2857ac42022-01-21 14:58:16 +0100941 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
942 // configured via {@link
943 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
944 // Only the handler thread is allowed to access this field.
945 private long mIngressRateLimit = -1;
946
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900947 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
948 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900949 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900950 @GuardedBy("mSelfCertifiedCapabilityCache")
951 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
952 mSelfCertifiedCapabilityCache = new HashMap<>();
953
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900954 // Flag to enable the feature of closing frozen app sockets.
955 private final boolean mDestroyFrozenSockets;
956
957 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
958 private final boolean mDelayDestroyFrozenSockets;
959
960 // Uids that ConnectivityService is pending to close sockets of.
961 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
962
Robert Greenwalt802c1102014-06-02 15:32:02 -0700963 /**
964 * Implements support for the legacy "one network per network type" model.
965 *
966 * We used to have a static array of NetworkStateTrackers, one for each
967 * network type, but that doesn't work any more now that we can have,
968 * for example, more that one wifi network. This class stores all the
969 * NetworkAgentInfo objects that support a given type, but the legacy
970 * API will only see the first one.
971 *
972 * It serves two main purposes:
973 *
974 * 1. Provide information about "the network for a given type" (since this
975 * API only supports one).
976 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
977 * the first network for a given type changes, or if the default network
978 * changes.
979 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900980 @VisibleForTesting
981 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900982
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900983 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900984 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900985
Robert Greenwalt802c1102014-06-02 15:32:02 -0700986 /**
987 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
988 * Each list holds references to all NetworkAgentInfos that are used to
989 * satisfy requests for that network type.
990 *
991 * This array is built out at startup such that an unsupported network
992 * doesn't get an ArrayList instance, making this a tristate:
993 * unsupported, supported but not active and active.
994 *
995 * The actual lists are populated when we scan the network types that
996 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900997 *
998 * Threading model:
999 * - addSupportedType() is only called in the constructor
1000 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1001 * They are therefore not thread-safe with respect to each other.
1002 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1003 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001004 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001005 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001006 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001007 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001008 @NonNull
1009 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001010
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001011 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1012 // an entry have no timer (equivalent to -1). Lazily loaded.
1013 @NonNull
1014 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1015
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001016 LegacyTypeTracker(@NonNull ConnectivityService service) {
1017 mService = service;
1018 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001019 }
1020
Chiachang Wang3bc52762021-11-25 14:17:57 +08001021 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1022 // addressed.
1023 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001024 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1025 final PackageManager pm = ctx.getPackageManager();
1026 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1027 addSupportedType(TYPE_WIFI);
1028 }
1029 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1030 addSupportedType(TYPE_WIFI_P2P);
1031 }
1032 if (tm.isDataCapable()) {
1033 // Telephony does not have granular support for these types: they are either all
1034 // supported, or none is supported
1035 addSupportedType(TYPE_MOBILE);
1036 addSupportedType(TYPE_MOBILE_MMS);
1037 addSupportedType(TYPE_MOBILE_SUPL);
1038 addSupportedType(TYPE_MOBILE_DUN);
1039 addSupportedType(TYPE_MOBILE_HIPRI);
1040 addSupportedType(TYPE_MOBILE_FOTA);
1041 addSupportedType(TYPE_MOBILE_IMS);
1042 addSupportedType(TYPE_MOBILE_CBS);
1043 addSupportedType(TYPE_MOBILE_IA);
1044 addSupportedType(TYPE_MOBILE_EMERGENCY);
1045 }
1046 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1047 addSupportedType(TYPE_BLUETOOTH);
1048 }
1049 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1050 // TYPE_PROXY is only used on Wear
1051 addSupportedType(TYPE_PROXY);
1052 }
1053 // Ethernet is often not specified in the configs, although many devices can use it via
1054 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001055 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001056 addSupportedType(TYPE_ETHERNET);
1057 }
1058
1059 // Always add TYPE_VPN as a supported type
1060 addSupportedType(TYPE_VPN);
1061 }
1062
1063 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001064 if (mTypeLists[type] != null) {
1065 throw new IllegalStateException(
1066 "legacy list for type " + type + "already initialized");
1067 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001068 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001069 }
1070
Robert Greenwalt802c1102014-06-02 15:32:02 -07001071 public boolean isTypeSupported(int type) {
1072 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1073 }
1074
1075 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001076 synchronized (mTypeLists) {
1077 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1078 return mTypeLists[type].get(0);
1079 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001080 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001081 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001082 }
1083
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001084 public int getRestoreTimerForType(int type) {
1085 synchronized (mTypeLists) {
1086 if (mRestoreTimers == null) {
1087 mRestoreTimers = loadRestoreTimers();
1088 }
1089 return mRestoreTimers.getOrDefault(type, -1);
1090 }
1091 }
1092
1093 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1094 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001095 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001096 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1097 for (final String config : configs) {
1098 final String[] splits = TextUtils.split(config, ",");
1099 if (splits.length != 2) {
1100 logwtf("Invalid restore timer token count: " + config);
1101 continue;
1102 }
1103 try {
1104 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1105 } catch (NumberFormatException e) {
1106 logwtf("Invalid restore timer number format: " + config, e);
1107 }
1108 }
1109 return ret;
1110 }
1111
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001112 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001113 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001114 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001115 log("Sending " + state
1116 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001117 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001118 }
1119 }
1120
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001121 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1122 // network type, to preserve previous behaviour.
1123 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1124 if (vpnNai != mService.getLegacyLockdownNai()) return;
1125
1126 if (vpnNai.declaredUnderlyingNetworks == null
1127 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1128 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1129 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1130 return;
1131 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001132 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001133 vpnNai.declaredUnderlyingNetworks[0]);
1134 if (underlyingNai == null) return;
1135
1136 final int type = underlyingNai.networkInfo.getType();
1137 final DetailedState state = DetailedState.CONNECTED;
1138 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1139 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1140 }
1141
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001142 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001143 public void add(int type, NetworkAgentInfo nai) {
1144 if (!isTypeSupported(type)) {
1145 return; // Invalid network type.
1146 }
1147 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1148
1149 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1150 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001151 return;
1152 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001153 synchronized (mTypeLists) {
1154 list.add(nai);
1155 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001156
Chalard Jean5b409c72021-02-04 13:12:59 +09001157 // Send a broadcast if this is the first network of its type or if it's the default.
1158 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001159
1160 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1161 // to preserve previous behaviour.
1162 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001163 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001164 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1165 mService.sendLegacyNetworkBroadcast(nai, state, type);
1166 }
1167
1168 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1169 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001170 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001171 }
1172
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001173 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001174 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001175 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1176 if (list == null || list.isEmpty()) {
1177 return;
1178 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001179 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001180
Hugo Benichi389633f2016-06-21 09:48:07 +09001181 synchronized (mTypeLists) {
1182 if (!list.remove(nai)) {
1183 return;
1184 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001185 }
1186
Lorenzo Colitti49767722015-05-01 00:30:10 +09001187 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001188 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1189 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001190 }
1191
1192 if (!list.isEmpty() && wasFirstNetwork) {
1193 if (DBG) log("Other network available for type " + type +
1194 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001195 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001196 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001197 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001198 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001199 }
1200 }
1201
1202 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001203 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1204 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001205 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001206 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001207 }
1208 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001209
Chalard Jean46bfbf02022-02-02 00:56:25 +09001210 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001211 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001212 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001213 final DetailedState state = nai.networkInfo.getDetailedState();
1214 for (int type = 0; type < mTypeLists.length; type++) {
1215 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001216 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001217 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001218 if (isFirst || contains && isDefault) {
1219 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001220 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001221 }
1222 }
1223 }
1224
Robert Greenwalt94e22142014-07-30 16:31:24 -07001225 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001226 pw.println("mLegacyTypeTracker:");
1227 pw.increaseIndent();
1228 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001229 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001230 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001231 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001232 pw.println();
1233 pw.println("Current state:");
1234 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001235 synchronized (mTypeLists) {
1236 for (int type = 0; type < mTypeLists.length; type++) {
1237 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1238 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001239 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001240 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001241 }
1242 }
1243 pw.decreaseIndent();
1244 pw.decreaseIndent();
1245 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001246 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001247 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001248 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001249
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001250 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001251 /**
1252 * Helper class which parses out priority arguments and dumps sections according to their
1253 * priority. If priority arguments are omitted, function calls the legacy dump command.
1254 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001255 private class LocalPriorityDump {
1256 private static final String PRIORITY_ARG = "--dump-priority";
1257 private static final String PRIORITY_ARG_HIGH = "HIGH";
1258 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
Junyu Laif8dba342023-10-12 17:01:03 +08001259 private static final int DUMPSYS_DEFAULT_TIMEOUT_MS = 10_000;
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001260
1261 LocalPriorityDump() {}
1262
1263 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
Junyu Laif8dba342023-10-12 17:01:03 +08001264 if (!HandlerUtils.runWithScissors(mHandler, () -> {
1265 doDump(fd, pw, new String[]{DIAG_ARG});
1266 doDump(fd, pw, new String[]{SHORT_ARG});
1267 }, DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1268 pw.println("dumpHigh timeout");
1269 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001270 }
1271
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001272 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
Junyu Laif8dba342023-10-12 17:01:03 +08001273 if (!HandlerUtils.runWithScissors(mHandler, () -> doDump(fd, pw, args),
1274 DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1275 pw.println("dumpNormal timeout");
1276 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001277 }
1278
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001279 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1280 if (args == null) {
1281 dumpNormal(fd, pw, args);
1282 return;
1283 }
1284
1285 String priority = null;
1286 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1287 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1288 argIndex++;
1289 priority = args[argIndex];
1290 }
1291 }
1292
1293 if (PRIORITY_ARG_HIGH.equals(priority)) {
1294 dumpHigh(fd, pw);
1295 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1296 dumpNormal(fd, pw, args);
1297 } else {
1298 // ConnectivityService publishes binder service using publishBinderService() with
1299 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001300 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1301 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001302 // TODO: Integrate into signal dump.
1303 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001304 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001305 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001306 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001307
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001308 /**
1309 * Dependencies of ConnectivityService, for injection in tests.
1310 */
1311 @VisibleForTesting
1312 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001313 public int getCallingUid() {
1314 return Binder.getCallingUid();
1315 }
1316
Chalard Jeandf29a852023-05-29 17:02:43 +09001317 public boolean isAtLeastS() {
1318 return SdkLevel.isAtLeastS();
1319 }
1320
1321 public boolean isAtLeastT() {
1322 return SdkLevel.isAtLeastT();
1323 }
1324
1325 public boolean isAtLeastU() {
1326 return SdkLevel.isAtLeastU();
1327 }
1328
Chalard Jeaneb663892023-10-07 15:17:07 +09001329 public boolean isAtLeastV() {
1330 return SdkLevel.isAtLeastV();
1331 }
1332
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001333 /**
1334 * Get system properties to use in ConnectivityService.
1335 */
1336 public MockableSystemProperties getSystemProperties() {
1337 return new MockableSystemProperties();
1338 }
1339
1340 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001341 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1342 */
1343 public ConnectivityResources getResources(@NonNull Context ctx) {
1344 return new ConnectivityResources(ctx);
1345 }
1346
1347 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001348 * Create a HandlerThread to use in ConnectivityService.
1349 */
1350 public HandlerThread makeHandlerThread() {
1351 return new HandlerThread("ConnectivityServiceThread");
1352 }
1353
1354 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001355 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001356 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001357 public NetworkStackClientBase getNetworkStack() {
1358 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001359 }
1360
1361 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001362 * @see ProxyTracker
1363 */
1364 public ProxyTracker makeProxyTracker(@NonNull Context context,
1365 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001366 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001367 }
1368
1369 /**
1370 * @see NetIdManager
1371 */
1372 public NetIdManager makeNetIdManager() {
1373 return new NetIdManager();
1374 }
1375
1376 /**
1377 * @see NetworkUtils#queryUserAccess(int, int)
1378 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001379 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1380 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001381 }
1382
1383 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001384 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1385 * requires CAP_NET_ADMIN, which the unit tests do not have.
1386 */
1387 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1388 InetSocketAddress remote) {
1389 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1390 }
1391
1392 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001393 * @see MultinetworkPolicyTracker
1394 */
1395 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1396 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1397 return new MultinetworkPolicyTracker(c, h, r);
1398 }
1399
Aaron Huang330a4c02020-10-27 03:36:19 +08001400 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001401 * @see AutomaticOnOffKeepaliveTracker
1402 */
1403 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1404 @NonNull Context c, @NonNull Handler h) {
1405 return new AutomaticOnOffKeepaliveTracker(c, h);
1406 }
1407
1408 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001409 * @see BatteryStatsManager
1410 */
1411 public void reportNetworkInterfaceForTransports(Context context, String iface,
1412 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001413 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001414 context.getSystemService(BatteryStatsManager.class);
1415 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1416 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001417
1418 public boolean getCellular464XlatEnabled() {
1419 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1420 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001421
1422 /**
1423 * @see PendingIntent#intentFilterEquals
1424 */
1425 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1426 return a.intentFilterEquals(b);
1427 }
1428
1429 /**
1430 * @see LocationPermissionChecker
1431 */
1432 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1433 return new LocationPermissionChecker(context);
1434 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001435
1436 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001437 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001438 *
1439 * This method returns null in versions before T, where carrier privilege
1440 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001441 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001442 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001443 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1444 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001445 if (isAtLeastT()) {
Chalard Jean84dfa9f2023-01-30 11:23:20 +09001446 return new CarrierPrivilegeAuthenticator(context, this, tm);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001447 } else {
1448 return null;
1449 }
1450 }
1451
1452 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001453 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001454 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001455 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001456 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001457 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001458
1459 /**
1460 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001461 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001462 * @return BpfNetMaps implementation.
1463 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001464 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1465 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001466 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001467
1468 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001469 * @see ClatCoordinator
1470 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001471 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001472 public ClatCoordinator getClatCoordinator(INetd netd) {
1473 return new ClatCoordinator(
1474 new ClatCoordinator.Dependencies() {
1475 @NonNull
1476 public INetd getNetd() {
1477 return netd;
1478 }
1479 });
1480 }
1481
1482 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001483 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1484 */
1485 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1486 final InterfaceParams params = InterfaceParams.getByName(iface);
1487 if (params == null) {
1488 // the interface might have disappeared.
1489 logw("Failed to get interface params for interface " + iface);
1490 return;
1491 }
1492 try {
1493 // converting rateInBytesPerSecond from long to int is safe here because the
1494 // setting's range is limited to INT_MAX.
1495 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001496 Log.i(TAG,
1497 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001498 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1499 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1500 } catch (IOException e) {
1501 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1502 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1503 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1504 + ") failure: ", e);
1505 }
1506 }
1507
1508 /**
1509 * Wraps {@link TcUtils#tcFilterDelDev}
1510 */
1511 public void disableIngressRateLimit(String iface) {
1512 final InterfaceParams params = InterfaceParams.getByName(iface);
1513 if (params == null) {
1514 // the interface might have disappeared.
1515 logw("Failed to get interface params for interface " + iface);
1516 return;
1517 }
1518 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001519 Log.i(TAG,
1520 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001521 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1522 } catch (IOException e) {
1523 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1524 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1525 }
1526 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001527
1528 /**
1529 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1530 */
1531 // TODO: when available in all active branches:
1532 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1533 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1534 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1535 return BroadcastOptionsShimImpl.newInstance(options);
1536 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001537
1538 /**
1539 * Wrapper method for
1540 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1541 *
1542 * @param changeId The ID of the compatibility change in question.
1543 * @param packageName The package name of the app in question.
1544 * @param user The user that the operation is done for.
1545 * @return {@code true} if the change is enabled for the specified package.
1546 */
1547 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1548 @NonNull final UserHandle user) {
1549 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1550 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001551
1552 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001553 * As above but with a UID.
1554 * @see CompatChanges#isChangeEnabled(long, int)
1555 */
1556 public boolean isChangeEnabled(final long changeId, final int uid) {
1557 return CompatChanges.isChangeEnabled(changeId, uid);
1558 }
1559
1560 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001561 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1562 *
1563 * @param ranges target uid ranges
1564 * @param exemptUids uids to skip close socket
1565 */
1566 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1567 @NonNull final Set<Integer> exemptUids)
1568 throws SocketException, InterruptedIOException, ErrnoException {
1569 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1570 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001571
1572 /**
1573 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1574 *
1575 * @param ownerUids target uids to close sockets
1576 */
1577 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1578 throws SocketException, InterruptedIOException, ErrnoException {
1579 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1580 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001581
1582 /**
1583 * Schedule the evaluation timeout.
1584 *
1585 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1586 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1587 * of these events happen, this time will run out, after which the network is considered
1588 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1589 * on this network and considers it won't provide connectivity. In particular, that means
1590 * it's when the system prefers it to cell if it's wifi and configuration says it should
1591 * prefer bad wifi to cell.
1592 */
1593 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1594 @NonNull final Network network, final long delayMs) {
1595 handler.sendMessageDelayed(
1596 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1597 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001598 }
1599
junyulaie7c7d2a2021-01-26 15:29:15 +08001600 public ConnectivityService(Context context) {
1601 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001602 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1603 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001604 }
1605
1606 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001607 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1608 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001609 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001610
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001611 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001612 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001613 mSystemProperties = mDeps.getSystemProperties();
1614 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001615 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001616 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001617 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1618 // Pass limit - 1 to maintain backward compatibility.
1619 // TODO: Remove the workaround.
1620 mNetworkRequestCounter =
1621 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1622 mSystemNetworkRequestCounter =
1623 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001624
Hugo Benichi208c0102016-07-28 17:53:06 +09001625 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001626 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1627 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001628 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001629 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001630 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001631 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1632 mDefaultNetworkRequests.add(mDefaultRequest);
1633 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001634
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001635 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001636 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001637
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001638 // The default WiFi request is a background request so that apps using WiFi are
1639 // migrated to a better network (typically ethernet) when one comes up, instead
1640 // of staying on WiFi forever.
1641 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1642 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1643
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001644 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1645 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1646 NetworkRequest.Type.BACKGROUND_REQUEST);
1647
Chalard Jean0702f982021-09-16 21:50:07 +09001648 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1649 // TODO: Consider making the timer customizable.
1650 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1651 mCellularRadioTimesharingCapable =
1652 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1653
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001654 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1655 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1656
1657 if (SdkLevel.isAtLeastU()) {
1658 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1659 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1660 final int defaultUMarkMask = 0x80000000; // u32
1661
1662 if ((mark == 0) || (mask == 0)) {
1663 // simply treat unset/disabled as the default U value
1664 mark = defaultUMarkMask;
1665 mask = defaultUMarkMask;
1666 }
1667 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1668 // invalid device overlay settings
1669 throw new IllegalArgumentException(
1670 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1671 }
1672 }
1673
1674 mWakeUpMark = mark;
1675 mWakeUpMask = mask;
1676
Paul Hu51f816b2022-08-11 14:43:47 +00001677 mNetd = netd;
1678 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001679 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001680 mPermissionMonitor =
1681 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001682 mHandlerThread.start();
1683 mHandler = new InternalHandler(mHandlerThread.getLooper());
1684 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001685 mConnectivityDiagnosticsHandler =
1686 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001687
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001688 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001689 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001690
junyulaie7c7d2a2021-01-26 15:29:15 +08001691 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001692 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001693 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001694 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001695
Wink Saville32506bc2013-06-29 21:10:57 -07001696 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001697 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001698 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001699 mCarrierPrivilegeAuthenticator =
1700 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001701
Sudheer Shanka9967d462021-03-18 19:09:25 +00001702 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001703 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1704 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001705 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001706
1707 final PowerManager powerManager = (PowerManager) context.getSystemService(
1708 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001709 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001710 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001711
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001712 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1713 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001714 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001715 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001716 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001717 mProtectedNetworks.add(p);
1718 } else {
1719 if (DBG) loge("Ignoring protectedNetwork " + p);
1720 }
1721 }
1722
soma, kawata29444ae2019-05-23 09:30:40 +09001723 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1724
James Mattis02220e22021-03-13 19:27:21 -08001725 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001726 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001727 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001728 final IntentFilter userIntentFilter = new IntentFilter();
1729 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1730 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1731 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1732 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001733
James Mattis02220e22021-03-13 19:27:21 -08001734 // Listen to package add/removes for netd
1735 final IntentFilter packageIntentFilter = new IntentFilter();
1736 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1737 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1738 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1739 packageIntentFilter.addDataScheme("package");
1740 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001741 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001742
Motomu Utsumi1e51a642023-07-18 15:11:41 +09001743 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001744
Chalard Jean46bfbf02022-02-02 00:56:25 +09001745 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001746 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001747 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001748 } catch (RemoteException | ServiceSpecificException e) {
1749 loge("Error registering event listener :" + e);
1750 }
1751
Erik Kline05f2b402015-04-30 12:58:40 +09001752 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1753 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001754
chiachangwang7c17c282023-02-02 05:58:59 +00001755 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001756 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001757 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001758
1759 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001760 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001761 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1762 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001763 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001764 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1765 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001766
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001767 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001768 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001769 mNetworkRanker =
1770 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1771
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001772 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001773
Chiachang Wangc1215d32020-10-20 15:38:58 +08001774 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001775 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001776
Chalard Jean28018572020-12-21 18:36:52 +09001777 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1778 // request that doesn't allow fallback to the default network. It should never be visible
1779 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1780 // arguments like the handler or the DnsResolver.
1781 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001782 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001783 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001784 new NetworkInfo(TYPE_NONE, 0, "", ""),
Anton Kulakov6eea22b2023-10-13 15:04:01 +00001785 new LinkProperties(), new NetworkCapabilities(),
Chalard Jean28018572020-12-21 18:36:52 +09001786 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001787 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1788 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001789
1790 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001791 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1792 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1793 // Even if it could, running on S would at least require mocking out the BPF map,
1794 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1795 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001796 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001797 mDscpPolicyTracker = new DscpPolicyTracker();
1798 }
Tyler Wear72388212021-09-09 14:49:02 -07001799 } catch (ErrnoException e) {
1800 loge("Unable to create DscpPolicyTracker");
1801 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001802
1803 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1804 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001805
Chalard Jeandf29a852023-05-29 17:02:43 +09001806 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001807 mCdmps = new CompanionDeviceManagerProxyService(context);
1808 } else {
1809 mCdmps = null;
1810 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001811
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001812 mDestroyFrozenSockets = mDeps.isAtLeastU()
1813 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
1814 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1815 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
1816 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001817 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1818 new UidFrozenStateChangedCallback() {
1819 @Override
1820 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1821 if (uids.length != frozenStates.length) {
1822 Log.wtf(TAG, "uids has length " + uids.length
1823 + " but frozenStates has length " + frozenStates.length);
1824 return;
1825 }
1826
1827 final UidFrozenStateChangedArgs args =
1828 new UidFrozenStateChangedArgs(uids, frozenStates);
1829
1830 mHandler.sendMessage(
1831 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1832 }
1833 };
1834
1835 final ActivityManager activityManager =
1836 mContext.getSystemService(ActivityManager.class);
1837 activityManager.registerUidFrozenStateChangedCallback(
1838 (Runnable r) -> r.run(), frozenStateChangedCallback);
1839 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001840 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001841
Xiao Ma0a171c02022-01-23 16:14:51 +00001842 /**
1843 * Check whether or not the device supports Ethernet transport.
1844 */
1845 public static boolean deviceSupportsEthernet(final Context context) {
1846 final PackageManager pm = context.getPackageManager();
1847 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1848 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1849 }
1850
Chalard Jean46adcf32018-04-18 20:18:38 +09001851 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001852 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1853 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001854 }
1855
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001856 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1857 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001858 final NetworkCapabilities netCap = new NetworkCapabilities();
1859 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001860 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001861 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001862 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001863 return netCap;
1864 }
1865
James Mattis45d81842021-01-10 14:24:24 -08001866 private NetworkRequest createDefaultRequest() {
1867 return createDefaultInternetRequestForTransport(
1868 TYPE_NONE, NetworkRequest.Type.REQUEST);
1869 }
1870
lucaslin3ba7cc22022-12-19 02:35:33 +00001871 private NetworkRequest createVpnRequest() {
1872 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1873 .withoutDefaultCapabilities()
1874 .addTransportType(TRANSPORT_VPN)
1875 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1876 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1877 .build();
1878 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1879 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1880 }
1881
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001882 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001883 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001884 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001885 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001886 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001887 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001888 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001889 netCap.addTransportType(transportType);
1890 }
James Mattis45d81842021-01-10 14:24:24 -08001891 return createNetworkRequest(type, netCap);
1892 }
1893
1894 private NetworkRequest createNetworkRequest(
1895 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001896 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001897 }
1898
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001899 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1900 NetworkRequest.Type type) {
1901 final NetworkCapabilities netCap = new NetworkCapabilities();
1902 netCap.clearAll();
1903 netCap.addCapability(capability);
1904 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1905 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1906 }
1907
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001908 // Used only for testing.
1909 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001910 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001911 // changing ContentResolver to make registerContentObserver non-final).
1912 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1913 // by subclassing SettingsObserver.
1914 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001915 void updateAlwaysOnNetworks() {
1916 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001917 }
1918
Erik Kline9a62f012018-03-21 07:18:33 -07001919 // See FakeSettingsProvider comment above.
1920 @VisibleForTesting
1921 void updatePrivateDnsSettings() {
1922 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1923 }
1924
paulhu51f77dc2021-06-07 02:34:20 +00001925 @VisibleForTesting
1926 void updateMobileDataPreferredUids() {
1927 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1928 }
1929
Patrick Rohr2857ac42022-01-21 14:58:16 +01001930 @VisibleForTesting
1931 void updateIngressRateLimit() {
1932 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1933 }
1934
Aaron Huang40b52442021-06-08 04:34:24 +08001935 @VisibleForTesting
1936 void simulateUpdateProxyInfo(@Nullable final Network network,
1937 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001938 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08001939 new Pair<>(network, proxyInfo)).sendToTarget();
1940 }
1941
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001942 private void handleAlwaysOnNetworkRequest(
1943 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001944 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001945 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001946 handleAlwaysOnNetworkRequest(networkRequest, enable);
1947 }
1948
1949 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001950 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001951 if (enable == isEnabled) {
1952 return; // Nothing to do.
1953 }
1954
1955 if (enable) {
1956 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001957 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001958 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001959 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001960 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001961 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1962 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001963 }
1964 }
1965
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001966 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001967 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1968 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1969 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1970 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001971 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1972 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001973 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001974 }
1975
paulhu51f77dc2021-06-07 02:34:20 +00001976 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001977 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001978 private void registerSettingsCallbacks() {
1979 // Watch for global HTTP proxy changes.
1980 mSettingsObserver.observe(
1981 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1982 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1983
Chalard Jean46bfbf02022-02-02 00:56:25 +09001984 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001985 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001986 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001987 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1988
Chalard Jean46bfbf02022-02-02 00:56:25 +09001989 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001990 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001991 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001992 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001993
1994 // Watch for mobile data preferred uids changes.
1995 mSettingsObserver.observe(
1996 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1997 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001998
1999 // Watch for ingress rate limit changes.
2000 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002001 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002002 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2003 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002004 }
2005
Erik Kline31b4a9e2018-01-11 21:07:29 +09002006 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002007 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2008 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002009 }
2010 }
2011
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002012 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002013 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2014 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002015 return mNextNetworkRequestId++;
2016 }
2017
junyulai74f9a8b2018-06-13 15:00:37 +08002018 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002019 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002020 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002021 if (network == null) {
2022 return null;
2023 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002024 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002025 }
2026
2027 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002028 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002029 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002030 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002031 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002032
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002033 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002034 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002035 private NetworkAgentInfo getVpnForUid(int uid) {
2036 synchronized (mNetworkForNetId) {
2037 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2038 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002039 if (nai.isVPN() && nai.everConnected()
2040 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002041 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002042 }
2043 }
2044 }
2045 return null;
2046 }
2047
Chalard Jean46bfbf02022-02-02 00:56:25 +09002048 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002049 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002050 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002051 final NetworkAgentInfo nai = getVpnForUid(uid);
2052 if (nai != null) return nai.declaredUnderlyingNetworks;
2053 return null;
2054 }
2055
Lorenzo Colittia7574052021-01-19 01:33:05 +09002056 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002057 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002058
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002059 final Network[] networks = getVpnUnderlyingNetworks(uid);
2060 if (networks != null) {
2061 // getUnderlyingNetworks() returns:
2062 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2063 // empty array => the VPN explicitly said "no default network".
2064 // non-empty array => the VPN specified one or more default networks; we use the
2065 // first one.
2066 if (networks.length > 0) {
2067 nai = getNetworkAgentInfoForNetwork(networks[0]);
2068 } else {
2069 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002070 }
2071 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002072 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002073 }
2074
2075 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002076 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002077 */
paulhu7aeba372020-12-30 00:42:19 +08002078 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2079 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002080 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002081 if (ignoreBlocked) {
2082 return false;
2083 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002084 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002085 final long ident = Binder.clearCallingIdentity();
2086 try {
2087 final boolean metered = nc == null ? true : nc.isMetered();
2088 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2089 } finally {
2090 Binder.restoreCallingIdentity(ident);
2091 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002092 }
2093
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002094 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002095 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2096 return;
2097 }
Hugo Benichi47011212017-03-30 10:46:05 +09002098 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002099 synchronized (mBlockedAppUids) {
2100 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002101 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002102 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002103 blocked = false;
2104 } else {
2105 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002106 }
2107 }
Hugo Benichi47011212017-03-30 10:46:05 +09002108 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2109 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2110 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002111 }
2112
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002113 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002114 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2115 return;
2116 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002117 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002118 final int requestId = nri.getActiveRequest() != null
2119 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002120 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002121 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002122 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002123 }
2124
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002125 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002126 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002127 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002128 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002129 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002130 @NonNull
2131 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2132 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002133 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2134 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2135 // but only exists if an app asks about them or requests them. Ensure the requesting app
2136 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002137 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002138 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2139 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2140 null /* extraInfo */);
2141 }
2142 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002143 return filtered;
2144 }
2145
2146 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2147 boolean ignoreBlocked) {
2148 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2149 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002150 }
2151
2152 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002153 * Return NetworkInfo for the active (i.e., connected) network interface.
2154 * It is assumed that at most one network is active at a time. If more
2155 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002156 * @return the info for the active network, or {@code null} if none is
2157 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002158 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002159 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002160 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002161 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002162 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002163 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002164 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2165 if (nai == null) return null;
2166 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2167 maybeLogBlockedNetworkInfo(networkInfo, uid);
2168 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002169 }
2170
Paul Jensen1f567382015-02-13 14:18:39 -05002171 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002172 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002173 public Network getActiveNetwork() {
2174 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002175 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002176 }
2177
2178 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002179 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002180 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002181 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002182 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002183 }
2184
Chalard Jean46bfbf02022-02-02 00:56:25 +09002185 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002186 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002187 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2188 if (vpnNai != null) {
2189 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2190 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2191 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002192 }
Paul Jensen1f567382015-02-13 14:18:39 -05002193 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002194
James Mattis2516da32021-01-31 17:06:19 -08002195 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002196 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2197 ignoreBlocked)) {
2198 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002199 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002200 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002201 }
2202
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002203 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002204 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002205 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002206 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002207 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2208 if (nai == null) return null;
2209 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002210 }
2211
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002212 /** Returns a NetworkInfo object for a network that doesn't exist. */
2213 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2214 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2215 getNetworkTypeName(networkType), "" /* subtypeName */);
2216 info.setIsAvailable(true);
2217 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2218 // background data is restricted.
2219 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2220 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2221 ? DetailedState.BLOCKED
2222 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002223 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2224 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002225 return info;
2226 }
2227
Lorenzo Colittia7574052021-01-19 01:33:05 +09002228 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002229 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2230 return null;
2231 }
2232 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002233 if (nai == null) {
2234 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002235 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002236 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2237 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002238 }
2239
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002240 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002241 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002242 public NetworkInfo getNetworkInfo(int networkType) {
2243 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002244 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002245 if (getVpnUnderlyingNetworks(uid) != null) {
2246 // A VPN is active, so we may need to return one of its underlying networks. This
2247 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002248 // getNetworkAgentInfoForUid.
2249 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2250 if (nai == null) return null;
2251 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2252 if (networkInfo.getType() == networkType) {
2253 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002254 }
2255 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002256 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002257 }
2258
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002259 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002260 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002261 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002262 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002263 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002264 if (nai == null) return null;
2265 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002266 }
2267
2268 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002269 public NetworkInfo[] getAllNetworkInfo() {
2270 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002271 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002272 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2273 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002274 NetworkInfo info = getNetworkInfo(networkType);
2275 if (info != null) {
2276 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002277 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002278 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002279 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002280 }
2281
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002282 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002283 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002284 public Network getNetworkForType(int networkType) {
2285 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002286 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2287 return null;
2288 }
2289 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2290 if (nai == null) {
2291 return null;
2292 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002293 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002294 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2295 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002296 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002297 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002298 }
2299
2300 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002301 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002302 public Network[] getAllNetworks() {
2303 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002304 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002305 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002306 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002307 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002308 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002309 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002310 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002311 }
2312
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002313 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002314 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002315 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002316 // The basic principle is: if an app's traffic could possibly go over a
2317 // network, without the app doing anything multinetwork-specific,
2318 // (hence, by "default"), then include that network's capabilities in
2319 // the array.
2320 //
2321 // In the normal case, app traffic only goes over the system's default
2322 // network connection, so that's the only network returned.
2323 //
2324 // With a VPN in force, some app traffic may go into the VPN, and thus
2325 // over whatever underlying networks the VPN specifies, while other app
2326 // traffic may go over the system default network (e.g.: a split-tunnel
2327 // VPN, or an app disallowed by the VPN), so the set of networks
2328 // returned includes the VPN's underlying networks and the system
2329 // default.
2330 enforceAccessPermission();
2331
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002332 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002333
James Mattis2516da32021-01-31 17:06:19 -08002334 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2335 if (!nri.isBeingSatisfied()) {
2336 continue;
2337 }
2338 final NetworkAgentInfo nai = nri.getSatisfier();
2339 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2340 if (null != nc
2341 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2342 && !result.containsKey(nai.network)) {
2343 result.put(
2344 nai.network,
2345 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002346 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002347 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2348 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002349 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002350 }
2351
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002352 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002353 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002354 if (null != networks) {
2355 for (final Network network : networks) {
2356 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2357 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002358 result.put(
2359 network,
2360 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002361 nc,
2362 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002363 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002364 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002365 }
2366 }
2367 }
2368
2369 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2370 out = result.values().toArray(out);
2371 return out;
2372 }
2373
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002374 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2375 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2376 // can call sampleConnectivityState and make the checks on it.
2377 @NonNull
2378 private StatsEvent sampleConnectivityStateToStatsEvent() {
2379 final ConnectivityStateSample sample = sampleConnectivityState();
2380 return ConnectivityStatsLog.buildStatsEvent(
2381 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2382 sample.getNetworkCountPerTransports().toByteArray(),
2383 sample.getConnectionDurationPerTransports().toByteArray(),
2384 sample.getNetworkRequestCount().toByteArray(),
2385 sample.getNetworks().toByteArray());
2386 }
2387
2388 /**
2389 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2390 *
2391 * This is used for metrics. These snapshots will be sampled and constitute a base for
2392 * statistics about connectivity state of devices.
2393 */
2394 @VisibleForTesting
2395 @NonNull
2396 public ConnectivityStateSample sampleConnectivityState() {
2397 ensureRunningOnConnectivityServiceThread();
2398 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2399 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2400 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2401 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2402 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2403 return builder.build();
2404 }
2405
2406 private static NetworkCountPerTransports sampleNetworkCount(
2407 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2408 final SparseIntArray countPerTransports = new SparseIntArray();
2409 for (final NetworkAgentInfo nai : nais) {
2410 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2411 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2412 }
2413 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2414 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2415 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2416 c.setTransportTypes(countPerTransports.keyAt(i));
2417 c.setNetworkCount(countPerTransports.valueAt(i));
2418 builder.addNetworkCountForTransports(c);
2419 }
2420 return builder.build();
2421 }
2422
2423 private static ConnectionDurationPerTransports sampleConnectionDuration(
2424 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2425 final ConnectionDurationPerTransports.Builder builder =
2426 ConnectionDurationPerTransports.newBuilder();
2427 for (final NetworkAgentInfo nai : nais) {
2428 final ConnectionDurationForTransports.Builder c =
2429 ConnectionDurationForTransports.newBuilder();
2430 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2431 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2432 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2433 // Add millisPerSecond/2 to round up or down to the nearest value
2434 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2435 builder.addConnectionDurationForTransports(c);
2436 }
2437 return builder.build();
2438 }
2439
2440 private static NetworkRequestCount sampleNetworkRequestCount(
2441 @NonNull final Collection<NetworkRequestInfo> nris) {
2442 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2443 final SparseIntArray countPerType = new SparseIntArray();
2444 for (final NetworkRequestInfo nri : nris) {
2445 final int type;
2446 if (Process.SYSTEM_UID == nri.mAsUid) {
2447 // The request is filed "as" the system, so it's the system on its own behalf.
2448 type = RequestType.RT_SYSTEM.getNumber();
2449 } else if (Process.SYSTEM_UID == nri.mUid) {
2450 // The request is filed by the system as some other app, so it's the system on
2451 // behalf of an app.
2452 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2453 } else {
2454 // Not the system, so it's an app requesting on its own behalf.
2455 type = RequestType.RT_APP.getNumber();
2456 }
2457 countPerType.put(type, countPerType.get(type, 0));
2458 }
2459 for (int i = countPerType.size() - 1; i >= 0; --i) {
2460 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2461 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2462 r.setRequestCount(countPerType.valueAt(i));
2463 builder.addRequestCountForType(r);
2464 }
2465 return builder.build();
2466 }
2467
2468 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2469 final NetworkList.Builder builder = NetworkList.newBuilder();
2470 for (final NetworkAgentInfo nai : nais) {
2471 final NetworkCapabilities nc = nai.networkCapabilities;
2472 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2473 d.setTransportTypes((int) nc.getTransportTypesInternal());
2474 final MeteredState meteredState;
2475 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2476 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2477 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2478 meteredState = MeteredState.METERED_NO;
2479 } else {
2480 meteredState = MeteredState.METERED_YES;
2481 }
2482 d.setMeteredState(meteredState);
2483 final ValidatedState validatedState;
2484 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2485 validatedState = ValidatedState.VS_PORTAL;
2486 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2487 validatedState = ValidatedState.VS_PARTIAL;
2488 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2489 validatedState = ValidatedState.VS_VALID;
2490 } else {
2491 validatedState = ValidatedState.VS_INVALID;
2492 }
2493 d.setValidatedState(validatedState);
2494 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2495 d.setCapabilities(nc.getCapabilitiesInternal());
2496 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2497 builder.addNetworkDescription(d);
2498 }
2499 return builder.build();
2500 }
2501
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002502 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002503 public boolean isNetworkSupported(int networkType) {
2504 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002505 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002506 }
2507
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002508 /**
2509 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002510 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002511 * @return the ip properties for the active network, or {@code null} if
2512 * none is active
2513 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002514 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002515 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002516 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002517 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002518 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2519 if (nai == null) return null;
2520 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002521 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002522 }
2523
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002524 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002525 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002526 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002527 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002528 final LinkProperties lp = getLinkProperties(nai);
2529 if (lp == null) return null;
2530 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002531 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002532 }
2533
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002534 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002535 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002536 public LinkProperties getLinkProperties(Network network) {
2537 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002538 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2539 if (lp == null) return null;
2540 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002541 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002542 }
2543
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002544 @Nullable
2545 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002546 if (nai == null) {
2547 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002548 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002549 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002550 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002551 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002552 }
2553
lucaslinc582d502022-01-27 09:07:00 +08002554 @Override
2555 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002556 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002557 @NonNull String packageName, @Nullable String callingAttributionTag) {
2558 Objects.requireNonNull(packageName);
2559 Objects.requireNonNull(lp);
2560 enforceNetworkStackOrSettingsPermission();
2561 if (!checkAccessPermission(-1 /* pid */, uid)) {
2562 return null;
2563 }
2564 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2565 }
2566
Qingxi Lib2748102020-01-08 12:51:49 -08002567 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2568 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2569 }
2570
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002571 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002572 if (nai == null) return null;
2573 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002574 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002575 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002576 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002577 }
2578
2579 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002580 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2581 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002582 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002583 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002584 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002585 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002586 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002587 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002588 }
2589
lucaslinc582d502022-01-27 09:07:00 +08002590 @Override
lucaslind2b06132022-03-02 10:56:57 +08002591 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2592 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2593 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002594 Objects.requireNonNull(nc);
2595 Objects.requireNonNull(packageName);
2596 enforceNetworkStackOrSettingsPermission();
2597 if (!checkAccessPermission(-1 /* pid */, uid)) {
2598 return null;
2599 }
2600 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2601 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2602 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2603 callingAttributionTag);
2604 }
2605
lucaslin69e1aa92022-03-22 18:15:09 +08002606 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2607 if (nc.getUnderlyingNetworks() != null
2608 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2609 nc.setUnderlyingNetworks(null);
2610 }
2611 }
2612
Qingxi Libb8da982020-01-17 17:54:27 -08002613 @VisibleForTesting
2614 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002615 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002616 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2617 // this would be expensive (one more permission check every time any NC callback is
2618 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2619 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2620 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002621 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002622 if (!checkSettingsPermission(callerPid, callerUid)) {
2623 newNc.setUids(null);
2624 newNc.setSSID(null);
2625 }
Etan Cohen107ae952018-12-30 17:59:59 -08002626 if (newNc.getNetworkSpecifier() != null) {
2627 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2628 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002629 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2630 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002631 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2632 newNc.setAdministratorUids(new int[0]);
2633 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002634 if (!checkAnyPermissionOf(mContext,
Benedict Wong53de25f2021-03-24 14:01:51 -07002635 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002636 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002637 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002638 }
lucaslin69e1aa92022-03-22 18:15:09 +08002639 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002640
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002641 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002642 }
2643
Roshan Pius98f59ec2021-02-23 08:47:39 -08002644 /**
2645 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002646 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002647 * NetworkCapabilities.
2648 * Note: This wrapper does not support any sort of invalidation and thus must not be
2649 * persistent or long-lived. It may only be used for the time necessary to
2650 * compute the redactions required by one particular NetworkCallback or
2651 * synchronous call.
2652 */
2653 private class RedactionPermissionChecker {
2654 private final int mCallingPid;
2655 private final int mCallingUid;
2656 @NonNull private final String mCallingPackageName;
2657 @Nullable private final String mCallingAttributionTag;
2658
2659 private Boolean mHasLocationPermission = null;
2660 private Boolean mHasLocalMacAddressPermission = null;
2661 private Boolean mHasSettingsPermission = null;
2662
2663 RedactionPermissionChecker(int callingPid, int callingUid,
2664 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2665 mCallingPid = callingPid;
2666 mCallingUid = callingUid;
2667 mCallingPackageName = callingPackageName;
2668 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002669 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002670
2671 private boolean hasLocationPermissionInternal() {
2672 final long token = Binder.clearCallingIdentity();
2673 try {
2674 return mLocationPermissionChecker.checkLocationPermission(
2675 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2676 null /* message */);
2677 } finally {
2678 Binder.restoreCallingIdentity(token);
2679 }
2680 }
2681
2682 /**
2683 * Returns whether the app holds location permission or not (might return cached result
2684 * if the permission was already checked before).
2685 */
2686 public boolean hasLocationPermission() {
2687 if (mHasLocationPermission == null) {
2688 // If there is no cached result, perform the check now.
2689 mHasLocationPermission = hasLocationPermissionInternal();
2690 }
2691 return mHasLocationPermission;
2692 }
2693
2694 /**
2695 * Returns whether the app holds local mac address permission or not (might return cached
2696 * result if the permission was already checked before).
2697 */
2698 public boolean hasLocalMacAddressPermission() {
2699 if (mHasLocalMacAddressPermission == null) {
2700 // If there is no cached result, perform the check now.
2701 mHasLocalMacAddressPermission =
2702 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2703 }
2704 return mHasLocalMacAddressPermission;
2705 }
2706
2707 /**
2708 * Returns whether the app holds settings permission or not (might return cached
2709 * result if the permission was already checked before).
2710 */
2711 public boolean hasSettingsPermission() {
2712 if (mHasSettingsPermission == null) {
2713 // If there is no cached result, perform the check now.
2714 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2715 }
2716 return mHasSettingsPermission;
2717 }
2718 }
2719
2720 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2721 @NetworkCapabilities.NetCapability long redaction) {
2722 return (redactions & redaction) != 0;
2723 }
2724
2725 /**
2726 * Use the provided |applicableRedactions| to check the receiving app's
2727 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2728 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2729 * before being sent to the corresponding app.
2730 */
2731 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2732 @NetworkCapabilities.RedactionType long applicableRedactions,
2733 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2734 boolean includeLocationSensitiveInfo) {
2735 long redactions = applicableRedactions;
2736 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2737 if (includeLocationSensitiveInfo
2738 && redactionPermissionChecker.hasLocationPermission()) {
2739 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2740 }
2741 }
2742 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2743 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2744 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2745 }
2746 }
2747 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2748 if (redactionPermissionChecker.hasSettingsPermission()) {
2749 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2750 }
2751 }
2752 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002753 }
2754
Qingxi Lib2748102020-01-08 12:51:49 -08002755 @VisibleForTesting
2756 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002757 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002758 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002759 int callingPid, int callingUid, @NonNull String callingPkgName,
2760 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002761 if (nc == null) {
2762 return null;
2763 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002764 // Avoid doing location permission check if the transport info has no location sensitive
2765 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002766 final RedactionPermissionChecker redactionPermissionChecker =
2767 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2768 callingAttributionTag);
2769 final long redactions = retrieveRequiredRedactions(
2770 nc.getApplicableRedactions(), redactionPermissionChecker,
2771 includeLocationSensitiveInfo);
2772 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002773 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002774 // TODO : calling UID is redacted because apps should generally not know what UID is
2775 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002776 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002777 newNc.setOwnerUid(INVALID_UID);
2778 return newNc;
2779 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002780 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2781 if (nc.hasTransport(TRANSPORT_VPN)) {
2782 // Owner UIDs already checked above. No need to re-check.
2783 return newNc;
2784 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002785 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2786 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002787 // compatibility for older apps.
2788 if (!includeLocationSensitiveInfo
2789 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002790 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002791 newNc.setOwnerUid(INVALID_UID);
2792 return newNc;
2793 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002794 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002795 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002796 newNc.setOwnerUid(INVALID_UID);
2797 }
Qingxi Lib2748102020-01-08 12:51:49 -08002798 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002799 }
2800
lucaslinc582d502022-01-27 09:07:00 +08002801 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002802 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2803 LinkProperties lp, int callerPid, int callerUid) {
2804 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002805 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2806 // this would be expensive (one more permission check every time any LP callback is
2807 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2808 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2809 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002810
2811 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2812 final boolean needsSanitization =
2813 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2814 if (!needsSanitization) {
2815 return new LinkProperties(lp);
2816 }
2817
2818 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002819 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002820 }
2821
2822 final LinkProperties newLp = new LinkProperties(lp);
2823 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2824 // object gets parceled.
2825 newLp.setCaptivePortalApiUrl(null);
2826 newLp.setCaptivePortalData(null);
2827 return newLp;
2828 }
2829
Roshan Pius08c94fb2020-01-16 12:17:17 -08002830 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2831 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002832 // There is no need to track the effective UID of the request here. If the caller
2833 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002834 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002835 // Unprivileged apps can only pass in null or their own UID.
2836 if (nc.getUids() == null) {
2837 // If the caller passes in null, the callback will also match networks that do not
2838 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2839 // In this case, redact everything in the request immediately. This ensures that the
2840 // app is not able to get any redacted information by filing an unredacted request
2841 // and observing whether the request matches something.
2842 if (nc.getNetworkSpecifier() != null) {
2843 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2844 }
2845 } else {
2846 nc.setSingleUid(callerUid);
2847 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002848 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002849 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002850 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002851
2852 // Clear owner UID; this can never come from an app.
2853 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002854 }
2855
Chalard Jean38354d12018-03-20 19:13:57 +09002856 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002857 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002858 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2859 }
2860 }
2861
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002862 @Override
2863 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2864 enforceAccessPermission();
2865 final int callerUid = Binder.getCallingUid();
2866 final long token = Binder.clearCallingIdentity();
2867 try {
2868 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2869 } finally {
2870 Binder.restoreCallingIdentity(token);
2871 }
2872 }
2873
junyulaiebd15162021-03-03 12:09:05 +08002874 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002875 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002876 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002877 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002878 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002879
Serik Beketayev05130302021-01-15 16:47:25 -08002880 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002881 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002882 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2883 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002884 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002885 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002886 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002887 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2888 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002889 }
2890 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002891 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002892 }
2893
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002894 @Override
junyulaiebd15162021-03-03 12:09:05 +08002895 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002896 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002897 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002898 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002899
2900 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2901 for (Network network : getAllNetworks()) {
2902 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09002903 final boolean includeNetwork = (nai != null) && nai.isCreated();
2904 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002905 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2906 // NetworkCapabilities, which may contain UIDs of apps to which the
2907 // network applies. Should the UIDs be cleared so as not to leak or
2908 // interfere ?
2909 result.add(nai.getNetworkStateSnapshot());
2910 }
2911 }
2912 return result;
2913 }
2914
2915 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002916 public boolean isActiveNetworkMetered() {
2917 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002918
Qingxi Lib2748102020-01-08 12:51:49 -08002919 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002920 if (caps != null) {
2921 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2922 } else {
2923 // Always return the most conservative value
2924 return true;
2925 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002926 }
2927
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002928 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002929 * Ensures that the system cannot call a particular method.
2930 */
2931 private boolean disallowedBecauseSystemCaller() {
2932 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002933 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2934 // for devices launched with Q and above. However, existing devices upgrading to Q and
2935 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002936 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002937 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002938 log("This method exists only for app backwards compatibility"
2939 + " and must not be called by system services.");
2940 return true;
2941 }
2942 return false;
2943 }
2944
paulhub2c28682021-08-18 18:35:54 +08002945 private int getAppUid(final String app, final UserHandle user) {
2946 final PackageManager pm =
2947 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2948 final long token = Binder.clearCallingIdentity();
2949 try {
2950 return pm.getPackageUid(app, 0 /* flags */);
2951 } catch (PackageManager.NameNotFoundException e) {
2952 return -1;
2953 } finally {
2954 Binder.restoreCallingIdentity(token);
2955 }
2956 }
2957
2958 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2959 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2960 if (getAppUid(packageName, user) != callingUid) {
2961 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2962 }
2963 }
2964
Lorenzo Colitti23862912018-09-28 11:31:55 +09002965 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002966 * Ensure that a network route exists to deliver traffic to the specified
2967 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002968 * @param networkType the type of the network over which traffic to the
2969 * specified host is to be routed
2970 * @param hostAddress the IP address of the host to which the route is
2971 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002972 * @return {@code true} on success, {@code false} on failure
2973 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002974 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002975 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2976 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002977 if (disallowedBecauseSystemCaller()) {
2978 return false;
2979 }
paulhub2c28682021-08-18 18:35:54 +08002980 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002981 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002982 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002983 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002984 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002985
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002986 InetAddress addr;
2987 try {
2988 addr = InetAddress.getByAddress(hostAddress);
2989 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002990 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002991 return false;
2992 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002993
The Android Open Source Project28527d22009-03-03 19:31:44 -08002994 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002995 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002996 return false;
2997 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002998
2999 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3000 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003001 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003002 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3003 } else {
3004 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3005 }
3006 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003007 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003008
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003009 DetailedState netState;
3010 synchronized (nai) {
3011 netState = nai.networkInfo.getDetailedState();
3012 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003013
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003014 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003015 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003016 log("requestRouteToHostAddress on down network "
3017 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003018 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003019 }
3020 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003021 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003022
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003023 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003024 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003025 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003026 LinkProperties lp;
3027 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003028 synchronized (nai) {
3029 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003030 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003031 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003032 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003033 if (DBG) {
3034 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3035 }
Wink Saville32506bc2013-06-29 21:10:57 -07003036 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003037 } finally {
3038 Binder.restoreCallingIdentity(token);
3039 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003040 }
3041
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003042 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003043 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003044 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003045 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003046 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003047 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003048 if (bestRoute.getGateway().equals(addr)) {
3049 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003050 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003051 } else {
3052 // if we will connect to this through another route, add a direct route
3053 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003054 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003055 }
3056 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003057 if (DBG) log("Adding legacy route " + bestRoute +
3058 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003059
3060 final String dst = bestRoute.getDestinationLinkAddress().toString();
3061 final String nextHop = bestRoute.hasGateway()
3062 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003063 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003064 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3065 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003066 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003067 return false;
3068 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003069 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003070 }
3071
paulhu7c0a2e62021-01-08 00:51:49 +08003072 class DnsResolverUnsolicitedEventCallback extends
3073 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003074 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003075 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003076 try {
3077 mHandler.sendMessage(mHandler.obtainMessage(
3078 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003079 new PrivateDnsValidationUpdate(event.netId,
3080 InetAddresses.parseNumericAddress(event.ipAddress),
3081 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003082 } catch (IllegalArgumentException e) {
3083 loge("Error parsing ip address in validation event");
3084 }
3085 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003086
3087 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003088 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3089 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003090 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3091 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3092 // event callback for certain nai. e.g. cellular. Register here to pass to
3093 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003094 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003095 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3096 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003097 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003098 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003099 }
3100 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003101
3102 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003103 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3104 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3105 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003106 }
dalyk1720e542018-03-05 12:42:22 -05003107
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003108 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003109 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003110 return this.VERSION;
3111 }
3112
3113 @Override
3114 public String getInterfaceHash() {
3115 return this.HASH;
3116 }
paulhu7c0a2e62021-01-08 00:51:49 +08003117 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003118
3119 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003120 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3121 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003122
paulhu7c0a2e62021-01-08 00:51:49 +08003123 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003124 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003125 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003126 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003127 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003128 }
3129 }
3130
Sudheer Shanka9967d462021-03-18 19:09:25 +00003131 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003132 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003133 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003134 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3135 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003136 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003137 };
3138
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003139 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003140 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003141 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003142 }
3143
Mark Fasheh7c999d82023-05-04 20:23:11 +00003144 static final class UidFrozenStateChangedArgs {
3145 final int[] mUids;
3146 final int[] mFrozenStates;
3147
3148 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3149 mUids = uids;
3150 mFrozenStates = frozenStates;
3151 }
3152 }
3153
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003154 /**
3155 * Check if the cell network is idle.
3156 * @return true if the cell network state is idle
3157 * false if the cell network state is active or unknown
3158 */
3159 private boolean isCellNetworkIdle() {
3160 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3161 if (defaultNai == null
3162 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3163 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3164 // cell network is not the default network, cell network state is unknown.
3165 // TODO(b/279380356): Track cell network state when the cell is not the default network
3166 return false;
3167 }
3168
3169 return !mNetworkActivityTracker.isDefaultNetworkActive();
3170 }
3171
Mark Fasheh7c999d82023-05-04 20:23:11 +00003172 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003173 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003174
3175 for (int i = 0; i < uids.length; i++) {
3176 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003177 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003178 } else {
3179 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003180 }
3181 }
3182
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003183 if (ownerUids.isEmpty()) {
3184 return;
3185 }
3186
3187 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3188 // Delay closing sockets to avoid waking the cell modem up.
3189 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3190 // than waking cell modem up.
3191 mPendingFrozenUids.addAll(ownerUids);
3192 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003193 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003194 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003195 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003196 loge("Exception in socket destroy: " + e);
3197 }
3198 }
3199 }
3200
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003201 private void closePendingFrozenSockets() {
3202 ensureRunningOnConnectivityServiceThread();
3203
3204 try {
3205 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3206 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3207 loge("Failed to close pending frozen app sockets: " + e);
3208 }
3209 mPendingFrozenUids.clear();
3210 }
3211
3212 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3213 mNetworkActivityTracker.handleReportNetworkActivity(params);
3214
3215 if (mDelayDestroyFrozenSockets
3216 && params.isActive
3217 && params.label == TRANSPORT_CELLULAR
3218 && !mPendingFrozenUids.isEmpty()) {
3219 closePendingFrozenSockets();
3220 }
3221 }
3222
3223 /**
3224 * If the cellular network is no longer the default network, close pending frozen sockets.
3225 *
3226 * @param newNetwork new default network
3227 * @param oldNetwork old default network
3228 */
3229 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3230 NetworkAgentInfo oldNetwork) {
3231 final boolean isOldNetworkCellular = oldNetwork != null
3232 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3233 final boolean isNewNetworkCellular = newNetwork != null
3234 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3235
3236 if (isOldNetworkCellular
3237 && !isNewNetworkCellular
3238 && !mPendingFrozenUids.isEmpty()) {
3239 closePendingFrozenSockets();
3240 }
3241 }
3242
3243 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3244 pw.println("CloseFrozenAppSockets:");
3245 pw.increaseIndent();
3246 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3247 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3248 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3249 pw.decreaseIndent();
3250 }
3251
Mark Fasheh7c999d82023-05-04 20:23:11 +00003252 @VisibleForTesting
3253 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003254 @VisibleForTesting
3255 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3256 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003257
Paul Jensen83f5d572014-08-29 09:54:01 -04003258 private void enforceInternetPermission() {
3259 mContext.enforceCallingOrSelfPermission(
3260 android.Manifest.permission.INTERNET,
3261 "ConnectivityService");
3262 }
3263
The Android Open Source Project28527d22009-03-03 19:31:44 -08003264 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003265 mContext.enforceCallingOrSelfPermission(
3266 android.Manifest.permission.ACCESS_NETWORK_STATE,
3267 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003268 }
3269
lucaslinc582d502022-01-27 09:07:00 +08003270 private boolean checkAccessPermission(int pid, int uid) {
3271 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3272 == PERMISSION_GRANTED;
3273 }
3274
paulhua6ee2122021-02-22 15:40:43 +08003275 /**
3276 * Performs a strict and comprehensive check of whether a calling package is allowed to
3277 * change the state of network, as the condition differs for pre-M, M+, and
3278 * privileged/preinstalled apps. The caller is expected to have either the
3279 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3280 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3281 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3282 * permission and cannot be revoked. See http://b/23597341
3283 *
3284 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3285 * of this app will be updated to the current time.
3286 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003287 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003288 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3289 == PackageManager.PERMISSION_GRANTED) {
3290 return;
3291 }
3292
3293 if (callingPkg == null) {
3294 throw new SecurityException("Calling package name is null.");
3295 }
3296
3297 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3298 final int uid = mDeps.getCallingUid();
3299 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3300 callingPkg, callingAttributionTag, null /* message */);
3301
3302 if (mode == AppOpsManager.MODE_ALLOWED) {
3303 return;
3304 }
3305
3306 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3307 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3308 return;
3309 }
3310
3311 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3312 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3313 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003314 }
3315
Charles He9369e612017-05-15 17:07:18 +01003316 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003317 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003318 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003319 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003320 }
3321
Quang Luong98858d62023-02-11 00:25:24 +00003322 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003323 enforceAnyPermissionOf(mContext,
3324 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003325 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003326 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3327 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3328 }
3329
paulhu8e96a752019-08-12 16:25:11 +08003330 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003331 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003332 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003333 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003334 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003335 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003336 }
3337
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003338 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003339 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003340 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003341 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003342 android.Manifest.permission.NETWORK_SETTINGS,
3343 android.Manifest.permission.NETWORK_FACTORY,
3344 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3345 }
3346
3347 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003348 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003349 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003350 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003351 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3352 android.Manifest.permission.NETWORK_FACTORY,
3353 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3354 }
3355
lucaslin69e1aa92022-03-22 18:15:09 +08003356 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3357 return PERMISSION_GRANTED == mContext.checkPermission(
3358 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3359 || PERMISSION_GRANTED == mContext.checkPermission(
3360 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3361 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003362 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003363 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003364 }
3365
Chalard Jean9a396cc2018-02-21 18:43:54 +09003366 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003367 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003368 android.Manifest.permission.NETWORK_SETTINGS,
3369 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003370 }
3371
3372 private boolean checkSettingsPermission(int pid, int uid) {
3373 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003374 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3375 || PERMISSION_GRANTED == mContext.checkPermission(
3376 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003377 }
3378
paulhu8e96a752019-08-12 16:25:11 +08003379 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003380 enforceNetworkStackPermissionOr(mContext,
3381 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003382 }
3383
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003384 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003385 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003386 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003387 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003388 }
3389
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003390 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003391 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003392 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3393 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003394 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003395 }
3396
James Mattis8378aec2021-01-26 14:05:36 -08003397 private void enforceOemNetworkPreferencesPermission() {
3398 mContext.enforceCallingOrSelfPermission(
3399 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3400 "ConnectivityService");
3401 }
3402
James Mattisfa270db2021-05-31 17:11:10 -07003403 private void enforceManageTestNetworksPermission() {
3404 mContext.enforceCallingOrSelfPermission(
3405 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3406 "ConnectivityService");
3407 }
3408
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003409 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003410 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003411 android.Manifest.permission.NETWORK_STACK,
3412 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003413 }
3414
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003415 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003416 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003417 android.Manifest.permission.NETWORK_STACK,
3418 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3419 }
3420
paulhu1a407652019-03-22 16:35:06 +08003421 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003422 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003423 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003424 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3425 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003426 }
3427
Paul Hu8fc2a552022-05-04 18:44:42 +08003428 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3429 boolean checkUidsAllowedList) {
3430 if (PermissionUtils.checkAnyPermissionOf(mContext,
3431 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3432 return true;
3433 }
3434
3435 // fallback to ConnectivityInternalPermission
3436 // TODO: Remove this fallback check after all apps have declared
3437 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3438 if (PermissionUtils.checkAnyPermissionOf(mContext,
3439 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3440 return true;
3441 }
3442
3443 // Check whether uid is in allowed on restricted networks list.
3444 if (checkUidsAllowedList
3445 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3446 return true;
3447 }
3448 return false;
3449 }
3450
3451 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3452 final int callingUid = mDeps.getCallingUid();
3453 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3454 throw new SecurityException("ConnectivityService: user " + callingUid
3455 + " has no permission to access restricted network.");
3456 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003457 }
3458
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003459 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003460 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003461 }
3462
Roshan Pius98f59ec2021-02-23 08:47:39 -08003463 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3464 return PERMISSION_GRANTED == mContext.checkPermission(
3465 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3466 }
3467
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003468 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003469 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003470 }
3471
3472 private void sendInetConditionBroadcast(NetworkInfo info) {
3473 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3474 }
3475
Wink Saville4f0de1e2011-08-04 15:01:58 -07003476 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003477 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003478 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003479 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003480 if (info.isFailover()) {
3481 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3482 info.setFailover(false);
3483 }
3484 if (info.getReason() != null) {
3485 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3486 }
3487 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003488 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3489 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003490 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003491 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003492 return intent;
3493 }
3494
3495 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3496 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3497 }
3498
Michael Groover73f69482023-01-27 11:01:25 -06003499 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3500 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003501 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3502 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003503 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003504 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003505 if (!mSystemReady
3506 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003507 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003508 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003509 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003510 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003511 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003512 }
3513
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003514 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003515 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003516 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003517 final NetworkInfo ni = intent.getParcelableExtra(
3518 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003519 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3520 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003521 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003522 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003523 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003524 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003525 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003526 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003527 } finally {
3528 Binder.restoreCallingIdentity(ident);
3529 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003530 }
3531 }
3532
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003533 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3534 NetworkInfo info) {
3535 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003536 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003537
3538 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3539 try {
3540 // This allows us to discard older broadcasts still waiting to be delivered
3541 // which have the same namespace and key.
3542 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3543 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3544 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003545 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003546 } catch (UnsupportedApiLevelException e) {
3547 Log.wtf(TAG, "Using unsupported API" + e);
3548 }
3549 }
3550
3551 @VisibleForTesting
3552 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3553 final StringBuilder sb = new StringBuilder();
3554 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3555 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3556 sb.append(info.getExtraInfo());
3557 return sb.toString();
3558 }
3559
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003560 /**
Aaron Huang96011892020-06-27 07:18:23 +08003561 * Called by SystemServer through ConnectivityManager when the system is ready.
3562 */
3563 @Override
3564 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003565 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003566 throw new SecurityException("Calling Uid is not system uid.");
3567 }
3568 systemReadyInternal();
3569 }
3570
3571 /**
3572 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003573 */
3574 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003575 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003576 // Load flags after PackageManager is ready to query module version
3577 mFlags.loadFlags(mDeps, mContext);
3578
Aaron Huang9a57acf2020-12-08 10:03:29 +08003579 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3580 // listening network request which is sent by MultipathPolicyTracker won't be added
3581 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3582 // be called after PermissionMonitor#startMonitoring().
3583 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3584 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3585 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003586 final ConditionVariable startMonitoringDone = new ConditionVariable();
3587 mHandler.post(() -> {
3588 mPermissionMonitor.startMonitoring();
3589 startMonitoringDone.open();
3590 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003591 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003592 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003593
Hugo Benichie5220992017-04-26 14:53:28 +09003594 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003595 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003596 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003597 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003598 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003599 }
3600 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003601
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003602 // Create network requests for always-on networks.
3603 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003604
3605 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003606 // Note that updating can be skipped here if the list is empty only because no uid
3607 // rules are applied before system ready. Normally, the empty uid list means to clear
3608 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003609 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3610 updateMobileDataPreferredUids();
3611 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003612
3613 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003614 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003615 mBpfNetMaps.setPullAtomCallback(mContext);
3616 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003617 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3618 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003619 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3620 // have permission problem. While CV#block() is unbounded in time and can in principle block
3621 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3622 // could have blocked forever too.
3623 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003624 }
3625
The Android Open Source Project28527d22009-03-03 19:31:44 -08003626 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003627 * Start listening for default data network activity state changes.
3628 */
3629 @Override
3630 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003631 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003632 }
3633
3634 /**
3635 * Stop listening for default data network activity state changes.
3636 */
3637 @Override
3638 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003639 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003640 }
3641
3642 /**
3643 * Check whether the default network radio is currently active.
3644 */
3645 @Override
3646 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003647 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003648 }
3649
3650 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003651 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003652 * and set it on it's iface.
3653 */
Junyu Lai970963e2022-10-25 15:46:47 +08003654 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003655 final String iface = newLp.getInterfaceName();
3656 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003657 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003658 // Silently ignore unset MTU value.
3659 return;
3660 }
Hansen Kurli04252032022-12-07 11:21:49 +00003661 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3662 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3663 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003664 return;
3665 }
Hansen Kurli04252032022-12-07 11:21:49 +00003666 // Cannot set MTU without interface name
3667 if (TextUtils.isEmpty(iface)) {
3668 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003669 return;
3670 }
sy.yun4aa73922013-09-02 05:24:09 +09003671
Hansen Kurli04252032022-12-07 11:21:49 +00003672 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3673 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003674 return;
3675 }
3676
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003677 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003678 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003679 mNetd.interfaceSetMtu(iface, mtu);
3680 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003681 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003682 }
3683 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003684
Chenbo Feng15416292018-11-08 17:36:21 -08003685 @VisibleForTesting
3686 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003687
Junyu Lai970963e2022-10-25 15:46:47 +08003688 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003689 String[] values = null;
3690 if (tcpBufferSizes != null) {
3691 values = tcpBufferSizes.split(",");
3692 }
3693
3694 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003695 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003696 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3697 values = tcpBufferSizes.split(",");
3698 }
3699
3700 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3701
3702 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003703 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003704
Chenbo Feng15416292018-11-08 17:36:21 -08003705 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3706 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3707 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003708 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003709 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003710 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003711 }
3712 }
3713
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003714 @Override
3715 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003716 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003717 NETWORK_RESTORE_DELAY_PROP_NAME);
3718 if(restoreDefaultNetworkDelayStr != null &&
3719 restoreDefaultNetworkDelayStr.length() != 0) {
3720 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003721 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003722 } catch (NumberFormatException e) {
3723 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003724 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003725 // if the system property isn't set, use the value for the apn type
3726 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3727
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003728 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3729 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003730 }
3731 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003732 }
3733
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003734 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003735 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003736 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003737 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003738 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003739 // Start gathering diagnostic information.
3740 netDiags.add(new NetworkDiagnostics(
3741 nai.network,
3742 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003743 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003744 DIAG_TIME_MS));
3745 }
3746
3747 for (NetworkDiagnostics netDiag : netDiags) {
3748 pw.println();
3749 netDiag.waitForMeasurements();
3750 netDiag.dump(pw);
3751 }
3752 }
3753
The Android Open Source Project28527d22009-03-03 19:31:44 -08003754 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003755 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3756 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003757 if (!checkDumpPermission(mContext, TAG, writer)) return;
3758
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003759 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003760 }
3761
lucaslin99473f62020-12-10 15:10:54 +08003762 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3763 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3764 != PackageManager.PERMISSION_GRANTED) {
3765 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003766 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003767 + " due to missing android.permission.DUMP permission");
3768 return false;
3769 } else {
3770 return true;
3771 }
3772 }
3773
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003774 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003775 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003776
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003777 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003778 dumpNetworkDiagnostics(pw);
3779 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003780 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003781 dumpNetworks(pw);
3782 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003783 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003784 dumpNetworkRequests(pw);
3785 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003786 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3787 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3788 dumpTrafficController(pw, fd, verbose);
3789 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003790 }
Erik Kline9647f382015-06-05 17:47:34 +09003791
Junyu Lai0da479b2022-04-20 15:06:29 +08003792 pw.println("NetworkProviders for:");
3793 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003794 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003795 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003796 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003797 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003798 pw.println();
3799
Chalard Jean5b409c72021-02-04 13:12:59 +09003800 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003801 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003802 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003803 pw.println("none");
3804 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003805 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003806 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003807 pw.println();
3808
James Mattis8b298a02021-06-01 22:34:04 -07003809 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003810 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003811 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003812 pw.decreaseIndent();
3813 pw.println();
3814
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003815 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003816 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003817 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003818 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003819 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003820
junyulaif2c67e42018-08-07 19:50:45 +08003821 pw.println("Status for known UIDs:");
3822 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003823 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003824 for (int i = 0; i < size; i++) {
3825 // Don't crash if the array is modified while dumping in bugreports.
3826 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003827 final int uid = mUidBlockedReasons.keyAt(i);
3828 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3829 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003830 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003831 } catch (ArrayIndexOutOfBoundsException e) {
3832 pw.println(" ArrayIndexOutOfBoundsException");
3833 } catch (ConcurrentModificationException e) {
3834 pw.println(" ConcurrentModificationException");
3835 }
3836 }
3837 pw.println();
3838 pw.decreaseIndent();
3839
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003840 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003841 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003842 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003843 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003844 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003845
Junyu Lai0da479b2022-04-20 15:06:29 +08003846 pw.println("Network Offers:");
3847 pw.increaseIndent();
3848 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3849 pw.println(offerInfo.offer);
3850 }
3851 pw.decreaseIndent();
3852 pw.println();
3853
Robert Greenwalt94e22142014-07-30 16:31:24 -07003854 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003855
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003856 pw.println();
markchien5e866652019-09-30 14:40:57 +08003857 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003858
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003859 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003860 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003861
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003862 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003863 dumpCloseFrozenAppSockets(pw);
3864
3865 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003866
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003867 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003868 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003869 pw.println("mNetworkRequestInfoLogs (most recent first):");
3870 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003871 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003872 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003873
3874 pw.println();
3875 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3876 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003877 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003878 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003879
3880 pw.println();
3881 pw.println("NetTransition WakeLock activity (most recent first):");
3882 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003883 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3884 pw.println("total releases: " + mTotalWakelockReleases);
3885 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3886 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3887 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3888 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3889 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3890 }
James Mattiscb1e0362021-04-06 17:07:42 -07003891 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003892
3893 pw.println();
3894 pw.println("bandwidth update requests (by uid):");
3895 pw.increaseIndent();
3896 synchronized (mBandwidthRequests) {
3897 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3898 pw.println("[" + mBandwidthRequests.keyAt(i)
3899 + "]: " + mBandwidthRequests.valueAt(i));
3900 }
3901 }
3902 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003903 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003904
James Mattiscb1e0362021-04-06 17:07:42 -07003905 pw.println();
3906 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3907 pw.increaseIndent();
3908 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003909 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003910 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003911
3912 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003913
3914 pw.println();
3915 pw.println("Permission Monitor:");
3916 pw.increaseIndent();
3917 mPermissionMonitor.dump(pw);
3918 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003919
3920 pw.println();
3921 pw.println("Legacy network activity:");
3922 pw.increaseIndent();
3923 mNetworkActivityTracker.dump(pw);
3924 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003925 }
3926
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003927 private void dumpNetworks(IndentingPrintWriter pw) {
3928 for (NetworkAgentInfo nai : networksSortedById()) {
3929 pw.println(nai.toString());
3930 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003931 pw.println("Nat464Xlat:");
3932 pw.increaseIndent();
3933 nai.dumpNat464Xlat(pw);
3934 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003935 pw.println(String.format(
3936 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3937 nai.numForegroundNetworkRequests(),
3938 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3939 nai.numBackgroundNetworkRequests(),
3940 nai.numNetworkRequests()));
3941 pw.increaseIndent();
3942 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3943 pw.println(nai.requestAt(i).toString());
3944 }
3945 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003946 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003947 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003948 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003949 pw.decreaseIndent();
3950 pw.decreaseIndent();
3951 }
3952 }
3953
James Mattis8b298a02021-06-01 22:34:04 -07003954 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3955 if (!mProfileNetworkPreferences.isEmpty()) {
3956 pw.println("Profile preferences:");
3957 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09003958 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07003959 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003960 }
James Mattis8b298a02021-06-01 22:34:04 -07003961 if (!mOemNetworkPreferences.isEmpty()) {
3962 pw.println("OEM preferences:");
3963 pw.increaseIndent();
3964 pw.println(mOemNetworkPreferences);
3965 pw.decreaseIndent();
3966 }
3967 if (!mMobileDataPreferredUids.isEmpty()) {
3968 pw.println("Mobile data preferred UIDs:");
3969 pw.increaseIndent();
3970 pw.println(mMobileDataPreferredUids);
3971 pw.decreaseIndent();
3972 }
James Mattis45d81842021-01-10 14:24:24 -08003973
James Mattis8b298a02021-06-01 22:34:04 -07003974 pw.println("Default requests:");
3975 pw.increaseIndent();
3976 dumpPerAppDefaultRequests(pw);
3977 pw.decreaseIndent();
3978 }
3979
3980 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003981 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3982 if (mDefaultRequest == defaultRequest) {
3983 continue;
3984 }
3985
James Mattis8b298a02021-06-01 22:34:04 -07003986 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3987 final String networkOutput;
3988 if (null == satisfier) {
3989 networkOutput = "null";
3990 } else if (mNoServiceNetwork.equals(satisfier)) {
3991 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003992 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003993 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003994 }
James Mattis8b298a02021-06-01 22:34:04 -07003995 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3996 ? "" : " asUid: " + defaultRequest.mAsUid;
3997 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3998 + defaultRequest.mPid + asUidString + "]";
3999 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4000 + " Preference order: " + defaultRequest.mPreferenceOrder
4001 + " Tracked UIDs: " + defaultRequest.getUids();
4002 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004003 }
4004 }
4005
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004006 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004007 NetworkRequestInfo[] infos = null;
4008 while (infos == null) {
4009 try {
4010 infos = requestsSortedById();
4011 } catch (ConcurrentModificationException e) {
4012 // mNetworkRequests should only be accessed from handler thread, except dump().
4013 // As dump() is never called in normal usage, it would be needlessly expensive
4014 // to lock the collection only for its benefit. Instead, retry getting the
4015 // requests if ConcurrentModificationException is thrown during dump().
4016 }
4017 }
4018 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004019 pw.println(nri.toString());
4020 }
4021 }
4022
Ken Chene6d511f2022-01-25 11:10:42 +08004023 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4024 boolean verbose) {
4025 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004026 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004027 } catch (ServiceSpecificException e) {
4028 pw.println(e.getMessage());
4029 } catch (IOException e) {
4030 loge("Dump BPF maps failed, " + e);
4031 }
4032 }
4033
Chalard Jean524f0b12021-10-25 21:11:56 +09004034 private void dumpAllRequestInfoLogsToLogcat() {
4035 try (PrintWriter logPw = new PrintWriter(new Writer() {
4036 @Override
4037 public void write(final char[] cbuf, final int off, final int len) {
4038 // This method is called with 0-length and 1-length arrays for empty strings
4039 // or strings containing only the DEL character.
4040 if (len <= 1) return;
4041 Log.e(TAG, new String(cbuf, off, len));
4042 }
4043 @Override public void flush() {}
4044 @Override public void close() {}
4045 })) {
4046 mNetworkRequestInfoLogs.dump(logPw);
4047 }
4048 }
4049
Hugo Benichia480ba52018-09-03 08:19:02 +09004050 /**
4051 * Return an array of all current NetworkAgentInfos sorted by network id.
4052 */
4053 private NetworkAgentInfo[] networksSortedById() {
4054 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004055 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004056 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004057 return networks;
4058 }
4059
4060 /**
4061 * Return an array of all current NetworkRequest sorted by request id.
4062 */
James Mattis258ea3c2020-11-15 15:04:40 -08004063 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004064 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004065 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004066 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004067 // Sort the array based off the NRI containing the min requestId in its requests.
4068 Arrays.sort(requests,
4069 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4070 Comparator.comparingInt(req -> req.requestId)).requestId
4071 )
4072 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004073 return requests;
4074 }
4075
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004076 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004077 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004078 if (officialNai != null && officialNai.equals(nai)) return true;
4079 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004080 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004081 " - " + nai);
4082 }
4083 return false;
4084 }
4085
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004086 private boolean isDisconnectRequest(Message msg) {
4087 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4088 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4089 return info.getState() == NetworkInfo.State.DISCONNECTED;
4090 }
4091
Robert Greenwalt2034b912009-08-12 16:08:25 -07004092 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004093 private class NetworkStateTrackerHandler extends Handler {
4094 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004095 super(looper);
4096 }
4097
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004098 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004099 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4100 final NetworkAgentInfo nai = arg.first;
4101 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004102 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004103 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004104 }
4105 return;
4106 }
4107
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004108 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004109 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004110 return;
4111 }
4112
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004113 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004114 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09004115 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
4116 final NetworkCapabilities sanitized =
4117 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004118 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004119 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004120 break;
4121 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004122 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004123 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004124 processLinkPropertiesFromAgent(nai, newLp);
4125 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004126 break;
4127 }
4128 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004129 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004130 updateNetworkInfo(nai, info);
4131 break;
4132 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004133 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004134 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004135 break;
4136 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004137 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004138 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004139 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004140 // Note that if the NAI had been connected, this would affect the
4141 // score, and therefore would require re-mixing the score and performing
4142 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004143 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004144 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4145 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004146 // Mark the network as temporarily accepting partial connectivity so that it
4147 // will be validated (and possibly become default) even if it only provides
4148 // partial internet access. Note that if user connects to partial connectivity
4149 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4150 // out of wifi coverage) and if the same wifi is available again, the device
4151 // will auto connect to this wifi even though the wifi has "no internet".
4152 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004153 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004154 break;
4155 }
junyulai011b1f12019-01-03 18:50:15 +08004156 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004157 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004158 break;
4159 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004160 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004161 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004162 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004163
4164 if (isLegacyLockdownNai(nai)
4165 && (underlying == null || underlying.size() != 1)) {
4166 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4167 + " must have exactly one underlying network: " + underlying);
4168 }
4169
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004170 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4171 nai.declaredUnderlyingNetworks = (underlying != null)
4172 ? underlying.toArray(new Network[0]) : null;
4173
4174 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4175 if (DBG) {
4176 log(nai.toShortString() + " changed underlying networks to "
4177 + Arrays.toString(nai.declaredUnderlyingNetworks));
4178 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004179 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004180 notifyIfacesChangedForNetworkStats();
4181 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004182 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004183 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004184 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4185 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4186 nai.teardownDelayMs = msg.arg1;
4187 } else {
4188 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4189 }
Chalard Jean550b5212021-03-05 23:07:53 +09004190 break;
4191 }
4192 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4193 nai.setLingerDuration((int) arg.second);
4194 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004195 }
Tyler Wear72388212021-09-09 14:49:02 -07004196 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4197 DscpPolicy policy = (DscpPolicy) arg.second;
4198 if (mDscpPolicyTracker != null) {
4199 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4200 }
4201 break;
4202 }
4203 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4204 if (mDscpPolicyTracker != null) {
4205 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4206 }
4207 break;
4208 }
4209 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4210 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004211 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004212 }
4213 break;
4214 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004215 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004216 if (!nai.everConnected()) {
4217 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4218 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004219 teardownUnneededNetwork(nai);
4220 break;
4221 }
4222
4223 if (nai.isDestroyed()) {
4224 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4225 + ", ignoring");
4226 break;
4227 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004228
4229 final int timeoutMs = (int) arg.second;
4230 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4231 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4232 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4233 }
4234
4235 // Marking a network awaiting replacement is used to ensure that any requests
4236 // satisfied by the network do not switch to another network until a
4237 // replacement is available or the wait for a replacement times out.
4238 // If the network is inactive (i.e., nascent or lingering), then there are no
4239 // such requests, and there is no point keeping it. Just tear it down.
4240 // Note that setLingerDuration(0) cannot be used to do this because the network
4241 // could be nascent.
4242 nai.clearInactivityState();
4243 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4244 Log.d(TAG, nai.toShortString()
4245 + " marked awaiting replacement is unneeded, tearing down instead");
4246 teardownUnneededNetwork(nai);
4247 break;
4248 }
4249
4250 Log.d(TAG, "Marking " + nai.toShortString()
4251 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4252 destroyNativeNetwork(nai);
4253
4254 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4255 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4256 // consider the fact that the network could already have disconnected or been
4257 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4258 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4259 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4260 mKeepaliveTracker.handleStopAllKeepalives(nai,
4261 SocketKeepalive.ERROR_INVALID_NETWORK);
4262
4263 nai.updateScoreForNetworkAgentUpdate();
4264 // This rematch is almost certainly not going to result in any changes, because
4265 // the destroyed flag is only just above the "current satisfier wins"
4266 // tie-breaker. But technically anything that affects scoring should rematch.
4267 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004268 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004269 break;
4270 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004271 }
4272 }
4273
4274 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004275 final int netId = msg.arg2;
4276 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004277 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004278 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004279 switch (msg.what) {
4280 default:
4281 return false;
lucasline117e2e2019-10-22 18:27:33 +08004282 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004283 if (nai == null) {
4284 break;
4285 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004286 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4287 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004288 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004289 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004290 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004291 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004292 if (probePrivateDnsCompleted) {
4293 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4294 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004295 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004296 }
4297 // Only show the notification when the private DNS is broken and the
4298 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004299 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004300 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4301 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004302 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004303 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4304 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4305 // private DNS is broken, it means this network is being reevaluated.
4306 // Either probing private DNS is not necessary any more or it hasn't been
4307 // done yet. In either case, the networkCapabilities should be updated to
4308 // reflect the new status.
4309 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004310 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004311 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004312 }
4313 break;
4314 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004315 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004316 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4317
Erik Kline31b4a9e2018-01-11 21:07:29 +09004318 if (nai == null) break;
4319
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004320 handleNetworkTested(nai, results.mTestResult,
4321 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004322 break;
4323 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004324 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004325 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004326 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004327 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004328 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004329 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004330 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4331 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004332 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004333 if (nai == null) {
4334 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4335 break;
4336 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004337 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004338 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004339 (PendingIntent) msg.obj,
4340 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004341 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004342 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004343 break;
4344 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004345 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004346 if (nai == null) break;
4347
Erik Kline9a62f012018-03-21 07:18:33 -07004348 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004349 break;
4350 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004351 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004352 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004353 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004354 break;
4355 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004356 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004357 return true;
4358 }
4359
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004360 private void handleNetworkTested(
4361 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004362 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4363 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004364 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004365
4366 // If there is any kind of working networking, then the NAI has been evaluated
4367 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4368 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004369 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004370 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004371 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4372 // any callback that receives onAvailable for that rematch receives an extra caps
4373 // callback. To prevent that, update the score in the agent so the updates below won't
4374 // see an update to both caps and score at the same time.
4375 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004376 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4377
he_won.hwang881307a2022-03-15 21:23:52 +09004378 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4379 // Assume the validation failure is due to a temporary failure after roaming
4380 // and ignore it. NetworkMonitor will continue to retry validation. If it
4381 // continues to fail after the block timeout expires, the network will be
4382 // marked unvalidated. If it succeeds, then validation state will not change.
4383 return;
4384 }
4385
Chalard Jean254bd162022-08-25 13:04:51 +09004386 final boolean wasValidated = nai.isValidated();
4387 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004388 final boolean wasPortal = nai.captivePortalDetected();
4389 nai.setPartialConnectivity(partial);
4390 nai.setCaptivePortalDetected(portal);
4391 nai.updateScoreForNetworkAgentUpdate();
4392 final boolean partialConnectivityChanged = (wasPartial != partial);
4393 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004394
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004395 if (DBG) {
4396 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4397 ? " with redirect to " + redirectUrl
4398 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004399 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004400 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004401 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004402 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004403 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004404 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004405 if (valid) {
4406 handleFreshlyValidatedNetwork(nai);
4407 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4408 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004409 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004410 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004411 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004412 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004413 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004414 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004415 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004416 NotificationType.PRIVATE_DNS_BROKEN);
4417 // If network becomes valid, the hasShownBroken should be reset for
4418 // that network so that the notification will be fired when the private
4419 // DNS is broken again.
4420 nai.networkAgentConfig.hasShownBroken = false;
4421 }
4422 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004423 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004424 } else if (portalChanged) {
4425 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004426 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004427 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4428 nai.onPreventAutomaticReconnect();
4429 teardownUnneededNetwork(nai);
4430 return;
4431 } else {
4432 updateCapabilitiesForNetwork(nai);
4433 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004434 } else if (becameEvaluated) {
4435 // If valid or partial connectivity changed, updateCapabilities* has
4436 // done the rematch.
4437 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004438 }
4439 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004440
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004441 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004442 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004443 nai.onValidationStatusChanged(
4444 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4445 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004446
4447 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004448 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004449 // immediately. Re-notify partial connectivity silently if no internet
4450 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004451 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004452 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004453 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4454 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004455 }
4456
Chalard Jean254bd162022-08-25 13:04:51 +09004457 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004458 handleNetworkUnvalidated(nai);
4459 }
4460 }
4461
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004462 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4463 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4464 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4465 // Do not avoid captive portal when network is wear proxy.
4466 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4467 }
4468
Calvin Ondada1452016-10-11 15:10:46 -07004469 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004470 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4471 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004472 }
4473
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004474 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4475 switch (msg.what) {
4476 default:
4477 return false;
4478 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4479 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4480 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4481 handleLingerComplete(nai);
4482 }
4483 break;
4484 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004485 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4486 handleNetworkAgentRegistered(msg);
4487 break;
4488 }
4489 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4490 handleNetworkAgentDisconnected(msg);
4491 break;
4492 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004493 }
4494 return true;
4495 }
4496
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004497 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004498 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004499 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004500 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004501 maybeHandleNetworkAgentMessage(msg);
4502 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004503 }
4504 }
4505
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004506 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004507 private final int mNetId;
4508 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004509
4510 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004511 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004512 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004513 }
4514
4515 @Override
4516 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4517 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004518 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004519 }
4520
4521 @Override
4522 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004523 // Legacy version of notifyNetworkTestedWithExtras.
4524 // Would only be called if the system has a NetworkStack module older than the
4525 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004526 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004527 }
4528
4529 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004530 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004531 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4532 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004533 final Message msg = mTrackerHandler.obtainMessage(
4534 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004535 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004536 new NetworkTestedResults(
4537 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004538 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004539
4540 // Invoke ConnectivityReport generation for this Network test event.
4541 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4542 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004543
Cody Kestingf1120be2020-08-03 18:01:40 -07004544 // NetworkMonitor reports the network validation result as a bitmask while
4545 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4546 // logical value for ConnectivityDiagnostics.
4547 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4548 p.result);
4549
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004550 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004551 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004552 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4553 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4554
Aaron Huang959d3642021-01-21 15:47:41 +08004555 ConnectivityReportEvent reportEvent =
4556 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4557 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004558 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004559 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004560 }
4561
4562 @Override
4563 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4564 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4565 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004566 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004567 }
4568
4569 @Override
lucasline117e2e2019-10-22 18:27:33 +08004570 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4571 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4572 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004573 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004574 }
4575
4576 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004577 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4578 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4579 EVENT_CAPPORT_DATA_CHANGED,
4580 0, mNetId, data));
4581 }
4582
4583 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004584 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004585 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004586 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004587
4588 final PendingIntent pendingIntent;
4589 // Only the system server can register notifications with package "android"
4590 final long token = Binder.clearCallingIdentity();
4591 try {
paulhu7746e4e2020-06-09 19:07:03 +08004592 pendingIntent = PendingIntent.getBroadcast(
4593 mContext,
4594 0 /* requestCode */,
4595 intent,
4596 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004597 } finally {
4598 Binder.restoreCallingIdentity(token);
4599 }
4600 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4601 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004602 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004603 }
4604
4605 @Override
4606 public void hideProvisioningNotification() {
4607 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004608 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004609 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004610
4611 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004612 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004613 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004614 }
4615
4616 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004617 public int getInterfaceVersion() {
4618 return this.VERSION;
4619 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004620
4621 @Override
4622 public String getInterfaceHash() {
4623 return this.HASH;
4624 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004625 }
4626
Cody Kestingf1120be2020-08-03 18:01:40 -07004627 /**
4628 * Converts the given NetworkMonitor-specific validation result bitmask to a
4629 * ConnectivityDiagnostics-specific validation result int.
4630 */
4631 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4632 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4633 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4634 }
4635 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4636 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4637 }
4638 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4639 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4640 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4641 }
4642
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004643 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004644 log("Data stall detected with methods: " + p.detectionMethod);
4645
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004646 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004647 int detectionMethod = 0;
4648 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4649 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4650 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4651 }
4652 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4653 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4654 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4655 p.tcpMetricsCollectionPeriodMillis);
4656 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004657 }
4658
Cody Kestingf53a0752020-04-15 12:33:28 -07004659 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004660 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004661 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004662
4663 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4664 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4665 // the cost of going through two handlers.
4666 mConnectivityDiagnosticsHandler.sendMessage(msg);
4667 }
4668
Cody Kestingb37958e2020-05-15 10:36:01 -07004669 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4670 return (p.detectionMethod & detectionMethod) != 0;
4671 }
4672
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004673 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4674 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004675 }
4676
Erik Klinea73af002018-06-26 18:53:43 +09004677 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4678 if (nai == null) return;
4679 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4680 // in order to restart a validation pass from within netd.
4681 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4682 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004683 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004684 }
4685 }
4686
Erik Kline31b4a9e2018-01-11 21:07:29 +09004687 private void handlePrivateDnsSettingsChanged() {
4688 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4689
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004690 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004691 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004692 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004693 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4694 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004695 }
4696 }
4697
Erik Kline9a62f012018-03-21 07:18:33 -07004698 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4699 // Private DNS only ever applies to networks that might provide
4700 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004701 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004702
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004703 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004704 // schedule DNS resolutions. If a DNS resolution is required the
4705 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004706 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004707
4708 // With Private DNS bypass support, we can proceed to update the
4709 // Private DNS config immediately, even if we're in strict mode
4710 // and have not yet resolved the provider name into a set of IPs.
4711 updatePrivateDns(nai, cfg);
4712 }
4713
4714 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4715 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004716 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004717 }
4718
dalyk1720e542018-03-05 12:42:22 -05004719 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4720 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4721 if (nai == null) {
4722 return;
4723 }
4724 mDnsManager.updatePrivateDnsValidation(update);
4725 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4726 }
4727
paulhu7c0a2e62021-01-08 00:51:49 +08004728 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004729 int prefixLength) {
4730 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4731 if (nai == null) return;
4732
paulhu7c0a2e62021-01-08 00:51:49 +08004733 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4734 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004735
4736 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004737 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004738 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004739 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004740 prefixLength);
4741 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004742 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004743 return;
4744 }
4745 }
4746
Lorenzo Colittid523d142020-04-01 20:16:30 +09004747 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004748 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4749 }
4750
Hai Shalome58bdc62021-01-11 18:45:34 -08004751 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004752 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004753 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004754 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4755 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4756 }
4757
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004758 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004759 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004760 * @param nai the agent info to update
4761 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004762 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004763 */
junyulai2b6f0c22021-02-03 20:15:30 +08004764 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4765 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4766 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004767 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004768 // one lingered request, set inactive.
4769 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004770 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004771 if (DBG) log("Unsetting inactive " + nai.toShortString());
4772 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004773 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004774 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004775 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004776 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4777 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004778 }
junyulai2b6f0c22021-02-03 20:15:30 +08004779 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004780 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004781 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004782 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004783 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004784 }
4785
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004786 private void handleNetworkAgentRegistered(Message msg) {
4787 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4788 if (!mNetworkAgentInfos.contains(nai)) {
4789 return;
4790 }
4791
4792 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4793 if (VDBG) log("NetworkAgent registered");
4794 } else {
4795 loge("Error connecting NetworkAgent");
4796 mNetworkAgentInfos.remove(nai);
4797 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004798 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004799 synchronized (mNetworkForNetId) {
4800 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004801 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004802 mNetIdManager.releaseNetId(nai.network.getNetId());
4803 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004804 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004805 }
4806 }
4807 }
Paul Jensend5f53392014-11-25 15:26:53 -05004808
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004809 @VisibleForTesting
4810 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09004811 // The feature of creating the networks immediately was slated for U, but race conditions
4812 // detected late required this was flagged off.
4813 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
4814 // in NetworkAgentTest.
4815 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004816 }
4817
4818 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4819 @NonNull NetworkInfo.State state) {
4820 if (nai.isCreated()) return false;
4821 if (state == NetworkInfo.State.CONNECTED) return true;
4822 if (state != NetworkInfo.State.CONNECTING) {
4823 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09004824 if (shouldCreateNetworksImmediately()) {
4825 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4826 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004827 return false;
4828 }
4829 return nai.isVPN() || shouldCreateNetworksImmediately();
4830 }
4831
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004832 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004833 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004834 }
4835
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004836 @VisibleForTesting
4837 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004838 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09004839 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004840
4841 // If the network never roamed, return false. The check below is not sufficient if time
4842 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4843 if (nai.lastRoamTime == 0) return false;
4844
he_won.hwang881307a2022-03-15 21:23:52 +09004845 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4846 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004847 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004848 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004849 final long currentTimeMs = SystemClock.elapsedRealtime();
4850 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004851 if (timeSinceLastRoam <= blockTimeOut) {
4852 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4853 return true;
4854 }
4855 }
4856 return false;
4857 }
4858
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004859 private void handleNetworkAgentDisconnected(Message msg) {
4860 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004861 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004862 }
4863
Chalard Jeand9fffc32018-05-11 20:19:20 +09004864 // Destroys a network, remove references to it from the internal state managed by
4865 // ConnectivityService, free its interfaces and clean up.
4866 // Must be called on the Handler thread.
4867 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004868 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004869
4870 if (!mNetworkAgentInfos.contains(nai)) return;
4871
Chalard Jeand9fffc32018-05-11 20:19:20 +09004872 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004873 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004874 }
lucaslinb25c9a62019-02-12 15:30:13 +08004875 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004876 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004877 // A network agent has disconnected.
4878 // TODO - if we move the logic to the network agent (have them disconnect
4879 // because they lost all their requests or because their score isn't good)
4880 // then they would disconnect organically, report their new state and then
4881 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08004882 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004883 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4884 null, null);
4885 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004886 final boolean wasDefault = isDefaultNetwork(nai);
4887 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004888 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004889 }
4890 notifyIfacesChangedForNetworkStats();
4891 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4892 // by other networks that are already connected. Perhaps that can be done by
4893 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4894 // of rematchAllNetworksAndRequests
4895 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004896 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004897
4898 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004899 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4900 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08004901 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004902 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004903 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004904 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004905 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004906 synchronized (mNetworkForNetId) {
4907 // Remove the NetworkAgent, but don't mark the netId as
4908 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004909 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004910 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004911 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08004912 // Update allowed network lists in netd. This should be called after removing nai
4913 // from mNetworkAgentInfos.
4914 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004915 // Remove all previously satisfied requests.
4916 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004917 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004918 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004919 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004920 if (currentNetwork != null
4921 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004922 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004923 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4924 // rematch not to keep disconnected agents instead of setting it here ; this
4925 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004926 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004927 for (final NetworkOfferInfo noi : mNetworkOffers) {
4928 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004929 }
James Mattise3ef1912020-12-20 11:09:58 -08004930
Chalard Jean5b409c72021-02-04 13:12:59 +09004931 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004932 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004933 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004934 // network, because while incorrect this is the closest to the old (also
4935 // incorrect) behavior.
4936 mNetworkActivityTracker.updateDataActivityTracking(
4937 null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004938 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004939 ensureNetworkTransitionWakelock(nai.toShortString());
4940 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004941 }
4942 }
junyulai2b6f0c22021-02-03 20:15:30 +08004943 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004944 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004945 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004946 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004947 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004948 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004949 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004950
Aaron Huang9fe47be2021-06-08 13:11:45 +08004951 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
4952 // The obvious place to do this would be in makeDefault(), however makeDefault() is
4953 // not called by the rematch in this case. This is because the code above unset
4954 // this network from the default request's satisfier, and that is what the rematch
4955 // is using as its source data to know what the old satisfier was. So as far as the
4956 // rematch above is concerned, the old default network was null.
4957 // Therefore if there is no new default, the default network was null and is still
4958 // null, thus there was no change so makeDefault() is not called. So if the old
4959 // network had a proxy and there is no new default, the proxy tracker should be told
4960 // that there is no longer a default proxy.
4961 // Strictly speaking this is not essential because having a proxy setting when
4962 // there is no network is harmless, but it's still counter-intuitive so reset to null.
4963 mProxyTracker.setDefaultProxy(null);
4964 }
4965
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004966 // Immediate teardown.
4967 if (nai.teardownDelayMs == 0) {
4968 destroyNetwork(nai);
4969 return;
4970 }
4971
4972 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004973 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304974 try {
4975 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4976 } catch (RemoteException e) {
4977 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4978 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004979 }
4980 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4981 }
4982
4983 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004984 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004985 // Tell netd to clean up the configuration for this network
4986 // (routing rules, DNS, etc).
4987 // This may be slow as it requires a lot of netd shelling out to ip and
4988 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004989 // after we've rematched networks with requests (which might change the default
4990 // network or service a new request from an app), so network traffic isn't interrupted
4991 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004992 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004993 }
Chalard Jeandf29a852023-05-29 17:02:43 +09004994 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004995 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4996 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4997 // false if the network was never created.
4998 // TODO: delete when S is no longer supported.
4999 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005000 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08005001 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005002 }
5003
Ken Chen6df7a902021-04-09 15:08:42 +08005004 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08005005 try {
5006 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005007 final NativeNetworkConfig config;
5008 if (nai.isVPN()) {
5009 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005010 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005011 return false;
5012 }
5013 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5014 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005015 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005016 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005017 } else {
Anton Kulakovcc409152023-10-13 15:04:01 +00005018 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005019 getNetworkPermission(nai.networkCapabilities),
5020 false /* secure */,
5021 VpnManager.TYPE_VPN_NONE,
5022 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005023 }
Ken Chen6df7a902021-04-09 15:08:42 +08005024 mNetd.networkCreate(config);
5025 mDnsResolver.createNetworkCache(nai.network.getNetId());
5026 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
5027 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08005028 return true;
5029 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005030 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005031 return false;
5032 }
5033 }
5034
Ken Chen6df7a902021-04-09 15:08:42 +08005035 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005036 if (mDscpPolicyTracker != null) {
5037 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5038 }
Luke Huangfdd11f82019-04-09 18:41:49 +08005039 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005040 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005041 } catch (RemoteException | ServiceSpecificException e) {
5042 loge("Exception destroying network(networkDestroy): " + e);
5043 }
5044 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005045 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005046 } catch (RemoteException | ServiceSpecificException e) {
5047 loge("Exception destroying network: " + e);
5048 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005049 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5050 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5051 // gets created, could add data to DnsManager data structures that will never get deleted.
5052 mDnsManager.removeNetwork(nai.network);
5053
5054 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005055 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005056 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5057 }
5058
Chalard Jean254bd162022-08-25 13:04:51 +09005059 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005060 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005061 }
5062
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005063 // If this method proves to be too slow then we can maintain a separate
5064 // pendingIntent => NetworkRequestInfo map.
5065 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5066 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005067 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5068 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5069 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005070 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005071 return entry.getValue();
5072 }
5073 }
5074 return null;
5075 }
5076
Chalard Jean524f0b12021-10-25 21:11:56 +09005077 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005078 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005079 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5080 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5081 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5082 // bug is fixed.
5083 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005084 throw new IllegalStateException("This NRI is already registered. New : " + nri
5085 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005086 }
5087 }
5088 }
5089 }
5090
Chalard Jeanac9ace02022-01-26 16:54:05 +09005091 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5092 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005093 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09005094 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
5095 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005096 }
5097 return false;
5098 }
5099
James Mattisf7027322020-12-13 16:28:14 -08005100 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005101 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005102 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5103 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5104 final NetworkRequestInfo existingRequest =
5105 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005106 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005107 if (DBG) {
5108 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5109 + nri.mRequests.get(0) + " because their intents matched.");
5110 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005111 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005112 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005113 }
Erik Kline05f2b402015-04-30 12:58:40 +09005114 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005115 }
5116
James Mattisf7027322020-12-13 16:28:14 -08005117 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005118 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005119 }
5120
James Mattis3ce3d3c2021-02-09 18:18:28 -08005121 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005122 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005123 for (final NetworkRequestInfo nri : nris) {
5124 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005125 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005126 for (final NetworkRequest req : nri.mRequests) {
5127 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005128 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005129 if (req.isListen()) {
5130 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5131 if (req.networkCapabilities.hasSignalStrength()
5132 && network.satisfiesImmutableCapabilitiesOf(req)) {
5133 updateSignalStrengthThresholds(network, "REGISTER", req);
5134 }
James Mattisf7027322020-12-13 16:28:14 -08005135 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005136 }
5137 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005138
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005139 // If this NRI has a satisfier already, it is replacing an older request that
5140 // has been removed. Track it.
5141 final NetworkRequest activeRequest = nri.getActiveRequest();
5142 if (null != activeRequest) {
5143 // If there is an active request, then for sure there is a satisfier.
5144 nri.getSatisfier().addRequest(activeRequest);
5145 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005146 }
James Mattisf7027322020-12-13 16:28:14 -08005147
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005148 if (mFlags.noRematchAllRequestsOnRegister()) {
5149 rematchNetworksAndRequests(nris);
5150 } else {
5151 rematchAllNetworksAndRequests();
5152 }
James Mattis45d81842021-01-10 14:24:24 -08005153
Chalard Jean0354d8c2021-01-12 10:58:56 +09005154 // Requests that have not been matched to a network will not have been sent to the
5155 // providers, because the old satisfier and the new satisfier are the same (null in this
5156 // case). Send these requests to the providers.
5157 for (final NetworkRequestInfo nri : nris) {
5158 for (final NetworkOfferInfo noi : mNetworkOffers) {
5159 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005160 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005161 }
5162 }
5163
James Mattisf7027322020-12-13 16:28:14 -08005164 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5165 final int callingUid) {
5166 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005167 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005168 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5169 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5170 handleReleaseNetworkRequest(
5171 nri.mRequests.get(0),
5172 callingUid,
5173 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005174 }
5175 }
5176
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005177 // Determines whether the network is the best (or could become the best, if it validated), for
5178 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5179 // on the value of reason:
5180 //
5181 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5182 // then it should be torn down.
5183 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5184 // then it should be lingered.
5185 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005186 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005187
Chalard Jean254bd162022-08-25 13:04:51 +09005188 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005189 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5190 return false;
5191 }
5192
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005193 final int numRequests;
5194 switch (reason) {
5195 case TEARDOWN:
5196 numRequests = nai.numRequestNetworkRequests();
5197 break;
5198 case LINGER:
5199 numRequests = nai.numForegroundNetworkRequests();
5200 break;
5201 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005202 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005203 return true;
5204 }
5205
Chalard Jean947acd42021-03-08 22:29:27 +09005206 if (numRequests > 0) return false;
5207
Paul Jensende49eb12015-06-25 15:30:08 -04005208 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005209 if (reason == UnneededFor.LINGER
5210 && !nri.isMultilayerRequest()
5211 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005212 // Background requests don't affect lingering.
5213 continue;
5214 }
5215
James Mattis3d229892020-11-16 16:46:28 -08005216 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005217 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005218 }
5219 }
Paul Jensende49eb12015-06-25 15:30:08 -04005220 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005221 }
5222
James Mattis3d229892020-11-16 16:46:28 -08005223 private boolean isNetworkPotentialSatisfier(
5224 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
5225 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005226 // request, return immediately. For multilayer requests, check to see if any of the
5227 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005228 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5229 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005230 return false;
5231 }
5232 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005233 // This multilayer listen request is satisfied therefore no further requests need to be
5234 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005235 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005236 return false;
5237 }
James Mattis3d229892020-11-16 16:46:28 -08005238 // As non-multilayer listen requests have already returned, the below would only happen
5239 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005240 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005241 continue;
5242 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09005243 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08005244 // there is hope for it to become one if it validated, then it is needed.
5245 if (candidate.satisfies(req)) {
5246 // As soon as a network is found that satisfies a request, return. Specifically for
5247 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5248 // is important so as to not evaluate lower priority requests further in
5249 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005250 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5251 ? nri.getSatisfier() : null;
5252 // Note that this catches two important cases:
5253 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5254 // is currently satisfying the request. This is desirable when
5255 // cellular ends up validating but WiFi does not.
5256 // 2. Unvalidated WiFi will not be reaped when validated cellular
5257 // is currently satisfying the request. This is desirable when
5258 // WiFi ends up validating and out scoring cellular.
5259 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005260 }
5261 }
5262
5263 return false;
5264 }
5265
Erik Kline0c04b742016-07-07 16:50:58 +09005266 private NetworkRequestInfo getNriForAppRequest(
5267 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005268 // Looking up the app passed param request in mRequests isn't possible since it may return
5269 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5270 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005271 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5272 // to avoid potential race conditions when validating a package->uid mapping when sending
5273 // the callback on the very low-chance that an application shuts down prior to the callback
5274 // being sent.
5275 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5276 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005277
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005278 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005279 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005280 log(String.format("UID %d attempted to %s for unowned request %s",
5281 callingUid, requestedOperation, nri));
5282 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005283 }
Erik Kline0c04b742016-07-07 16:50:58 +09005284 }
5285
5286 return nri;
5287 }
5288
James Mattisf7027322020-12-13 16:28:14 -08005289 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5290 final String callingMethod) {
5291 if (nri.isMultilayerRequest()) {
5292 throw new IllegalStateException(
5293 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005294 }
5295 }
5296
James Mattisf7027322020-12-13 16:28:14 -08005297 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005298 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005299 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5300 // single NetworkRequest and thus does not apply to multilayer requests.
5301 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5302 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005303 return;
5304 }
James Mattis2516da32021-01-31 17:06:19 -08005305 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005306 return;
5307 }
James Mattisf7027322020-12-13 16:28:14 -08005308 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5309 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005310 }
5311 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005312 callCallbackForRequest(
5313 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005314 }
5315
James Mattisf7027322020-12-13 16:28:14 -08005316 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5317 final int callingUid,
5318 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005319 final NetworkRequestInfo nri =
5320 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5321 if (nri == null) {
5322 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005323 }
James Mattisf7027322020-12-13 16:28:14 -08005324 if (VDBG || (DBG && request.isRequest())) {
5325 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005326 }
5327 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005328 if (callOnUnavailable) {
5329 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5330 }
Erik Kline155a59a2015-11-25 12:49:38 +09005331 }
Erik Kline0c04b742016-07-07 16:50:58 +09005332
James Mattisa076c532020-12-02 14:12:41 -08005333 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005334 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005335 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005336 if (null == mNetworkRequests.remove(req)) {
5337 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5338 continue;
5339 }
James Mattisa076c532020-12-02 14:12:41 -08005340 if (req.isListen()) {
5341 removeListenRequestFromNetworks(req);
5342 }
5343 }
James Mattis8f036802021-06-20 16:26:01 -07005344 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005345 if (mDefaultNetworkRequests.remove(nri)) {
5346 // If this request was one of the defaults, then the UID rules need to be updated
5347 // WARNING : if the app(s) for which this network request is the default are doing
5348 // traffic, this will kill their connected sockets, even if an equivalent request
5349 // is going to be reinstated right away ; unconnected traffic will go on the default
5350 // until the new default is set, which will happen very soon.
5351 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5352 // remove ranges for those requests that won't have a replacement
5353 final NetworkAgentInfo satisfier = nri.getSatisfier();
5354 if (null != satisfier) {
5355 try {
paulhu0e79d952021-06-09 16:11:35 +08005356 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5357 satisfier.network.getNetId(),
5358 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005359 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005360 } catch (RemoteException e) {
5361 loge("Exception setting network preference default network", e);
5362 }
5363 }
5364 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005365
Junyu Lai00d92df2022-07-05 11:01:52 +08005366 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005367 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005368 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005369
5370 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005371 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005372 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005373 }
5374 }
5375
Chalard Jean0354d8c2021-01-12 10:58:56 +09005376 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5377 // needed for this offer.
5378 for (final NetworkOfferInfo noi : mNetworkOffers) {
5379 for (final NetworkRequest req : nri.mRequests) {
5380 if (req.isRequest() && noi.offer.neededFor(req)) {
5381 noi.offer.onNetworkUnneeded(req);
5382 }
5383 }
5384 }
James Mattisa076c532020-12-02 14:12:41 -08005385 }
5386
James Mattis3ce3d3c2021-02-09 18:18:28 -08005387 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5388 for (final NetworkRequestInfo nri : nris) {
5389 if (mDefaultRequest == nri) {
5390 // Make sure we never remove the default request.
5391 continue;
5392 }
5393 handleRemoveNetworkRequest(nri);
5394 }
5395 }
5396
James Mattisa076c532020-12-02 14:12:41 -08005397 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5398 // listens don't have a singular affected Network. Check all networks to see
5399 // if this listen request applies and remove it.
5400 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5401 nai.removeRequest(req.requestId);
5402 if (req.networkCapabilities.hasSignalStrength()
5403 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5404 updateSignalStrengthThresholds(nai, "RELEASE", req);
5405 }
5406 }
5407 }
5408
5409 /**
5410 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5411 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5412 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5413 */
5414 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5415 boolean wasKept = false;
5416 final NetworkAgentInfo nai = nri.getSatisfier();
5417 if (nai != null) {
5418 final int requestLegacyType = nri.getActiveRequest().legacyType;
5419 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5420 nai.removeRequest(nri.getActiveRequest().requestId);
5421 if (VDBG || DDBG) {
5422 log(" Removing from current network " + nai.toShortString()
5423 + ", leaving " + nai.numNetworkRequests() + " requests.");
5424 }
5425 // If there are still lingered requests on this network, don't tear it down,
5426 // but resume lingering instead.
5427 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005428 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005429 notifyNetworkLosing(nai, now);
5430 }
5431 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5432 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5433 teardownUnneededNetwork(nai);
5434 } else {
5435 wasKept = true;
5436 }
James Mattisa076c532020-12-02 14:12:41 -08005437 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5438 // Went from foreground to background.
5439 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005440 }
5441
Erik Kline0c04b742016-07-07 16:50:58 +09005442 // Maintain the illusion. When this request arrived, we might have pretended
5443 // that a network connected to serve it, even though the network was already
5444 // connected. Now that this request has gone away, we might have to pretend
5445 // that the network disconnected. LegacyTypeTracker will generate that
5446 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005447 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005448 boolean doRemove = true;
5449 if (wasKept) {
5450 // check if any of the remaining requests for this network are for the
5451 // same legacy type - if so, don't remove the nai
5452 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5453 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005454 if (otherRequest.legacyType == requestLegacyType
5455 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005456 if (DBG) log(" still have other legacy request - leaving");
5457 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005458 }
5459 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005460 }
5461
Erik Kline0c04b742016-07-07 16:50:58 +09005462 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005463 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005464 }
5465 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005466 }
5467 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005468
Junyu Lai00d92df2022-07-05 11:01:52 +08005469 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005470 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005471 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5472 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5473 }
5474
Lorenzo Colittid6459092016-07-04 12:55:44 +09005475 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005476 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005477 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005478 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005479 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005480 }
5481
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005482 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005483 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5484 enforceNetworkStackSettingsOrSetup();
5485 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5486 encodeBool(accept), encodeBool(always), network));
5487 }
5488
5489 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005490 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005491 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005492 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5493 }
5494
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005495 @Override
5496 public void setTestAllowBadWifiUntil(long timeMs) {
5497 enforceSettingsPermission();
5498 if (!Build.isDebuggable()) {
5499 throw new IllegalStateException("Does not support in non-debuggable build");
5500 }
5501
5502 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5503 throw new IllegalArgumentException("It should not exceed "
5504 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5505 }
5506
5507 mHandler.sendMessage(
5508 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5509 }
5510
chiachangwange0192a72023-02-06 13:25:01 +00005511 @Override
5512 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5513 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005514
5515 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5516 throw new IllegalArgumentException("Argument should not exceed "
5517 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5518 }
5519
5520 mHandler.sendMessage(
5521 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5522 }
5523
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005524 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5525 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5526 " accept=" + accept + " always=" + always);
5527
5528 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5529 if (nai == null) {
5530 // Nothing to do.
5531 return;
5532 }
5533
Chalard Jean254bd162022-08-25 13:04:51 +09005534 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005535 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005536 return;
5537 }
5538
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005539 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005540 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005541 }
5542
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005543 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5544 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005545 // If network becomes partial connectivity and user already accepted to use this
5546 // network, we should respect the user's option and don't need to popup the
5547 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005548 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005549 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005550 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005551 }
5552
5553 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005554 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005555 }
5556
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005557 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005558 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005559 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005560 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005561 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005562 }
5563
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005564 }
5565
lucaslin2240ef62019-03-12 13:08:03 +08005566 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5567 boolean always) {
5568 if (DBG) {
5569 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5570 + " always=" + always);
5571 }
5572
5573 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5574 if (nai == null) {
5575 // Nothing to do.
5576 return;
5577 }
5578
Chalard Jean254bd162022-08-25 13:04:51 +09005579 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005580 // The network validated while the dialog box was up. Take no action.
5581 return;
5582 }
5583
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005584 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5585 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005586 }
5587
5588 // TODO: Use the current design or save the user choice into IpMemoryStore.
5589 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005590 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005591 }
5592
5593 if (!accept) {
5594 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005595 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005596 // Tear down the network.
5597 teardownUnneededNetwork(nai);
5598 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005599 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5600 // result in a partial connectivity result which will be processed by
5601 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005602 //
5603 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5604 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005605 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005606 }
5607 }
5608
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005609 private void handleSetAvoidUnvalidated(Network network) {
5610 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005611 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005612 // Nothing to do. The network either disconnected or revalidated.
5613 return;
5614 }
Chalard Jean254bd162022-08-25 13:04:51 +09005615 if (0L == nai.getAvoidUnvalidated()) {
5616 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005617 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005618 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005619 }
5620 }
5621
Chalard Jean5fb43c72022-09-08 19:03:14 +09005622 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005623 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005624 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005625 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005626 }
5627
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005628 @Override
5629 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005630 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005631 mHandler.post(() -> {
5632 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5633 if (nai == null) return;
5634 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005635 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005636 });
5637 }
5638
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005639 /**
5640 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5641 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005642 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005643 * @param appExtras Bundle to use as intent extras for the captive portal application.
5644 * Must be treated as opaque to avoid preventing the captive portal app to
5645 * update its arguments.
5646 */
5647 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005648 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005649 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5650 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005651
5652 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5653 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005654 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5655 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005656 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5657
lucaslin75ff7022020-12-17 04:14:35 +08005658 final long token = Binder.clearCallingIdentity();
5659 try {
5660 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5661 } finally {
5662 Binder.restoreCallingIdentity(token);
5663 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005664 }
5665
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005666 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5667 private final Network mNetwork;
5668
5669 private CaptivePortalImpl(Network network) {
5670 mNetwork = network;
5671 }
5672
5673 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005674 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005675 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5676 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005677 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5678 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5679 // Since the network will be disconnected, skip notifying NetworkMonitor
5680 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005681 }
5682
Chiachang Wang938bfba2020-01-09 13:50:55 +08005683 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005684 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005685 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005686 }
5687
5688 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005689 public void appRequest(final int request) {
5690 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5691 if (nm == null) return;
5692
5693 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005694 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005695 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005696 }
5697 }
5698
5699 @Nullable
5700 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5701 // getNetworkAgentInfoForNetwork is thread-safe
5702 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5703 if (nai == null) return null;
5704
5705 // nai.networkMonitor() is thread-safe
5706 return nai.networkMonitor();
5707 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005708 }
5709
Hugo Benichic9048bc2016-09-14 23:23:08 +00005710 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005711 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005712 }
5713
Chalard Jean020b93a2022-09-01 13:20:14 +09005714 private boolean activelyPreferBadWifi() {
5715 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5716 }
5717
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005718 /**
5719 * Return whether the device should maintain continuous, working connectivity by switching away
5720 * from WiFi networks having no connectivity.
5721 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5722 */
5723 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005724 if (!checkNetworkStackPermission()) {
5725 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5726 }
5727 return avoidBadWifi();
5728 }
5729
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005730 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005731 ensureRunningOnConnectivityServiceThread();
5732 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005733 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005734 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005735 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005736 if (avoidBadWifi) {
5737 // If the device is now avoiding bad wifi, remove notifications that might have
5738 // been put up when the device didn't.
5739 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5740 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005741 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005742 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5743 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5744 for (final NetworkOfferInfo noi : offersToUpdate) {
5745 updateOfferScore(noi.offer);
5746 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005747 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005748 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005749 }
5750
Erik Kline95ecfee2016-10-02 18:02:14 +09005751 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005752 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005753 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005754 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005755 if (!configRestrict) {
5756 pw.println("Bad Wi-Fi avoidance: unrestricted");
5757 return;
5758 }
5759
5760 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5761 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005762 pw.println("Config restrict: " + configRestrict);
5763 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005764
Chalard Jeane0fdea32022-09-14 21:44:22 +09005765 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005766 String description;
5767 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005768 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005769 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005770 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005771 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005772 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005773 description = "avoid";
5774 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005775 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005776 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005777 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005778
5779 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5780 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005781 if (null == configValue) {
5782 description = "unset";
5783 } else if (configValue) {
5784 description = "force true";
5785 } else {
5786 description = "force false";
5787 }
5788 pw.println("Actively prefer bad wifi conf: " + description);
5789 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005790 pw.println("Network overrides:");
5791 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005792 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005793 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005794 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005795 }
5796 }
5797 pw.decreaseIndent();
5798 pw.decreaseIndent();
5799 }
5800
paulhu7746e4e2020-06-09 19:07:03 +08005801 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5802 // unify the method.
5803 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5804 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5805 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5806 return settingsComponent != null
5807 ? settingsComponent.getPackageName() : "com.android.settings";
5808 }
5809
lucaslinb1e8e382019-01-24 15:55:30 +08005810 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005811 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005812 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005813 switch (type) {
5814 case NO_INTERNET:
5815 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005816 // High priority because it is only displayed for explicitly selected networks.
5817 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005818 break;
lucasline117e2e2019-10-22 18:27:33 +08005819 case PRIVATE_DNS_BROKEN:
5820 action = Settings.ACTION_WIRELESS_SETTINGS;
5821 // High priority because we should let user know why there is no internet.
5822 highPriority = true;
5823 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005824 case LOST_INTERNET:
5825 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005826 // High priority because it could help the user avoid unexpected data usage.
5827 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005828 break;
lucaslin2240ef62019-03-12 13:08:03 +08005829 case PARTIAL_CONNECTIVITY:
5830 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005831 // Don't bother the user with a high-priority notification if the network was not
5832 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005833 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005834 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005835 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005836 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005837 return;
5838 }
5839
5840 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005841 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005842 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005843 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005844 // Some OEMs have their own Settings package. Thus, need to get the current using
5845 // Settings package name instead of just use default name "com.android.settings".
5846 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5847 intent.setClassName(settingsPkgName,
5848 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005849 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005850
paulhu2af50222020-10-11 22:52:27 +08005851 PendingIntent pendingIntent = PendingIntent.getActivity(
5852 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005853 0 /* requestCode */,
5854 intent,
paulhu2af50222020-10-11 22:52:27 +08005855 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005856
Serik Beketayevec8ad212020-12-07 22:43:07 -08005857 mNotifier.showNotification(
5858 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005859 }
5860
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005861 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5862 // Don't prompt if the network is validated, and don't prompt on captive portals
5863 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005864 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005865 return false;
5866 }
5867
5868 // If a network has partial connectivity, always prompt unless the user has already accepted
5869 // partial connectivity and selected don't ask again. This ensures that if the device
5870 // automatically connects to a network that has partial Internet access, the user will
5871 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005872 // because we have prompted them.
5873 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005874 return true;
5875 }
5876
5877 // If a network has no Internet access, only prompt if the network was explicitly selected
5878 // and if the user has not already told us to use the network regardless of whether it
5879 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005880 if (nai.networkAgentConfig.explicitlySelected
5881 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005882 return true;
5883 }
5884
5885 return false;
5886 }
5887
Chalard Jean5fb43c72022-09-08 19:03:14 +09005888 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5889 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005890
Chalard Jean5fb43c72022-09-08 19:03:14 +09005891 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5892 if (null == nai) return;
5893
5894 if (nai.setEvaluated()) {
5895 // If setEvaluated() returned true, the network never had any form of connectivity.
5896 // This may have an impact on request matching if bad WiFi avoidance is off and the
5897 // network was found not to have Internet access.
5898 nai.updateScoreForNetworkAgentUpdate();
5899 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005900
5901 // Also, if this is WiFi and it should be preferred actively, now is the time to
5902 // prompt the user that they walked past and connected to a bad WiFi.
5903 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5904 && !avoidBadWifi()
5905 && activelyPreferBadWifi()) {
5906 // The notification will be removed if the network validates or disconnects.
5907 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5908 return;
5909 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005910 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005911
Chalard Jean5fb43c72022-09-08 19:03:14 +09005912 if (!shouldPromptUnvalidated(nai)) return;
5913
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005914 // Stop automatically reconnecting to this network in the future. Automatically connecting
5915 // to a network that provides no or limited connectivity is not useful, because the user
5916 // cannot use that network except through the notification shown by this method, and the
5917 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005918 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005919
Chalard Jean254bd162022-08-25 13:04:51 +09005920 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005921 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005922 } else {
5923 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5924 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005925 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005926
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005927 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5928 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005929 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005930
lucaslin2240ef62019-03-12 13:08:03 +08005931 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5932 return;
5933 }
5934
5935 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005936 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005937 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005938 }
5939
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005940 @Override
5941 public int getMultipathPreference(Network network) {
5942 enforceAccessPermission();
5943
5944 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005945 if (nai != null && nai.networkCapabilities
5946 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005947 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5948 }
5949
Aaron Huang9a57acf2020-12-08 10:03:29 +08005950 final NetworkPolicyManager netPolicyManager =
5951 mContext.getSystemService(NetworkPolicyManager.class);
5952
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005953 final long token = Binder.clearCallingIdentity();
5954 final int networkPreference;
5955 try {
5956 networkPreference = netPolicyManager.getMultipathPreference(network);
5957 } finally {
5958 Binder.restoreCallingIdentity(token);
5959 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005960 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005961 return networkPreference;
5962 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005963 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5964 }
5965
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005966 @Override
5967 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005968 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005969 }
5970
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005971 private class InternalHandler extends Handler {
5972 public InternalHandler(Looper looper) {
5973 super(looper);
5974 }
5975
5976 @Override
5977 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005978 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005979 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005980 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005981 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005982 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005983 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005984 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005985 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005986 break;
5987 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08005988 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005989 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08005990 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005991 break;
5992 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005993 case EVENT_REGISTER_NETWORK_PROVIDER: {
5994 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005995 break;
5996 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005997 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5998 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005999 break;
6000 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006001 case EVENT_REGISTER_NETWORK_OFFER: {
6002 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
6003 break;
6004 }
6005 case EVENT_UNREGISTER_NETWORK_OFFER: {
6006 final NetworkOfferInfo offer =
6007 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6008 if (null != offer) {
6009 handleUnregisterNetworkOffer(offer);
6010 }
6011 break;
6012 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006013 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006014 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6015 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6016 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006017 break;
6018 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006019 case EVENT_REGISTER_NETWORK_REQUEST:
6020 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006021 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006022 break;
6023 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006024 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6025 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006026 handleRegisterNetworkRequestWithIntent(msg);
6027 break;
6028 }
Erik Kline155a59a2015-11-25 12:49:38 +09006029 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6030 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6031 handleTimedOutNetworkRequest(nri);
6032 break;
6033 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006034 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6035 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6036 break;
6037 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006038 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006039 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6040 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006041 break;
6042 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006043 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006044 Network network = (Network) msg.obj;
6045 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006046 break;
6047 }
lucaslin2240ef62019-03-12 13:08:03 +08006048 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6049 Network network = (Network) msg.obj;
6050 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6051 toBool(msg.arg2));
6052 break;
6053 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006054 case EVENT_SET_AVOID_UNVALIDATED: {
6055 handleSetAvoidUnvalidated((Network) msg.obj);
6056 break;
6057 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006058 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6059 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006060 break;
6061 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006062 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6063 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006064 break;
6065 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006066 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6067 // handler thread.
6068 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006069 mKeepaliveTracker.handleStartKeepalive(msg);
6070 break;
6071 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006072 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006073 final AutomaticOnOffKeepalive ki =
6074 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6075 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006076
chiachangwang676c84e2023-02-14 09:22:05 +00006077 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006078 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006079 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006080 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006081 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6082 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006083 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6084 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006085 }
6086 }
6087
6088 // If the network no longer exists, then the keepalive should have been
6089 // cleaned up already. There is no point trying to resume keepalives.
6090 if (!networkFound) return;
6091
chiachangwang676c84e2023-02-14 09:22:05 +00006092 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006093 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang676c84e2023-02-14 09:22:05 +00006094 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006095 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006096 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006097 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006098 }
6099 break;
6100 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006101 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006102 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006103 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6104 (IBinder) msg.obj);
6105 if (ki == null) {
6106 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006107 return;
6108 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006109 final int reason = msg.arg2;
6110 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006111 break;
6112 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006113 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6114 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6115 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006116 break;
6117 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006118 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6119 handlePrivateDnsSettingsChanged();
6120 break;
dalyk1720e542018-03-05 12:42:22 -05006121 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6122 handlePrivateDnsValidationUpdate(
6123 (PrivateDnsValidationUpdate) msg.obj);
6124 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006125 case EVENT_UID_BLOCKED_REASON_CHANGED:
6126 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006127 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006128 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6129 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6130 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006131 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006132 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6133 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006134 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006135 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006136 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006137 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006138 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6139 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006140 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006141 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006142 }
lucaslin1193a5d2021-01-21 02:04:15 +08006143 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006144 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006145 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006146 break;
paulhu51f77dc2021-06-07 02:34:20 +00006147 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6148 handleMobileDataPreferredUidsChanged();
6149 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006150 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6151 final long timeMs = ((Long) msg.obj).longValue();
6152 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6153 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006154 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6155 handleIngressRateLimitChanged();
6156 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006157 case EVENT_USER_DOES_NOT_WANT:
6158 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6159 if (nai == null) break;
6160 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006161 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006162 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006163 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6164 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6165 break;
chiachangwange0192a72023-02-06 13:25:01 +00006166 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6167 final long time = ((Long) msg.obj).longValue();
6168 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6169 break;
6170 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006171 case EVENT_UID_FROZEN_STATE_CHANGED:
6172 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6173 handleFrozenUids(args.mUids, args.mFrozenStates);
6174 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006175 }
6176 }
6177 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006178
Lorenzo Colittid6459092016-07-04 12:55:44 +09006179 @Override
markchien5776f962019-12-16 20:15:20 +08006180 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006181 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006182 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006183 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6184 Context.TETHERING_SERVICE);
6185 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006186 }
6187
Lorenzo Colittid6459092016-07-04 12:55:44 +09006188 @Override
markchien5776f962019-12-16 20:15:20 +08006189 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006190 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006191 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006192 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6193 Context.TETHERING_SERVICE);
6194 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006195 }
6196
Lorenzo Colittid6459092016-07-04 12:55:44 +09006197 @Override
markchien5776f962019-12-16 20:15:20 +08006198 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006199 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006200 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006201 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6202 Context.TETHERING_SERVICE);
6203 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006204 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006205
markchien5776f962019-12-16 20:15:20 +08006206
Lorenzo Colittid6459092016-07-04 12:55:44 +09006207 @Override
markchien5776f962019-12-16 20:15:20 +08006208 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006209 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006210 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006211 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6212 Context.TETHERING_SERVICE);
6213
6214 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006215 }
6216
Lorenzo Colittid6459092016-07-04 12:55:44 +09006217 @Override
markchien5776f962019-12-16 20:15:20 +08006218 @Deprecated
6219 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006220 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006221 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6222 Context.TETHERING_SERVICE);
6223
6224 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006225 }
6226
Udam Saini8f7d6a72017-06-07 12:06:28 -07006227 @Override
markchien5776f962019-12-16 20:15:20 +08006228 @Deprecated
6229 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006230 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006231 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6232 Context.TETHERING_SERVICE);
6233 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006234 }
6235
Robert Greenwalte0b00512014-07-02 09:59:16 -07006236 // Called when we lose the default network and have no replacement yet.
6237 // This will automatically be cleared after X seconds or a new default network
6238 // becomes CONNECTED, whichever happens first. The timer is started by the
6239 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006240 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006241 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006242 if (mNetTransitionWakeLock.isHeld()) {
6243 return;
6244 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006245 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006246 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6247 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006248 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006249 mWakelockLogs.log("ACQUIRE for " + forWhom);
6250 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006251 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006252 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006253 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006254 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006255
Hugo Benichi471b62a2017-03-30 23:18:10 +09006256 // Called when we gain a new default network to release the network transition wakelock in a
6257 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6258 // message is cancelled.
6259 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006260 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006261 if (!mNetTransitionWakeLock.isHeld()) {
6262 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006263 }
6264 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006265 // Cancel self timeout on wakelock hold.
6266 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6267 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6268 mHandler.sendMessageDelayed(msg, 1000);
6269 }
6270
6271 // Called when either message of ensureNetworkTransitionWakelock or
6272 // scheduleReleaseNetworkTransitionWakelock is processed.
6273 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6274 String event = eventName(eventId);
6275 synchronized (this) {
6276 if (!mNetTransitionWakeLock.isHeld()) {
6277 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006278 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006279 return;
6280 }
6281 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006282 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6283 mTotalWakelockDurationMs += lockDuration;
6284 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6285 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006286 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006287 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006288 }
6289
Robert Greenwalt986c7412010-09-08 15:24:47 -07006290 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006291 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006292 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006293 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006294 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006295 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006296 }
6297
Lorenzo Colittid6459092016-07-04 12:55:44 +09006298 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006299 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006300 enforceAccessPermission();
6301 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006302 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006303 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006304
6305 final NetworkAgentInfo nai;
6306 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006307 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006308 } else {
6309 nai = getNetworkAgentInfoForNetwork(network);
6310 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006311
6312 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006313 mHandler.obtainMessage(
6314 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006315 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006316
Hugo Benichid6b510a2017-04-06 17:22:18 +09006317 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006318 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006319 if (nai == null
6320 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006321 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006322 return;
6323 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006324 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006325 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006326 mConnectivityDiagnosticsHandler.sendMessage(
6327 mConnectivityDiagnosticsHandler.obtainMessage(
6328 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6329 new ReportedNetworkConnectivityInfo(
6330 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006331 return;
6332 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006333 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006334 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006335 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006336 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006337 // Validating a network that has not yet connected could result in a call to
6338 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006339 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006340 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006341 }
paulhu7aeba372020-12-30 00:42:19 +08006342 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6343 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006344 return;
6345 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006346
6347 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6348 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6349 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6350 // completed.
6351 mConnectivityDiagnosticsHandler.sendMessage(
6352 mConnectivityDiagnosticsHandler.obtainMessage(
6353 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6354 new ReportedNetworkConnectivityInfo(
6355 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006356 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006357 }
6358
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006359 // TODO: call into netd.
6360 private boolean queryUserAccess(int uid, Network network) {
6361 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6362 if (nai == null) return false;
6363
6364 // Any UID can use its default network.
6365 if (nai == getDefaultNetworkForUid(uid)) return true;
6366
6367 // Privileged apps can use any network.
6368 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6369 return true;
6370 }
6371
6372 // An unprivileged UID can use a VPN iff the VPN applies to it.
6373 if (nai.isVPN()) {
6374 return nai.networkCapabilities.appliesToUid(uid);
6375 }
6376
6377 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6378 // sockets, i.e., if it is the owner.
6379 final NetworkAgentInfo vpn = getVpnForUid(uid);
6380 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6381 && uid != vpn.networkCapabilities.getOwnerUid()) {
6382 return false;
6383 }
6384
6385 // The UID's permission must be at least sufficient for the network. Since the restricted
6386 // permission was already checked above, that just leaves background networks.
6387 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6388 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6389 }
6390
6391 // Unrestricted network. Anyone gets to use it.
6392 return true;
6393 }
6394
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006395 /**
6396 * Returns information about the proxy a certain network is using. If given a null network, it
6397 * it will return the proxy for the bound network for the caller app or the default proxy if
6398 * none.
6399 *
6400 * @param network the network we want to get the proxy information for.
6401 * @return Proxy information if a network has a proxy configured, or otherwise null.
6402 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006403 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006404 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006405 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006406 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006407 if (network == null) {
6408 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006409 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006410 true);
6411 if (activeNetwork == null) {
6412 return null;
6413 }
6414 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006415 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006416 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6417 // caller may not have.
6418 return getLinkPropertiesProxyInfo(network);
6419 }
6420 // No proxy info available if the calling UID does not have network access.
6421 return null;
6422 }
6423
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006424
6425 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006426 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6427 if (nai == null) return null;
6428 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006429 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6430 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006431 }
6432 }
6433
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006434 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006435 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006436 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006437 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006438 }
6439
Chalard Jean777e2e52018-06-07 18:02:37 +09006440 @Override
6441 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006442 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006443 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006444 }
6445
Aaron Huang9fe47be2021-06-08 13:11:45 +08006446 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006447 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006448 final NetworkAgentInfo nai = getDefaultNetwork();
6449 // TODO : this method should check that net == nai.network, unfortunately at this point
6450 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6451 // is only ever installed on the default network so in practice this is okay.
6452 if (null == nai) return;
6453 // PAC proxies only work on the default network. Therefore, only the default network
6454 // should have its link properties fixed up for PAC proxies.
6455 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6456 if (nai.everConnected()) {
6457 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6458 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006459 }
6460
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006461 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6462 // when any network changes proxy.
6463 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6464 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006465 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6466 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006467 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6468
Chalard Jean7d97afc2018-06-07 17:41:29 +09006469 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006470 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006471 }
6472 }
6473
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006474 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006475 final private HashMap<Uri, Integer> mUriEventMap;
6476 final private Context mContext;
6477 final private Handler mHandler;
6478
6479 SettingsObserver(Context context, Handler handler) {
6480 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006481 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006482 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006483 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006484 }
6485
Erik Kline05f2b402015-04-30 12:58:40 +09006486 void observe(Uri uri, int what) {
6487 mUriEventMap.put(uri, what);
6488 final ContentResolver resolver = mContext.getContentResolver();
6489 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006490 }
6491
6492 @Override
6493 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006494 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006495 }
6496
6497 @Override
6498 public void onChange(boolean selfChange, Uri uri) {
6499 final Integer what = mUriEventMap.get(uri);
6500 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006501 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006502 } else {
6503 loge("No matching event to send for URI=" + uri);
6504 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006505 }
6506 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006507
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006508 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006509 Log.d(TAG, s);
6510 }
6511
6512 private static void logw(String s) {
6513 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006514 }
6515
Daniel Brightf9e945b2020-06-15 16:10:01 -07006516 private static void logwtf(String s) {
6517 Log.wtf(TAG, s);
6518 }
6519
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006520 private static void logwtf(String s, Throwable t) {
6521 Log.wtf(TAG, s, t);
6522 }
6523
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006524 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006525 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006526 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006527
Hugo Benichi39621362017-02-11 17:04:43 +09006528 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006529 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006530 }
6531
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006532 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006533 * Return the information of all ongoing VPNs.
6534 *
6535 * <p>This method is used to update NetworkStatsService.
6536 *
6537 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006538 */
junyulai2050bed2021-01-23 09:46:34 +08006539 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006540 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006541 if (mLockdownEnabled) {
6542 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006543 }
junyulai2050bed2021-01-23 09:46:34 +08006544 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006545 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006546 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006547 if (info != null) {
6548 infoList.add(info);
6549 }
6550 }
junyulai2050bed2021-01-23 09:46:34 +08006551 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006552 }
6553
6554 /**
6555 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006556 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006557 */
junyulai2050bed2021-01-23 09:46:34 +08006558 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006559 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006560 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6561 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006562 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6563 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6564 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006565 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6566 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006567 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006568 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006569 }
6570 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006571
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006572 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006573
6574 List<String> interfaces = new ArrayList<>();
6575 for (Network network : underlyingNetworks) {
6576 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6577 if (underlyingNai == null) continue;
6578 LinkProperties lp = underlyingNai.linkProperties;
6579 for (String iface : lp.getAllInterfaceNames()) {
6580 if (!TextUtils.isEmpty(iface)) {
6581 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006582 }
6583 }
Benedict Wong34857f82019-06-12 17:46:15 +00006584 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006585
6586 if (interfaces.isEmpty()) return null;
6587
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006588 // Must be non-null or NetworkStatsService will crash.
6589 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6590 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006591 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006592 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006593
junyulai2050bed2021-01-23 09:46:34 +08006594 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6595 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006596 }
6597
James Mattisd31bdfa2020-12-23 16:37:26 -08006598 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006599 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6600 Network[] underlyingNetworks) {
6601 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006602 if (underlyingNetworks == null && defaultNetwork != null) {
6603 // null underlying networks means to track the default.
6604 underlyingNetworks = new Network[] { defaultNetwork };
6605 }
6606 return underlyingNetworks;
6607 }
6608
6609 // Returns true iff |network| is an underlying network of |nai|.
6610 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6611 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6612 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006613 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006614 final Network[] underlying = underlyingNetworksOrDefault(
6615 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006616 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006617 }
6618
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006619 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006620 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006621 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006622 * When underlying networks change, such networks may have to update capabilities to reflect
6623 * things like the metered bit, their transports, and so on. The capabilities are calculated
6624 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006625 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006626 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006627 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006628 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006629 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006630 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006631 }
6632 }
6633 }
6634
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006635 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6636 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6637 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6638 // a VPN is not up.
6639 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6640 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6641 for (UidRange range : blockedUidRanges) {
6642 if (range.contains(uid)) return true;
6643 }
6644 return false;
6645 }
6646
6647 @Override
6648 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006649 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006650 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6651 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6652 }
6653
6654 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6655 if (DBG) {
6656 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6657 + Arrays.toString(ranges));
6658 }
6659 // Cannot use a Set since the list of UID ranges might contain duplicates.
6660 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6661 for (int i = 0; i < ranges.length; i++) {
6662 if (requireVpn) {
6663 newVpnBlockedUidRanges.add(ranges[i]);
6664 } else {
6665 newVpnBlockedUidRanges.remove(ranges[i]);
6666 }
6667 }
6668
6669 try {
6670 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6671 } catch (RemoteException | ServiceSpecificException e) {
6672 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6673 + Arrays.toString(ranges) + "): netd command failed: " + e);
6674 }
6675
Chalard Jeandf29a852023-05-29 17:02:43 +09006676 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006677 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6678 }
6679
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006680 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6681 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006682 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6683 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006684 }
6685
6686 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6687 }
6688
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006689 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006690 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006691 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006692 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006693 }
6694
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006695 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6696 return mLockdownEnabled
6697 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6698 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006699 }
6700
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006701 private NetworkAgentInfo getLegacyLockdownNai() {
6702 if (!mLockdownEnabled) {
6703 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006704 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006705 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006706 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6707 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006708
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006709 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006710 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6711 // a local variable. There is no need to make a copy because its contents cannot change.
6712 final Network[] underlying = nai.declaredUnderlyingNetworks;
6713 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006714 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006715 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006716
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006717 // The legacy lockdown VPN always uses the default network.
6718 // If the VPN's underlying network is no longer the current default network, it means that
6719 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006720 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6721 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006722 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006723 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006724 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006725 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006726
6727 return nai;
6728 };
6729
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006730 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6731 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6732 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006733 private DetailedState getLegacyLockdownState(DetailedState origState) {
6734 if (origState != DetailedState.CONNECTED) {
6735 return origState;
6736 }
6737 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6738 ? DetailedState.CONNECTING
6739 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006740 }
6741
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006742 private void filterForLegacyLockdown(NetworkInfo ni) {
6743 if (!mLockdownEnabled || !ni.isConnected()) return;
6744 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6745 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6746 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6747 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6748 // network, this time with a state of CONNECTED.
6749 //
6750 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6751 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6752 // is not too far off the truth, since an always-on VPN, when not connected, is always
6753 // trying to reconnect.
6754 if (getLegacyLockdownNai() == null) {
6755 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6756 }
6757 }
6758
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006759 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006760 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006761 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006762 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006763 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6764 return;
6765 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006766 final long ident = Binder.clearCallingIdentity();
6767 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006768 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006769 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006770 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006771 } finally {
6772 Binder.restoreCallingIdentity(ident);
6773 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006774 }
Wink Savillecb117d32013-08-29 14:57:08 -07006775
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006776 @Override
6777 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006778 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006779 final long ident = Binder.clearCallingIdentity();
6780 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006781 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006782 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006783 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6784 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006785 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006786 } finally {
6787 Binder.restoreCallingIdentity(ident);
6788 }
6789 }
6790
James Mattis02220e22021-03-13 19:27:21 -08006791 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006792 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6793 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6794 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006795 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006796 }
6797
James Mattis02220e22021-03-13 19:27:21 -08006798 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006799 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006800 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006801 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6802 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006803 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006804 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6805 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6806 }
junyulaid91e7052020-08-28 13:44:33 +08006807 }
6808
James Mattis02220e22021-03-13 19:27:21 -08006809 private void onPackageChanged(@NonNull final String packageName) {
6810 // This is necessary in case a package is added or removed, but also when it's replaced to
6811 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6812 // as one in the preferences, then it should follow the same routing as that other package,
6813 // which means updating the rules is never to be needed in this case (whether it joins or
6814 // leaves a UID with a preference).
6815 if (isMappedInOemNetworkPreference(packageName)) {
6816 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6817 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006818
6819 // Invalidates cache entry when the package is updated.
6820 synchronized (mSelfCertifiedCapabilityCache) {
6821 mSelfCertifiedCapabilityCache.remove(packageName);
6822 }
James Mattis02220e22021-03-13 19:27:21 -08006823 }
6824
6825 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006826 @Override
6827 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006828 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006829 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006830 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006831
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006832 // User should be filled for below intents, check the existence.
6833 if (user == null) {
6834 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6835 return;
6836 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006837
Lorenzo Colitticd675292021-02-04 17:32:07 +09006838 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006839 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006840 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006841 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006842 } else {
junyulaid91e7052020-08-28 13:44:33 +08006843 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006844 }
6845 }
6846 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006847
James Mattis02220e22021-03-13 19:27:21 -08006848 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6849 @Override
6850 public void onReceive(Context context, Intent intent) {
6851 ensureRunningOnConnectivityServiceThread();
6852 switch (intent.getAction()) {
6853 case Intent.ACTION_PACKAGE_ADDED:
6854 case Intent.ACTION_PACKAGE_REMOVED:
6855 case Intent.ACTION_PACKAGE_REPLACED:
6856 onPackageChanged(intent.getData().getSchemeSpecificPart());
6857 break;
6858 default:
6859 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6860 }
6861 }
6862 };
6863
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006864 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006865 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006866
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006867 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006868 public final String name;
6869 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006870 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006871 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006872
lifraf3a3492021-03-10 13:58:14 +08006873 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6874 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006875 this.name = name;
6876 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006877 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006878 mDeathRecipient = deathRecipient;
6879
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006880 if (mDeathRecipient == null) {
6881 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006882 }
6883 }
6884
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006885 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006886 try {
6887 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6888 } catch (RemoteException e) {
6889 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006890 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006891 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006892 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006893
James Mattis4fce5d12020-11-12 15:53:42 -08006894 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6895 for (int i = 0; i < requests.size(); i++) {
6896 ensureNetworkRequestHasType(requests.get(i));
6897 }
6898 }
6899
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006900 private void ensureNetworkRequestHasType(NetworkRequest request) {
6901 if (request.type == NetworkRequest.Type.NONE) {
6902 throw new IllegalArgumentException(
6903 "All NetworkRequests in ConnectivityService must have a type");
6904 }
6905 }
6906
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006907 /**
6908 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006909 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006910 */
James Mattis258ea3c2020-11-15 15:04:40 -08006911 @VisibleForTesting
6912 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006913 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6914 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006915 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006916
James Mattisa076c532020-12-02 14:12:41 -08006917 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6918 void setSatisfier(
6919 @Nullable final NetworkAgentInfo satisfier,
6920 @Nullable final NetworkRequest activeRequest) {
6921 mSatisfier = satisfier;
6922 mActiveRequest = activeRequest;
6923 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006924
James Mattisd31bdfa2020-12-23 16:37:26 -08006925 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006926 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006927 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006928 private NetworkAgentInfo mSatisfier;
6929 NetworkAgentInfo getSatisfier() {
6930 return mSatisfier;
6931 }
6932
6933 // The request in mRequests assigned to a network agent. This is null if none of the
6934 // requests in mRequests can be satisfied. This member has the constraint of only being
6935 // accessible on the handler thread.
6936 @Nullable
6937 private NetworkRequest mActiveRequest;
6938 NetworkRequest getActiveRequest() {
6939 return mActiveRequest;
6940 }
6941
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006942 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006943 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006944 @Nullable
6945 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006946
6947 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006948 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006949 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006950 final int mPid;
6951 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006952 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006953 @Nullable
6954 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006955
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006956 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006957 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006958
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006959 // Effective UID of this request. This is different from mUid when a privileged process
6960 // files a request on behalf of another UID. This UID is used to determine blocked status,
6961 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6962 // maximum limit of registered callbacks per UID.
6963 final int mAsUid;
6964
paulhu48291862021-07-14 14:53:57 +08006965 // Preference order of this request.
6966 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006967
James Mattis3ce3d3c2021-02-09 18:18:28 -08006968 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6969 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6970 // maintained for keying off of. This is only a concern when the original nri
6971 // mNetworkRequests changes which happens currently for apps that register callbacks to
6972 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6973 // that match the per-app default nri that currently tracks the calling app's uid so that
6974 // callbacks are fired at the appropriate time. When the callbacks fire,
6975 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6976 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6977 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6978 @NonNull
6979 private final NetworkRequest mNetworkRequestForCallback;
6980 NetworkRequest getNetworkRequestForCallback() {
6981 return mNetworkRequestForCallback;
6982 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006983
James Mattisd31bdfa2020-12-23 16:37:26 -08006984 /**
6985 * Get the list of UIDs this nri applies to.
6986 */
6987 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006988 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006989 // networkCapabilities.getUids() returns a defensive copy.
6990 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006991 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6992 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006993 }
6994
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006995 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6996 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006997 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006998 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006999 }
7000
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007001 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007002 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007003 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007004 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007005 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007006 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007007 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007008 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007009 mBinder = null;
7010 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007011 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007012 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007013 mPerUidCounter = getRequestCounter(this);
7014 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007015 /**
7016 * Location sensitive data not included in pending intent. Only included in
7017 * {@link NetworkCallback}.
7018 */
7019 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007020 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007021 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007022 }
7023
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007024 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007025 @Nullable final IBinder binder,
7026 @NetworkCallback.Flag int callbackFlags,
7027 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007028 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7029 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007030 }
7031
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007032 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007033 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007034 @Nullable final IBinder binder,
7035 @NetworkCallback.Flag int callbackFlags,
7036 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007037 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007038 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007039 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007040 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007041 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007042 mBinder = binder;
7043 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007044 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007045 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007046 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007047 mPerUidCounter = getRequestCounter(this);
7048 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007049 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007050 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007051 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007052 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007053 }
7054
James Mattis3ce3d3c2021-02-09 18:18:28 -08007055 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7056 @NonNull final List<NetworkRequest> r) {
7057 super();
7058 ensureAllNetworkRequestsHaveType(r);
7059 mRequests = initializeRequests(r);
7060 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007061 final NetworkAgentInfo satisfier = nri.getSatisfier();
7062 if (null != satisfier) {
7063 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7064 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007065 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007066 // As this code creates a new NRI with a new set of requests, figure out which of
7067 // the list of requests should be the active request. It is always the first
7068 // request of the list that can be satisfied by the satisfier since the order of
7069 // requests is a priority order.
7070 // Note even in the presence of a satisfier there may not be an active request,
7071 // when the satisfier is the no-service network.
7072 NetworkRequest activeRequest = null;
7073 for (final NetworkRequest candidate : r) {
7074 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7075 activeRequest = candidate;
7076 break;
7077 }
7078 }
7079 setSatisfier(satisfier, activeRequest);
7080 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007081 mMessenger = nri.mMessenger;
7082 mBinder = nri.mBinder;
7083 mPid = nri.mPid;
7084 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007085 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007086 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007087 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007088 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007089 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007090 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007091 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007092 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007093 }
7094
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007095 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007096 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007097 }
7098
paulhue9913722021-05-26 15:19:20 +08007099 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007100 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007101 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007102 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007103 }
7104
James Mattis2516da32021-01-31 17:06:19 -08007105 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7106 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7107 // false.
7108 boolean isBeingSatisfied() {
7109 return (null != mSatisfier && null != mActiveRequest);
7110 }
7111
James Mattis3d229892020-11-16 16:46:28 -08007112 boolean isMultilayerRequest() {
7113 return mRequests.size() > 1;
7114 }
7115
James Mattis45d81842021-01-10 14:24:24 -08007116 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7117 // Creating a defensive copy to prevent the sender from modifying the list being
7118 // reflected in the return value of this method.
7119 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007120 return Collections.unmodifiableList(tempRequests);
7121 }
7122
James Mattisb1392002021-03-31 13:57:52 -07007123 void linkDeathRecipient() {
7124 if (null != mBinder) {
7125 try {
7126 mBinder.linkToDeath(this, 0);
7127 } catch (RemoteException e) {
7128 binderDied();
7129 }
7130 }
7131 }
7132
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007133 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007134 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007135 try {
7136 mBinder.unlinkToDeath(this, 0);
7137 } catch (NoSuchElementException e) {
7138 // Temporary workaround for b/194394697 pending analysis of additional logs
7139 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7140 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007141 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007142 }
7143
paulhu48291862021-07-14 14:53:57 +08007144 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7145 // Compare two preference orders.
7146 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007147 }
7148
paulhu48291862021-07-14 14:53:57 +08007149 int getPreferenceOrderForNetd() {
7150 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7151 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7152 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007153 }
paulhu48291862021-07-14 14:53:57 +08007154 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007155 }
7156
James Mattis4fce5d12020-11-12 15:53:42 -08007157 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007158 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007159 // As an immutable collection, mRequests cannot change by the time the
7160 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7161 // is acceptable. Use handleReleaseNetworkRequest and not directly
7162 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7163 // the app already unregistered the request.
7164 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7165 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007166 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007167
James Mattis4fce5d12020-11-12 15:53:42 -08007168 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007169 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007170 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7171 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007172 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007173 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007174 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007175 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007176 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007177 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007178 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007179 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007180 }
7181
Junyu Lai00d92df2022-07-05 11:01:52 +08007182 // Keep backward compatibility since the ServiceSpecificException is used by
7183 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7184 public static class RequestInfoPerUidCounter extends PerUidCounter {
7185 RequestInfoPerUidCounter(int maxCountPerUid) {
7186 super(maxCountPerUid);
7187 }
7188
7189 @Override
7190 public synchronized void incrementCountOrThrow(int uid) {
7191 try {
7192 super.incrementCountOrThrow(uid);
7193 } catch (IllegalStateException e) {
7194 throw new ServiceSpecificException(
7195 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7196 "Uid " + uid + " exceeded its allotted requests limit");
7197 }
7198 }
7199
7200 @Override
7201 public synchronized void decrementCountOrThrow(int uid) {
7202 throw new UnsupportedOperationException("Use decrementCount instead.");
7203 }
7204
7205 public synchronized void decrementCount(int uid) {
7206 try {
7207 super.decrementCountOrThrow(uid);
7208 } catch (IllegalStateException e) {
7209 logwtf("Exception when decrement per uid request count: ", e);
7210 }
7211 }
7212 }
7213
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007214 // This checks that the passed capabilities either do not request a
7215 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007216 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007217 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007218 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007219 throw new SecurityException("Insufficient permissions to request a specific SSID");
7220 }
paulhu1a407652019-03-22 16:35:06 +08007221
7222 if (nc.hasSignalStrength()
7223 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7224 throw new SecurityException(
7225 "Insufficient permissions to request a specific signal strength");
7226 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007227 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007228
junyulai2217bec2021-04-14 23:33:31 +08007229 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007230 enforceNetworkFactoryPermission();
7231 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007232 }
7233
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007234 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007235 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007236 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007237 // mNetworkRequests may contain the same value multiple times in case of
7238 // multilayer requests. It won't matter in this case because the thresholds
7239 // will then be the same and be deduplicated as they enter the `thresholds` set.
7240 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007241 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7242 for (final NetworkRequest req : nri.mRequests) {
7243 if (req.networkCapabilities.hasSignalStrength()
7244 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7245 thresholds.add(req.networkCapabilities.getSignalStrength());
7246 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007247 }
7248 }
7249 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007250 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007251 }
7252
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007253 private void updateSignalStrengthThresholds(
7254 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007255 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007256
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007257 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007258 String detail;
7259 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7260 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7261 } else {
7262 detail = reason;
7263 }
7264 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007265 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007266 }
7267
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007268 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007269 }
7270
Chalard Jeandd421992021-12-16 23:16:02 +09007271 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007272 if (nc == null) {
7273 return;
7274 }
7275 NetworkSpecifier ns = nc.getNetworkSpecifier();
7276 if (ns == null) {
7277 return;
7278 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007279 if (ns instanceof MatchAllNetworkSpecifier) {
7280 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7281 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007282 }
7283
Chalard Jeandd421992021-12-16 23:16:02 +09007284 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007285 ensureValidNetworkSpecifier(nc);
7286 if (nc.isPrivateDnsBroken()) {
7287 throw new IllegalArgumentException("Can't request broken private DNS");
7288 }
Chalard Jeande665262022-02-25 16:12:12 +09007289 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007290 throw new IllegalArgumentException("Can't request access UIDs");
7291 }
lucasline117e2e2019-10-22 18:27:33 +08007292 }
7293
Chalard Jeandd421992021-12-16 23:16:02 +09007294 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7295 ensureListenableCapabilities(nc);
7296 final String badCapability = nc.describeFirstNonRequestableCapability();
7297 if (badCapability != null) {
7298 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7299 }
7300 }
7301
Chiachang Wang3bc52762021-11-25 14:17:57 +08007302 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7303 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007304 private boolean isTargetSdkAtleast(int version, int callingUid,
7305 @NonNull String callingPackageName) {
7306 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007307 final PackageManager pm =
7308 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007309 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007310 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007311 if (callingVersion < version) return false;
7312 } catch (PackageManager.NameNotFoundException e) { }
7313 return true;
7314 }
7315
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007316 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007317 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007318 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007319 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007320 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007321 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007322 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7323 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007324 throw new SecurityException("Insufficient permissions to specify legacy type");
7325 }
markchienfac84a22020-03-18 21:16:15 +08007326 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007327 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007328 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007329 // Privileged callers can track the default network of another UID by passing in a UID.
7330 if (asUid != Process.INVALID_UID) {
7331 enforceSettingsPermission();
7332 } else {
7333 asUid = callingUid;
7334 }
junyulaiad010792021-01-11 16:53:38 +08007335 final NetworkRequest.Type reqType;
7336 try {
7337 reqType = NetworkRequest.Type.values()[reqTypeInt];
7338 } catch (ArrayIndexOutOfBoundsException e) {
7339 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7340 }
7341 switch (reqType) {
7342 case TRACK_DEFAULT:
7343 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007344 // is unused and will be replaced by ones appropriate for the UID (usually, the
7345 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007346 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007347 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007348 enforceAccessPermission();
7349 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007350 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007351 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007352 networkCapabilities = new NetworkCapabilities(defaultNc);
7353 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007354 case BACKGROUND_REQUEST:
7355 enforceNetworkStackOrSettingsPermission();
7356 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007357 case REQUEST:
7358 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7359 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007360 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007361 // TODO: this is incorrect. We mark the request as metered or not depending on
7362 // the state of the app when the request is filed, but we never change the
7363 // request if the app changes network state. http://b/29964605
7364 enforceMeteredApnPolicy(networkCapabilities);
7365 break;
junyulai1b1c8742021-03-12 20:05:08 +08007366 case LISTEN_FOR_BEST:
7367 enforceAccessPermission();
7368 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7369 break;
junyulaiad010792021-01-11 16:53:38 +08007370 default:
7371 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007372 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007373 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007374 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007375 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007376
junyulai1b1c8742021-03-12 20:05:08 +08007377 // Enforce FOREGROUND if the caller does not have permission to use background network.
7378 if (reqType == LISTEN_FOR_BEST) {
7379 restrictBackgroundRequestForCaller(networkCapabilities);
7380 }
7381
7382 // Set the UID range for this request to the single UID of the requester, unless the
7383 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007384 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7385 // are no visible methods to set the UIDs, an app could use reflection to try and get
7386 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007387 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007388 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7389 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007390
Etan Cohen85000162017-02-05 10:42:27 -08007391 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007392 throw new IllegalArgumentException("Bad timeout specified");
7393 }
Etan Cohen9786d922015-11-18 10:56:15 -08007394
James Mattis3ce3d3c2021-02-09 18:18:28 -08007395 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007396 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007397 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007398 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007399 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007400 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007401
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007402 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7403 // copied from the default request above. (This is necessary to ensure, for example, that
7404 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7405 // changes don't alter request matching.
7406 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7407 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007408 throw new IllegalStateException(
7409 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007410 + networkCapabilities + " vs. " + defaultNc);
7411 }
7412
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007413 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007414 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007415 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007416 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007417 }
7418 return networkRequest;
7419 }
7420
James Mattis3ce3d3c2021-02-09 18:18:28 -08007421 /**
7422 * Return the nri to be used when registering a network request. Specifically, this is used with
7423 * requests registered to track the default request. If there is currently a per-app default
7424 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7425 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007426 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7427 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007428 * @param nr the network request for the nri.
7429 * @param msgr the messenger for the nri.
7430 * @param binder the binder for the nri.
7431 * @param callingAttributionTag the calling attribution tag for the nri.
7432 * @return the nri to register.
7433 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007434 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007435 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007436 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007437 @Nullable String callingAttributionTag) {
7438 final List<NetworkRequest> requests;
7439 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7440 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007441 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007442 } else {
7443 requests = Collections.singletonList(nr);
7444 }
Roshan Pius951c0032020-12-22 15:10:42 -08007445 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007446 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007447 }
7448
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007449 private boolean shouldCheckCapabilitiesDeclaration(
7450 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7451 @NonNull final String callingPackageName) {
7452 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7453 // Only run the check if the change is enabled.
7454 if (!mDeps.isChangeEnabled(
7455 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7456 callingPackageName, user)) {
7457 return false;
7458 }
7459
7460 return networkCapabilities.hasCapability(
7461 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7462 || networkCapabilities.hasCapability(
7463 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7464 }
7465
7466 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
7467 @NonNull final NetworkCapabilities networkCapabilities) {
7468 // This check is added to fix the linter error for "current min is 30", which is not going
7469 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007470 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007471 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7472 return;
7473 }
7474 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007475 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007476 try {
7477 synchronized (mSelfCertifiedCapabilityCache) {
7478 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7479 callerPackageName);
7480 if (applicationNetworkCapabilities == null) {
7481 final PackageManager packageManager = mContext.getPackageManager();
7482 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7483 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7484 callerPackageName
7485 );
7486 final XmlResourceParser parser = packageManager
7487 .getResourcesForApplication(callerPackageName)
7488 .getXml(networkSliceProperty.getResourceId());
7489 applicationNetworkCapabilities =
7490 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7491 mSelfCertifiedCapabilityCache.put(callerPackageName,
7492 applicationNetworkCapabilities);
7493 }
7494
7495 }
7496 } catch (PackageManager.NameNotFoundException ne) {
7497 throw new SecurityException(
7498 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7499 + " property");
7500 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7501 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007502 } finally {
7503 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007504 }
7505
7506 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7507 networkCapabilities);
7508 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007509 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007510 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007511 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7512 callingPackageName)) {
7513 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7514 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007515 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007516 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7517 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7518 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7519 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007520 }
junyulai96bd9fe2022-03-08 17:36:42 +08007521 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007522 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007523 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007524 }
7525 }
7526
fenglu3f357402015-03-20 11:29:56 -07007527 @Override
fenglub00f4882015-04-21 17:12:05 -07007528 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007529 enforceAccessPermission();
7530 NetworkAgentInfo nai = null;
7531 if (network == null) {
7532 return false;
7533 }
7534 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007535 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007536 }
7537 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007538 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007539 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007540 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007541 Integer uidReqs = mBandwidthRequests.get(uid);
7542 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007543 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007544 }
7545 mBandwidthRequests.put(uid, ++uidReqs);
7546 }
fenglu3f357402015-03-20 11:29:56 -07007547 return true;
7548 }
7549 return false;
7550 }
7551
Felipe Leme0a5ae422016-06-20 16:36:29 -07007552 private boolean isSystem(int uid) {
7553 return uid < Process.FIRST_APPLICATION_UID;
7554 }
fenglu3f357402015-03-20 11:29:56 -07007555
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007556 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007557 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007558 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007559 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007560 return;
7561 }
Hugo Benichi39621362017-02-11 17:04:43 +09007562 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7563 // Policy already enforced.
7564 return;
7565 }
paulhuaf50d7d2020-12-24 19:47:34 +08007566 final long ident = Binder.clearCallingIdentity();
7567 try {
7568 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7569 // If UID is restricted, don't allow them to bring up metered APNs.
7570 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7571 }
7572 } finally {
7573 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007574 }
7575 }
7576
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007577 @Override
7578 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007579 PendingIntent operation, @NonNull String callingPackageName,
7580 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007581 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007582 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007583 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007584 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007585 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007586 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007587 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007588 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007589 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007590 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7591 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007592
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007593 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007594 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007595 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7596 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007597 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007598 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7599 nri));
7600 return networkRequest;
7601 }
7602
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007603 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7604 mHandler.sendMessageDelayed(
7605 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007606 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007607 }
7608
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007609 @Override
7610 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007611 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007612 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007613 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007614 }
7615
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007616 // In order to implement the compatibility measure for pre-M apps that call
7617 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7618 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7619 // This ensures it has permission to do so.
7620 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7621 if (nc == null) {
7622 return false;
7623 }
7624 int[] transportTypes = nc.getTransportTypes();
7625 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7626 return false;
7627 }
7628 try {
7629 mContext.enforceCallingOrSelfPermission(
7630 android.Manifest.permission.ACCESS_WIFI_STATE,
7631 "ConnectivityService");
7632 } catch (SecurityException e) {
7633 return false;
7634 }
7635 return true;
7636 }
7637
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007638 @Override
7639 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007640 Messenger messenger, IBinder binder,
7641 @NetworkCallback.Flag int callbackFlags,
7642 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007643 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007644 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7645 enforceAccessPermission();
7646 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007647
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007648 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007649 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007650 Binder.getCallingPid(), callingUid, callingPackageName);
7651 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007652 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7653 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7654 // onLost and onAvailable callbacks when networks move in and out of the background.
7655 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7656 // can't request networks.
7657 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007658 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007659
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007660 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007661 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007662 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007663 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007664 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007665 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007666
7667 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7668 return networkRequest;
7669 }
7670
7671 @Override
7672 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007673 PendingIntent operation, @NonNull String callingPackageName,
7674 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007675 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007676 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007677 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7678 enforceAccessPermission();
7679 }
Chalard Jeandd421992021-12-16 23:16:02 +09007680 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007681 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007682 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007683 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007684 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007685
7686 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007687 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007688 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7689 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007690 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007691
WeiZhang1cc3f172021-06-03 19:02:04 -05007692 mHandler.sendMessage(mHandler.obtainMessage(
7693 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007694 }
7695
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007696 /** Returns the next Network provider ID. */
7697 public final int nextNetworkProviderId() {
7698 return mNextNetworkProviderId.getAndIncrement();
7699 }
7700
Erik Kline0c04b742016-07-07 16:50:58 +09007701 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007702 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007703 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007704 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007705 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007706 }
7707
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007708 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7709 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007710 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7711 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7712 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007713 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007714 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007715 return;
7716 }
7717
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007718 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7719 mNetworkProviderInfos.put(npi.messenger, npi);
7720 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007721 }
7722
7723 @Override
7724 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007725 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007726 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007727 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007728 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007729 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7730 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007731 }
7732
7733 @Override
7734 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007735 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007736 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007737 }
7738
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007739 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007740 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007741 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7742 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007743 Objects.requireNonNull(score);
7744 Objects.requireNonNull(caps);
7745 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007746 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007747 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007748 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7749 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007750 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7751 }
7752
Chalard Jeanbb902a52021-08-18 01:35:19 +09007753 private void updateOfferScore(final NetworkOffer offer) {
7754 final boolean yieldToBadWiFi =
7755 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7756 final NetworkOffer newOffer = new NetworkOffer(
7757 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7758 offer.caps, offer.callback, offer.providerId);
7759 if (offer.equals(newOffer)) return;
7760 handleRegisterNetworkOffer(newOffer);
7761 }
7762
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007763 @Override
7764 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007765 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007766 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7767 }
7768
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007769 private void handleUnregisterNetworkProvider(Messenger messenger) {
7770 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7771 if (npi == null) {
7772 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007773 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007774 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007775 // Unregister all the offers from this provider
7776 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7777 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007778 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007779 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7780 toRemove.add(noi);
7781 }
7782 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007783 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007784 handleUnregisterNetworkOffer(noi);
7785 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007786 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007787 }
7788
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007789 @Override
James Mattisf7027322020-12-13 16:28:14 -08007790 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007791 if (request.hasTransport(TRANSPORT_TEST)) {
7792 enforceNetworkFactoryOrTestNetworksPermission();
7793 } else {
7794 enforceNetworkFactoryPermission();
7795 }
James Mattisf7027322020-12-13 16:28:14 -08007796 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7797 if (nri != null) {
7798 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7799 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7800 mHandler.post(() -> handleReleaseNetworkRequest(
7801 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7802 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007803 }
7804
Paul Jensen1f567382015-02-13 14:18:39 -05007805 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7806 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007807 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007808 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007809 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007810 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007811 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007812
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007813 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007814 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007815 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007816
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007817 // UID ranges for users that are currently blocked by VPNs.
7818 // This array is accessed and iterated on multiple threads without holding locks, so its
7819 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7820 // (on the handler thread).
7821 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7822
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007823 // Must only be accessed on the handler thread
7824 @NonNull
7825 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7826
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007827 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007828 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007829
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007830 // Current OEM network preferences. This object must only be written to on the handler thread.
7831 // Since it is immutable and always non-null, other threads may read it if they only care
7832 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007833 @NonNull
7834 private OemNetworkPreferences mOemNetworkPreferences =
7835 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007836 // Current per-profile network preferences. This object follows the same threading rules as
7837 // the OEM network preferences above.
7838 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007839 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7840 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007841
lucaslin3ba7cc22022-12-19 02:35:33 +00007842 // Current VPN network preferences. This object follows the same threading rules as the OEM
7843 // network preferences above.
7844 @NonNull
7845 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7846 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7847
paulhu51f77dc2021-06-07 02:34:20 +00007848 // A set of UIDs that should use mobile data preferentially if available. This object follows
7849 // the same threading rules as the OEM network preferences above.
7850 @NonNull
7851 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7852
James Mattiscb1e0362021-04-06 17:07:42 -07007853 // OemNetworkPreferences activity String log entries.
7854 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7855 @NonNull
7856 private final LocalLog mOemNetworkPreferencesLogs =
7857 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7858
James Mattis02220e22021-03-13 19:27:21 -08007859 /**
7860 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7861 * @param packageName the package name to check existence of a mapping for.
7862 * @return true if a mapping exists, false otherwise
7863 */
7864 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7865 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7866 }
7867
James Mattise3ef1912020-12-20 11:09:58 -08007868 // The always-on request for an Internet-capable network that apps without a specific default
7869 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007870 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007871 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007872 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007873 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007874 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007875 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007876 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007877
James Mattisd31bdfa2020-12-23 16:37:26 -08007878 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7879 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7880 }
7881
7882 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007883 * Return the default network request currently tracking the given uid.
7884 * @param uid the uid to check.
7885 * @return the NetworkRequestInfo tracking the given uid.
7886 */
7887 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007888 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007889 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007890 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007891 // Checking the first request is sufficient as only multilayer requests will have more
7892 // than one request and for multilayer, all requests will track the same uids.
7893 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007894 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007895 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007896 highestPriorityNri = nri;
7897 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007898 }
7899 }
paulhuaa0743d2021-05-26 21:56:03 +08007900 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007901 }
7902
7903 /**
7904 * Get a copy of the network requests of the default request that is currently tracking the
7905 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007906 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7907 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007908 * @param requestorUid the uid to check the default for.
7909 * @param requestorPackageName the requestor's package name.
7910 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7911 */
7912 @NonNull
7913 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007914 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007915 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007916 getDefaultRequestTrackingUid(asUid).mRequests,
7917 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007918 }
7919
7920 /**
7921 * Copy the given nri's NetworkRequest collection.
7922 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007923 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7924 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007925 * @param requestorUid the uid to set on the copied collection.
7926 * @param requestorPackageName the package name to set on the copied collection.
7927 * @return the copied NetworkRequest collection.
7928 */
7929 @NonNull
7930 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007931 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7932 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007933 final List<NetworkRequest> requests = new ArrayList<>();
7934 for (final NetworkRequest nr : requestsToCopy) {
7935 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007936 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007937 nr.legacyType, nextNetworkRequestId(), nr.type));
7938 }
7939 return requests;
7940 }
7941
7942 @NonNull
7943 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007944 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7945 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007946 // These capabilities are for a TRACK_DEFAULT callback, so:
7947 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7948 // mDefaultRequest and a per-UID default request.
7949 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007950 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007951 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007952 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7953 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007954 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007955 restrictRequestUidsForCallerAndSetRequestorInfo(
7956 netCap, requestorUid, requestorPackageName);
7957 return netCap;
7958 }
7959
7960 /**
7961 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7962 * @param nr the network request to check for equality against.
7963 * @return the nri if one exists, null otherwise.
7964 */
7965 @Nullable
7966 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7967 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7968 if (nri.getNetworkRequestForCallback().equals(nr)) {
7969 return nri;
7970 }
7971 }
7972 return null;
7973 }
7974
7975 /**
7976 * Check if an nri is currently being managed by per-app default networking.
7977 * @param nri the nri to check.
7978 * @return true if this nri is currently being managed by per-app default networking.
7979 */
7980 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7981 // nri.mRequests.get(0) is only different from the original request filed in
7982 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7983 // functionality therefore if these two don't match, it means this particular nri is
7984 // currently being managed by a per-app default.
7985 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7986 }
7987
7988 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007989 * Determine if an nri is a managed default request that disallows default networking.
7990 * @param nri the request to evaluate
7991 * @return true if device-default networking is disallowed
7992 */
7993 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7994 // Check if this nri is a managed default that supports the default network at its
7995 // lowest priority request.
7996 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7997 final NetworkCapabilities lowestPriorityNetCap =
7998 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7999 return isPerAppDefaultRequest(nri)
8000 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8001 lowestPriorityNetCap));
8002 }
8003
Erik Kline05f2b402015-04-30 12:58:40 +09008004 // Request used to optionally keep mobile data active even when higher
8005 // priority networks like Wi-Fi are active.
8006 private final NetworkRequest mDefaultMobileDataRequest;
8007
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008008 // Request used to optionally keep wifi data active even when higher
8009 // priority networks like ethernet are active.
8010 private final NetworkRequest mDefaultWifiRequest;
8011
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008012 // Request used to optionally keep vehicle internal network always active
8013 private final NetworkRequest mDefaultVehicleRequest;
8014
James Mattisd31bdfa2020-12-23 16:37:26 -08008015 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8016 // network with no service. This NAI should never be matched against, nor should any public API
8017 // ever return the associated network. For this reason, this NAI is not in the list of available
8018 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8019 // default requests that don't support using the device default network which will ultimately
8020 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8021 @VisibleForTesting
8022 final NetworkAgentInfo mNoServiceNetwork;
8023
Chalard Jean5b409c72021-02-04 13:12:59 +09008024 // The NetworkAgentInfo currently satisfying the default request, if any.
8025 private NetworkAgentInfo getDefaultNetwork() {
8026 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008027 }
8028
James Mattis2516da32021-01-31 17:06:19 -08008029 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008030 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008031 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8032 // Currently, all network requests will have the same uids therefore checking the first
8033 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008034 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008035 if (null == uids) {
8036 continue;
8037 }
8038 for (final UidRange range : uids) {
8039 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008040 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008041 highestPriorityNri = nri;
8042 }
James Mattis2516da32021-01-31 17:06:19 -08008043 }
8044 }
8045 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008046 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008047 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008048 }
8049
Varun Ananddf569952019-02-06 10:13:38 -08008050 @Nullable
8051 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8052 return nai != null ? nai.network : null;
8053 }
8054
8055 private void ensureRunningOnConnectivityServiceThread() {
8056 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8057 throw new IllegalStateException(
8058 "Not running on ConnectivityService thread: "
8059 + Thread.currentThread().getName());
8060 }
8061 }
8062
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008063 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008064 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8065 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008066 }
8067
Chalard Jean29d06db2018-05-02 21:14:54 +09008068 /**
8069 * Register a new agent with ConnectivityService to handle a network.
8070 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008071 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008072 * @param networkInfo the initial info associated with this network. It can be updated later :
8073 * see {@link #updateNetworkInfo}.
8074 * @param linkProperties the initial link properties of this network. They can be updated
8075 * later : see {@link #updateLinkProperties}.
8076 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008077 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008078 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008079 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008080 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008081 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008082 */
Anton Kulakov6eea22b2023-10-13 15:04:01 +00008083 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
8084 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
8085 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09008086 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008087 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8088 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8089 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008090 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008091 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008092 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008093 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008094 } else {
8095 enforceNetworkFactoryPermission();
8096 }
8097
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008098 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008099 final long token = Binder.clearCallingIdentity();
8100 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008101 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Anton Kulakov6eea22b2023-10-13 15:04:01 +00008102 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008103 } finally {
8104 Binder.restoreCallingIdentity(token);
8105 }
8106 }
8107
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008108 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008109 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Anton Kulakov6eea22b2023-10-13 15:04:01 +00008110 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09008111 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008112
Chalard Jeandbc46952022-02-02 00:14:18 +09008113 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8114 // and mutate them at any time.
8115 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8116 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8117 final LinkProperties lpCopy = new LinkProperties(linkProperties);
8118
Chalard Jean366c5252022-01-25 18:27:53 +09008119 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008120 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008121 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8122 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008123 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008124 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Anton Kulakov6eea22b2023-10-13 15:04:01 +00008125 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
8126 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
8127 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008128
Chalard Jeandbc46952022-02-02 00:14:18 +09008129 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008130 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008131 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008132 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008133 mDeps.getNetworkStack().makeNetworkMonitor(
8134 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008135 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8136 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008137 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008138 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008139 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008140 }
8141
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008142 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008143 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008144 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008145 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008146 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008147 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8148 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8149 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008150
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008151 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008152
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008153 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008154 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008155 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008156 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008157
8158 try {
8159 networkMonitor.start();
8160 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008161 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008162 }
Chalard Jean366c5252022-01-25 18:27:53 +09008163
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008164 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008165 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008166 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008167 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008168 }
8169
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008170 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8171 @NonNull public final NetworkOffer offer;
8172
8173 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8174 this.offer = offer;
8175 }
8176
8177 @Override
8178 public void binderDied() {
8179 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8180 }
8181 }
8182
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008183 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8184 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8185 if (npi.providerId == providerId) return true;
8186 }
8187 return false;
8188 }
8189
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008190 /**
8191 * Register or update a network offer.
8192 * @param newOffer The new offer. If the callback member is the same as an existing
8193 * offer, it is an update of that offer.
8194 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008195 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008196 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8197 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008198 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008199 // This may actually happen if a provider updates its score or registers and then
8200 // immediately unregisters. The offer would still be in the handler queue, but the
8201 // provider would have been removed.
8202 if (DBG) log("Received offer from an unregistered provider");
8203 return;
8204 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008205 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8206 if (null != existingOffer) {
8207 handleUnregisterNetworkOffer(existingOffer);
8208 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008209 if (DBG) {
8210 // handleUnregisterNetworkOffer has already logged the old offer
8211 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8212 }
8213 } else {
8214 if (DBG) {
8215 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8216 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008217 }
8218 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8219 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008220 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008221 } catch (RemoteException e) {
8222 noi.binderDied();
8223 return;
8224 }
8225 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008226 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008227 }
8228
8229 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8230 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008231 if (DBG) {
8232 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8233 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008234
8235 // If the provider removes the offer and dies immediately afterwards this
8236 // function may be called twice in a row, but the array will no longer contain
8237 // the offer.
8238 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008239 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008240 }
8241
8242 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8243 @NonNull final INetworkOfferCallback callback) {
8244 ensureRunningOnConnectivityServiceThread();
8245 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008246 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008247 }
8248 return null;
8249 }
8250
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008251 /**
8252 * Called when receiving LinkProperties directly from a NetworkAgent.
8253 * Stores into |nai| any data coming from the agent that might also be written to the network's
8254 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8255 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008256 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008257 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008258 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8259 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008260 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008261 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008262 }
8263
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008264 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008265 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008266 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008267
Lorenzo Colittid523d142020-04-01 20:16:30 +09008268 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8269 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8270 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008271 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008272
Suprabh Shukla1e312032023-01-24 03:36:37 -08008273 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008274
8275 // update filtering rules, need to happen after the interface update so netd knows about the
8276 // new interface (the interface name -> index map becomes initialized)
8277 updateVpnFiltering(newLp, oldLp, networkAgent);
8278
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008279 updateMtu(newLp, oldLp);
8280 // TODO - figure out what to do for clat
8281// for (LinkProperties lp : newLp.getStackedLinks()) {
8282// updateMtu(lp, null);
8283// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008284 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008285 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008286 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8287 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008288
Erik Klineb9888902016-04-05 13:30:49 +09008289 updateRoutes(newLp, oldLp, netId);
8290 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008291 // Make sure LinkProperties represents the latest private DNS status.
8292 // This does not need to be done before updateDnses because the
8293 // LinkProperties are not the source of the private DNS configuration.
8294 // updateDnses will fetch the private DNS configuration from DnsManager.
8295 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008296
Chalard Jean5b409c72021-02-04 13:12:59 +09008297 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008298 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008299 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008300 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008301 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008302
8303 updateWakeOnLan(newLp);
8304
Hai Shalome58bdc62021-01-11 18:45:34 -08008305 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8306 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8307 // does, it needs to be merged here.
8308 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8309 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008310
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008311 // TODO - move this check to cover the whole function
8312 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008313 synchronized (networkAgent) {
8314 networkAgent.linkProperties = newLp;
8315 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008316 // Start or stop DNS64 detection and 464xlat according to network state.
8317 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008318 // Notify NSS when relevant events happened. Currently, NSS only cares about
8319 // interface changed to update clat interfaces accounting.
8320 final boolean interfacesChanged = oldLp == null
8321 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8322 if (interfacesChanged) {
8323 notifyIfacesChangedForNetworkStats();
8324 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008325 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8326 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008327 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008328 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008329
8330 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008331 }
8332
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008333 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8334 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8335 }
8336
Hai Shalome58bdc62021-01-11 18:45:34 -08008337 /**
8338 * @param naData captive portal data from NetworkAgent
8339 * @param apiData captive portal data from capport API
8340 */
8341 @Nullable
8342 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8343 CaptivePortalData apiData) {
8344 if (naData == null || apiData == null) {
8345 return naData == null ? apiData : naData;
8346 }
8347 final CaptivePortalData.Builder captivePortalBuilder =
8348 new CaptivePortalData.Builder(naData);
8349
8350 if (apiData.isCaptive()) {
8351 captivePortalBuilder.setCaptive(true);
8352 }
8353 if (apiData.isSessionExtendable()) {
8354 captivePortalBuilder.setSessionExtendable(true);
8355 }
8356 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8357 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8358 // otherwise data would be inconsistent. Prefer the capport API info if present,
8359 // as it can generally be refreshed more often.
8360 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8361 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8362 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8363 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8364 // No source has time / bytes remaining information: surface the newest refresh time
8365 // for other fields
8366 captivePortalBuilder.setRefreshTime(
8367 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8368 }
8369
Hai Shalom7c6ab402021-02-04 19:34:06 -08008370 // Prioritize the user portal URL from the network agent if the source is authenticated.
8371 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8372 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8373 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8374 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008375 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008376 // Prioritize the venue information URL from the network agent if the source is
8377 // authenticated.
8378 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8379 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8380 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8381 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008382 }
8383 return captivePortalBuilder.build();
8384 }
8385
Suprabh Shukla53e16392023-04-26 18:47:36 -07008386 @VisibleForTesting
8387 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008388 // This needs to be kept in sync and backwards compatible with the decoding logic in
8389 // NetdEventListenerService, which is non-mainline code.
8390 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8391 }
8392
Suprabh Shukla75642282023-04-25 23:15:43 -07008393 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8394 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8395 return true;
8396 }
8397 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8398 return true;
8399 }
8400 return false;
8401 }
8402
Suprabh Shukla1e312032023-01-24 03:36:37 -08008403 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008404 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008405 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008406 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008407 return;
8408 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008409
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008410 // Mask/mark of zero will not detect anything interesting.
8411 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008412 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008413 return;
8414 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008415
Suprabh Shukla1e312032023-01-24 03:36:37 -08008416 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008417 try {
8418 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008419 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008420 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008421 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008422 }
8423 } catch (Exception e) {
8424 loge("Exception modifying wakeup packet monitoring: " + e);
8425 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008426 }
8427
Junyu Lai970963e2022-10-25 15:46:47 +08008428 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008429 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008430 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008431 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008432 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008433 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008434 for (final String iface : interfaceDiff.added) {
8435 try {
8436 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008437 mNetd.networkAddInterface(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008438 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008439 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008440 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008441 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008442 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008443 }
Paul Jensenbff73492014-04-28 10:33:11 -04008444 }
8445 }
Chalard Jean9589e722019-11-19 19:03:53 +09008446 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008447 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008448 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008449 wakeupModifyInterface(iface, nai, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008450 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008451 } catch (Exception e) {
8452 loge("Exception removing interface: " + e);
8453 }
8454 }
8455 }
8456
Tyler Weare4314862019-12-05 14:55:30 -08008457 // TODO: move to frameworks/libs/net.
8458 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
8459 final String nextHop;
8460
8461 switch (route.getType()) {
8462 case RouteInfo.RTN_UNICAST:
8463 if (route.hasGateway()) {
8464 nextHop = route.getGateway().getHostAddress();
8465 } else {
8466 nextHop = INetd.NEXTHOP_NONE;
8467 }
8468 break;
8469 case RouteInfo.RTN_UNREACHABLE:
8470 nextHop = INetd.NEXTHOP_UNREACHABLE;
8471 break;
8472 case RouteInfo.RTN_THROW:
8473 nextHop = INetd.NEXTHOP_THROW;
8474 break;
8475 default:
8476 nextHop = INetd.NEXTHOP_NONE;
8477 break;
8478 }
8479
8480 final RouteInfoParcel rip = new RouteInfoParcel();
8481 rip.ifName = route.getInterface();
8482 rip.destination = route.getDestination().toString();
8483 rip.nextHop = nextHop;
8484 rip.mtu = route.getMtu();
8485
8486 return rip;
8487 }
8488
Paul Jensene0fd4a82014-08-06 15:51:33 -04008489 /**
8490 * Have netd update routes from oldLp to newLp.
8491 * @return true if routes changed between oldLp and newLp
8492 */
Junyu Lai970963e2022-10-25 15:46:47 +08008493 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8494 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008495 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008496 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8497 new CompareOrUpdateResult<>(
8498 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008499 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008500 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008501
8502 // add routes before removing old in case it helps with continuous connectivity
8503
Chalard Jean9dd11612018-06-04 16:52:49 +09008504 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008505 for (RouteInfo route : routeDiff.added) {
8506 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008507 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008508 try {
Tyler Weare4314862019-12-05 14:55:30 -08008509 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008510 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008511 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008512 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008513 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008514 }
8515 }
8516 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008517 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008518 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008519 try {
Tyler Weare4314862019-12-05 14:55:30 -08008520 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008521 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008522 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008523 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008524 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008525 }
8526 }
8527
8528 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008529 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008530 try {
Tyler Weare4314862019-12-05 14:55:30 -08008531 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008532 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08008533 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008534 }
8535 }
Tyler Weare4314862019-12-05 14:55:30 -08008536
8537 for (RouteInfo route : routeDiff.updated) {
8538 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8539 try {
8540 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
8541 } catch (Exception e) {
8542 loge("Exception in networkUpdateRouteParcel: " + e);
8543 }
8544 }
8545 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8546 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008547 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008548
Junyu Lai970963e2022-10-25 15:46:47 +08008549 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8550 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008551 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8552 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008553 }
Erik Klineb9888902016-04-05 13:30:49 +09008554
Erik Kline31b4a9e2018-01-11 21:07:29 +09008555 if (DBG) {
8556 final Collection<InetAddress> dnses = newLp.getDnsServers();
8557 log("Setting DNS servers for network " + netId + " to " + dnses);
8558 }
Erik Klineb9888902016-04-05 13:30:49 +09008559 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008560 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008561 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008562 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008563 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008564 }
Erik Kline54e35c02017-04-07 15:29:29 +09008565 }
8566
Junyu Lai970963e2022-10-25 15:46:47 +08008567 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8568 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008569 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8570 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008571 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8572 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008573
8574 if (!wasFiltering && !needsFiltering) {
8575 // Nothing to do.
8576 return;
8577 }
8578
8579 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8580 // Nothing changed.
8581 return;
8582 }
8583
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008584 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008585 if (ranges == null || ranges.isEmpty()) {
8586 return;
8587 }
8588
Qingxi Libb8da982020-01-17 17:54:27 -08008589 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008590 // TODO: this create a window of opportunity for apps to receive traffic between the time
8591 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008592 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008593 // old rules are being removed.
8594 if (wasFiltering) {
8595 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8596 }
8597 if (needsFiltering) {
8598 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8599 }
8600 }
8601
Valentin Iftime9fa35092019-09-24 13:32:13 +02008602 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008603 if (mWolSupportedInterfaces == null) {
8604 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008605 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008606 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008607 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8608 }
8609
Luke Huangb913c812018-08-24 20:33:16 +08008610 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008611 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008612 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008613 }
8614 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008615 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008616 }
Luke Huangb913c812018-08-24 20:33:16 +08008617 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008618 }
8619
Chalard Jean62edfd82019-12-02 18:39:29 +09008620 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8621 @NonNull final NetworkCapabilities newNc) {
8622 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8623 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008624 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008625 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008626 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008627 } catch (RemoteException | ServiceSpecificException e) {
8628 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008629 }
8630 }
8631 }
8632
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008633 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008634 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008635 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008636 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008637 underlyingNetworks = underlyingNetworksOrDefault(
8638 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008639 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008640 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8641 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008642 // metered if any underlying is metered, or originally declared metered by the agent.
8643 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008644 boolean roaming = false; // roaming if any underlying is roaming
8645 boolean congested = false; // congested if any underlying is congested
8646 boolean suspended = true; // suspended if all underlying are suspended
8647
8648 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008649 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008650 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008651 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008652 for (Network underlyingNetwork : underlyingNetworks) {
8653 final NetworkAgentInfo underlying =
8654 getNetworkAgentInfoForNetwork(underlyingNetwork);
8655 if (underlying == null) continue;
8656
8657 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8658 hadUnderlyingNetworks = true;
8659 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008660 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008661 }
8662
8663 // Merge capabilities of this underlying network. For bandwidth, assume the
8664 // worst case.
8665 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8666 underlyingCaps.getLinkDownstreamBandwidthKbps());
8667 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8668 underlyingCaps.getLinkUpstreamBandwidthKbps());
8669 // If this underlying network is metered, the VPN is metered (it may cost money
8670 // to send packets on this network).
8671 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8672 // If this underlying network is roaming, the VPN is roaming (the billing structure
8673 // is different than the usual, local one).
8674 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8675 // If this underlying network is congested, the VPN is congested (the current
8676 // condition of the network affects the performance of this network).
8677 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8678 // If this network is not suspended, the VPN is not suspended (the VPN
8679 // is able to transfer some data).
8680 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008681 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008682 }
8683 }
8684 if (!hadUnderlyingNetworks) {
8685 // No idea what the underlying networks are; assume reasonable defaults
8686 metered = true;
8687 roaming = false;
8688 congested = false;
8689 suspended = false;
8690 }
8691
Chalard Jean1d420b32022-10-12 16:39:37 +09008692 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008693 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8694 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8695 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8696 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8697 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8698 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008699 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008700 }
8701
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008702 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008703 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8704 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8705 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008706 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008707 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008708 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008709 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008710 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8711 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008712 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008713 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008714 if (nai.everConnected()
8715 && !nai.isVPN()
8716 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008717 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008718 // does not cause any request (that is not a listen) currently matching that agent to
8719 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008720 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008721 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008722 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008723 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008724 }
8725
Paul Jensen53f08952015-06-16 14:27:36 -04008726 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008727 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008728 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008729 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008730 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008731 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008732 }
Chalard Jean254bd162022-08-25 13:04:51 +09008733 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008734 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008735 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008736 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008737 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008738 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008739 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008740 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008741 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008742 }
Chalard Jean254bd162022-08-25 13:04:51 +09008743 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008744 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8745 } else {
8746 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8747 }
lucasline117e2e2019-10-22 18:27:33 +08008748 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008749
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008750 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008751 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8752 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008753 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008754 }
8755
Lorenzo Colittibd079452021-07-02 11:47:57 +09008756 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008757 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008758 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008759 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008760 }
8761
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008762 return newNc;
8763 }
8764
Lorenzo Colitti44840702021-01-11 22:27:57 +09008765 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8766 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8767 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8768 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8769 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8770 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8771 if (prevSuspended != suspended) {
8772 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8773 // onResumed have been removed.
8774 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8775 : ConnectivityManager.CALLBACK_RESUMED);
8776 }
8777 if (prevSuspended != suspended || prevRoaming != roaming) {
8778 // updateNetworkInfo will mix in the suspended info from the capabilities and
8779 // take appropriate action for the network having possibly changed state.
8780 updateNetworkInfo(nai, nai.networkInfo);
8781 }
8782 }
8783
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008784 /**
8785 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8786 *
8787 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8788 * capabilities we manage and store in {@code nai}, such as validated status and captive
8789 * portal status)
8790 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8791 * potentially triggers rematches.
8792 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8793 * change.)
8794 *
8795 * @param oldScore score of the network before any of the changes that prompted us
8796 * to call this function.
8797 * @param nai the network having its capabilities updated.
8798 * @param nc the new network capabilities.
8799 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008800 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008801 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008802 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008803 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008804 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8805 if (null != differences) {
8806 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8807 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008808 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008809 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008810
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008811 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008812 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008813 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008814
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008815 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008816 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8817 // the change we're processing can't affect any requests, it can only affect the listens
8818 // on this network. We might have been called by rematchNetworkAndRequests when a
8819 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008820 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008821 } else {
8822 // If the requestable capabilities have changed or the score changed, we can't have been
8823 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008824 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008825 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008826 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008827 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008828
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008829 final boolean oldMetered = prevNc.isMetered();
8830 final boolean newMetered = newNc.isMetered();
8831 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008832
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008833 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008834 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8835 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008836 }
junyulaif2c67e42018-08-07 19:50:45 +08008837
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008838 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8839 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008840
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008841 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008842 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008843 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008844 }
8845
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008846 // This network might have been underlying another network. Propagate its capabilities.
8847 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008848
8849 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008850 mDnsManager.updateTransportsForNetwork(
8851 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008852 }
lucaslin53e8a262021-06-08 01:43:59 +08008853
8854 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008855 }
8856
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008857 /** Convenience method to update the capabilities for a given network. */
8858 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008859 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008860 }
8861
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008862 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008863 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008864 *
8865 * Ingress interface filtering enforces that all apps under the given network can only receive
8866 * packets from the network's interface (and loopback). This is important for VPNs because
8867 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8868 * non-VPN interfaces.
8869 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008870 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008871 * 1. the network is an app VPN (not legacy VPN)
8872 * 2. the VPN does not allow bypass
8873 * 3. the VPN is fully-routed
8874 * 4. the VPN interface is non-null
8875 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008876 * @see INetd#firewallAddUidInterfaceRules
8877 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008878 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008879 @Nullable
8880 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008881 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008882 if (nc == null || lp == null) return null;
8883 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008884 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008885 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008886 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008887 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008888 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008889 && !lp.hasExcludeRoute()) {
8890 return lp.getInterfaceName();
8891 }
8892 return null;
8893 }
8894
8895 /**
8896 * Returns whether we need to set interface filtering rule or not
8897 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008898 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008899 String isolationIface) {
8900 // Allow rules are always needed if VPN isolation is enabled.
8901 if (isolationIface != null) return true;
8902
8903 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8904 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8905 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09008906 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008907 }
8908
Chiachang Wang28afaff2020-12-10 22:24:47 +08008909 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8910 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8911 int index = 0;
8912 for (UidRange range : ranges) {
8913 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8914 index++;
8915 }
8916 return stableRanges;
8917 }
8918
Chalard Jeane6c95272022-01-25 21:04:21 +09008919 private static UidRangeParcel[] intsToUidRangeStableParcels(
8920 final @NonNull ArraySet<Integer> uids) {
8921 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8922 int index = 0;
8923 for (int uid : uids) {
8924 stableRanges[index] = new UidRangeParcel(uid, uid);
8925 index++;
8926 }
8927 return stableRanges;
8928 }
8929
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008930 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8931 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8932 for (int i = 0; i < ranges.length; i++) {
8933 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8934 }
8935 return stableRanges;
8936 }
8937
Motomu Utsumi93a22182023-03-16 17:04:21 +09008938 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09008939 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08008940 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8941 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09008942 if (mDeps.isAtLeastU()) {
8943 final Set<Integer> exemptUidSet = new ArraySet<>();
8944 for (final int uid: exemptUids) {
8945 exemptUidSet.add(uid);
8946 }
8947 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
8948 } else {
8949 mNetd.socketDestroy(uidRangeParcels, exemptUids);
8950 }
Ken Chen5e65a852020-12-24 12:59:10 +08008951 } catch (Exception e) {
8952 loge("Exception in socket destroy: ", e);
8953 }
8954 }
8955 }
8956
paulhuaa0743d2021-05-26 21:56:03 +08008957 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09008958 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08008959 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8960 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8961 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09008962 exemptUids[0] = VPN_UID;
8963 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08008964 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8965
Motomu Utsumi6345e462023-03-13 13:24:50 +09008966 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09008967 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008968 try {
8969 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008970 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008971 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008972 } else {
paulhu0e79d952021-06-09 16:11:35 +08008973 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008974 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008975 }
8976 } catch (Exception e) {
8977 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8978 " on netId " + nai.network.netId + ". " + e);
8979 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09008980 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09008981 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008982 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008983
lucaslin53e8a262021-06-08 01:43:59 +08008984 private boolean isProxySetOnAnyDefaultNetwork() {
8985 ensureRunningOnConnectivityServiceThread();
8986 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8987 final NetworkAgentInfo nai = nri.getSatisfier();
8988 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8989 return true;
8990 }
8991 }
8992 return false;
8993 }
8994
8995 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8996 NetworkCapabilities newNc) {
8997 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8998 // the proxy might be changed since the default network satisfied by the apps might also
8999 // changed.
9000 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9001 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009002 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9003 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009004 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009005 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9006 mProxyTracker.sendProxyBroadcast();
9007 }
9008 }
9009
Chalard Jeane6c95272022-01-25 21:04:21 +09009010 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9011 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009012 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9013 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009014 if (null == prevRanges) prevRanges = new ArraySet<>();
9015 if (null == newRanges) newRanges = new ArraySet<>();
9016 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9017
9018 prevRanges.removeAll(newRanges);
9019 newRanges.removeAll(prevRangesCopy);
9020
9021 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009022 // When updating the VPN uid routing rules, add the new range first then remove the old
9023 // range. If old range were removed first, there would be a window between the old
9024 // range being removed and the new range being added, during which UIDs contained
9025 // in both ranges are not subject to any VPN routing rules. Adding new range before
9026 // removing old range works because, unlike the filtering rules below, it's possible to
9027 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009028 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9029 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9030 // [1-5] & [1-2],[4-5] == [3]
9031 // Then we can do:
9032 // maybeCloseSockets([3])
9033 // mNetd.networkAddUidRanges([1-2],[4-5])
9034 // mNetd.networkRemoveUidRanges([1-5])
9035 // maybeCloseSockets([3])
9036 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9037 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009038 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009039 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009040 }
9041 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009042 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009043 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009044 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9045 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009046 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9047 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009048 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009049 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009050 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9051 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9052 // were added first and then newRanges got removed later, there would be only one uid
9053 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9054 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9055 // Note that this is in contrast with the (more robust) update of VPN routing rules
9056 // above, where the addition of new ranges happens before the removal of old ranges.
9057 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9058 // to be removed will never overlap with the new range to be added.
9059 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009060 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9061 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009062 }
9063 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009064 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009065 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009066 } catch (Exception e) {
9067 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009068 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009069 }
9070 }
9071
Chalard Jeande665262022-02-25 16:12:12 +09009072 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009073 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9074 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009075 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9076 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009077 if (prevEmpty && newEmpty) return;
9078
9079 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009080 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009081 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009082 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009083
9084 if (prevUids.equals(newUids)) return;
9085
9086 // This implementation is very simple and vastly faster for sets of Integers than
9087 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9088 // a key computed from the value and has storage for that.
9089 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9090 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9091 toRemove.removeAll(newUids);
9092 toAdd.removeAll(prevUids);
9093
9094 try {
9095 if (!toAdd.isEmpty()) {
9096 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9097 nai.network.netId,
9098 intsToUidRangeStableParcels(toAdd),
9099 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9100 }
9101 if (!toRemove.isEmpty()) {
9102 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9103 nai.network.netId,
9104 intsToUidRangeStableParcels(toRemove),
9105 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9106 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009107 } catch (ServiceSpecificException e) {
9108 // Has the interface disappeared since the network was built ?
9109 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009110 } catch (RemoteException e) {
9111 // Netd died. This usually causes a runtime restart anyway.
9112 }
9113 }
9114
Junyu Lai2ed7d412022-10-07 16:52:21 +08009115 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9116 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009117 ensureRunningOnConnectivityServiceThread();
9118
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009119 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009120 // Ignore updates for disconnected networks
9121 return;
9122 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009123 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009124 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009125 + "; created=" + nai.getCreatedTime()
9126 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009127 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009128 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9129 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009130 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009131 }
9132
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009133 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9134 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009135 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009136 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009137 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009138 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9139 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9140 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009141 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9142 // need to be sent as a separate extra.
9143 final NetworkRequest req = nri.isMultilayerRequest()
9144 ? nri.getActiveRequest()
9145 // Non-multilayer listen requests do not have an active request
9146 : nri.mRequests.get(0);
9147 if (req == null) {
9148 Log.wtf(TAG, "No request in NRI " + nri);
9149 }
9150 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009151 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009152 sendIntent(nri.mPendingIntent, intent);
9153 }
9154 // else not handled
9155 }
9156
Michael Groover73f69482023-01-27 11:01:25 -06009157 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9158 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009159 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9160 mPendingIntentWakeLock.acquire();
9161 try {
9162 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009163 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009164 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009165 // Explicitly disallow the receiver from starting activities, to prevent apps from
9166 // utilizing the PendingIntent as a backdoor to do this.
9167 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9168 }
9169 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9170 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009171 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009172 } catch (PendingIntent.CanceledException e) {
9173 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9174 mPendingIntentWakeLock.release();
9175 releasePendingNetworkRequest(pendingIntent);
9176 }
9177 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9178 }
9179
9180 @Override
9181 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9182 String resultData, Bundle resultExtras) {
9183 if (DBG) log("Finished sending " + pendingIntent);
9184 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009185 // Release with a delay so the receiving client has an opportunity to put in its
9186 // own request.
9187 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009188 }
9189
Chalard Jean46bfbf02022-02-02 00:56:25 +09009190 // networkAgent is only allowed to be null if notificationType is
9191 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9192 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009193 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009194 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009195 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009196 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009197 // Default request has no msgr. Also prevents callbacks from being invoked for
9198 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9199 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9200 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009201 }
Anton Kulakovcc409152023-10-13 15:04:01 +00009202 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009203 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009204 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009205 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009206 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009207 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009208 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9209 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009210 }
Roshan Pius951c0032020-12-22 15:10:42 -08009211 final boolean includeLocationSensitiveInfo =
9212 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009213 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009214 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009215 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009216 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009217 networkCapabilitiesRestrictedForCallerPermissions(
9218 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9219 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009220 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009221 nri.mCallingAttributionTag);
9222 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009223 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9224 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08009225 // For this notification, arg1 contains the blocked status.
9226 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009227 break;
9228 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009229 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009230 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009231 break;
9232 }
9233 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009234 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009235 final NetworkCapabilities netCap =
9236 networkCapabilitiesRestrictedForCallerPermissions(
9237 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9238 putParcelable(
9239 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009240 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009241 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009242 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009243 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009244 break;
9245 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009246 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009247 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9248 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009249 break;
9250 }
junyulaif2c67e42018-08-07 19:50:45 +08009251 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009252 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009253 msg.arg1 = arg1;
9254 break;
9255 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009256 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009257 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009258 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009259 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009260 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009261 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009262 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009263 }
James Mattis45d81842021-01-10 14:24:24 -08009264 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009265 } catch (RemoteException e) {
9266 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009267 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009268 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009269 }
9270
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009271 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9272 bundle.putParcelable(t.getClass().getSimpleName(), t);
9273 }
9274
Chalard Jean0702f982021-09-16 21:50:07 +09009275 /**
9276 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9277 *
9278 * When a request should be assigned to a new network, it is normally lingered to give
9279 * time for apps to gracefully migrate their connections. When both networks are on the same
9280 * radio, but that radio can't do time-sharing efficiently, this may end up being
9281 * counter-productive because any traffic on the old network may drastically reduce the
9282 * performance of the new network.
9283 * The stack supports a configuration to let modem vendors state that their radio can't
9284 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9285 * from one cell network to another can't be done gracefully.
9286 *
9287 * @param oldNai the old network serving the request
9288 * @param newNai the new network serving the request
9289 * @return whether the switch can be graceful
9290 */
9291 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9292 @NonNull final NetworkAgentInfo newSatisfier) {
9293 if (mCellularRadioTimesharingCapable) return true;
9294 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9295 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9296 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9297 }
9298
Paul Jensenaf94b982014-09-30 15:37:41 -04009299 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009300 if (nai.numRequestNetworkRequests() != 0) {
9301 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9302 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009303 // Ignore listening and track default requests.
9304 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009305 loge("Dead network still had at least " + nr);
9306 break;
9307 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009308 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009309 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009310 }
9311
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009312 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9313 if (oldNetwork == null) {
9314 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9315 return;
9316 }
Chalard Jean49707572019-12-10 21:07:02 +09009317 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009318
9319 // If we get here it means that the last linger timeout for this network expired. So there
9320 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009321 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009322
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009323 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009324 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009325 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009326 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009327 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009328 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009329 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009330 }
9331
James Mattise3ef1912020-12-20 11:09:58 -08009332 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9333 boolean isDefaultChanged = false;
9334 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9335 final NetworkReassignment.RequestReassignment reassignment =
9336 changes.getReassignment(defaultRequestInfo);
9337 if (null == reassignment) {
9338 continue;
9339 }
9340 // reassignment only contains those instances where the satisfying network changed.
9341 isDefaultChanged = true;
9342 // Notify system services of the new default.
9343 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9344 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009345
James Mattise3ef1912020-12-20 11:09:58 -08009346 if (isDefaultChanged) {
9347 // Hold a wakelock for a short time to help apps in migrating to a new default.
9348 scheduleReleaseNetworkTransitionWakelock();
9349 }
9350 }
9351
Aaron Huang9fe47be2021-06-08 13:11:45 +08009352 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9353 if (null == oldDefaultNetwork) return;
9354 // The network stopped being the default. If it was using a PAC proxy, then the
9355 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9356 // to the local proxy server, which would forward them over the newly default network.
9357 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9358 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9359 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9360 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9361 }
9362
James Mattise3ef1912020-12-20 11:09:58 -08009363 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9364 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9365 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9366 if (DBG) {
9367 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9368 }
Chalard Jean8e382112019-12-03 20:45:30 +09009369
James Mattisd31bdfa2020-12-23 16:37:26 -08009370 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9371 if (newDefaultNetwork != null) {
9372 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009373 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009374
James Mattisd31bdfa2020-12-23 16:37:26 -08009375 // Set an app level managed default and return since further processing only applies to the
9376 // default network.
9377 if (mDefaultRequest != nri) {
9378 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9379 return;
9380 }
9381
9382 makeDefaultNetwork(newDefaultNetwork);
9383
James Mattise3ef1912020-12-20 11:09:58 -08009384 if (oldDefaultNetwork != null) {
9385 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9386 }
9387 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009388 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009389 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009390 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009391 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009392 updateTcpBufferSizes(null != newDefaultNetwork
9393 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009394 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009395 }
9396
James Mattisd31bdfa2020-12-23 16:37:26 -08009397 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9398 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9399 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9400 try {
9401 if (VDBG) {
9402 log("Setting default network for " + nri
9403 + " using UIDs " + nri.getUids()
9404 + " with old network " + (oldDefaultNetwork != null
9405 ? oldDefaultNetwork.network().getNetId() : "null")
9406 + " and new network " + (newDefaultNetwork != null
9407 ? newDefaultNetwork.network().getNetId() : "null"));
9408 }
9409 if (nri.getUids().isEmpty()) {
9410 throw new IllegalStateException("makeDefaultForApps called without specifying"
9411 + " any applications to set as the default." + nri);
9412 }
9413 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009414 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009415 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009416 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009417 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009418 }
9419 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009420 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009421 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009422 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009423 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009424 }
9425 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009426 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009427 }
9428 }
9429
Junyu Lai35665cc2022-12-19 17:37:48 +08009430 /**
9431 * Collect restricted uid ranges for the given network and UserHandle, these uids
9432 * are not restricted for matched enterprise networks but being restricted for non-matched
9433 * enterprise networks and non-enterprise networks.
9434 */
9435 @NonNull
9436 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9437 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9438 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9439 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9440 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9441
9442 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9443 // The NC is built from a `ProfileNetworkPreference` which has only one
9444 // enterprise ID, so it's guaranteed to have exactly one.
9445 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9446 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9447 continue;
9448 }
9449 }
9450
9451 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9452 pref.capabilities.getUidRanges())) {
9453 throw new IllegalArgumentException(
9454 "Overlapping uid range in preference: " + pref);
9455 }
9456 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9457 }
9458 return restrictedUidRanges;
9459 }
9460
9461 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009462 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +09009463 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009464
Junyu Lai35665cc2022-12-19 17:37:48 +08009465 ensureRunningOnConnectivityServiceThread();
9466 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9467 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9468 .getUserHandles(true /* excludeDying */);
9469 if (users.isEmpty()) {
9470 throw new IllegalStateException("No user is available");
9471 }
9472
9473 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9474 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9475 for (final UserHandle user : users) {
9476 final ArraySet<UidRange> restrictedUidRanges =
9477 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9478 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9479 UidRange.createForUser(user), restrictedUidRanges));
9480 }
9481
9482 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9483 configs.add(new NativeUidRangeConfig(
9484 nai.network.netId, rangesParcel, 0 /* subPriority */));
9485 }
9486
9487 // The netd API replaces the previous configs with the current configs.
9488 // Thus, for network disconnection or preference removal, no need to
9489 // unset previous config. Instead, collecting all currently needed
9490 // configs and issue to netd.
9491 try {
9492 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9493 } catch (ServiceSpecificException e) {
9494 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009495 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009496 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009497 // Netd died. This will cause a runtime restart anyway.
9498 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009499 }
9500 }
9501
James Mattisd31bdfa2020-12-23 16:37:26 -08009502 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9503 try {
9504 if (null != newDefaultNetwork) {
9505 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9506 } else {
9507 mNetd.networkClearDefault();
9508 }
9509 } catch (RemoteException | ServiceSpecificException e) {
9510 loge("Exception setting default network :" + e);
9511 }
9512 }
9513
Chalard Jean05cbe972019-12-09 11:50:38 +09009514 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009515 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009516 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009517 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009518 processNewlySatisfiedListenRequests(nai);
9519 }
9520
9521 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009522 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9523 if (nri.isMultilayerRequest()) {
9524 continue;
9525 }
9526 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009527 if (!nr.isListen()) continue;
9528 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009529 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009530 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9531 }
9532 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009533 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009534
Chalard Jeancd397a22019-11-22 22:33:33 +09009535 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009536 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9537 if (nri.isMultilayerRequest()) {
9538 continue;
9539 }
9540 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009541 if (!nr.isListen()) continue;
9542 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9543 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009544 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009545 }
9546 }
9547 }
9548
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009549 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009550 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009551 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009552 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009553 @Nullable public final NetworkRequest mOldNetworkRequest;
9554 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009555 @Nullable public final NetworkAgentInfo mOldNetwork;
9556 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009557 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009558 @Nullable final NetworkRequest oldNetworkRequest,
9559 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009560 @Nullable final NetworkAgentInfo oldNetwork,
9561 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009562 mNetworkRequestInfo = networkRequestInfo;
9563 mOldNetworkRequest = oldNetworkRequest;
9564 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009565 mOldNetwork = oldNetwork;
9566 mNewNetwork = newNetwork;
9567 }
Chalard Jean49707572019-12-10 21:07:02 +09009568
9569 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009570 final NetworkRequest requestToShow = null != mNewNetworkRequest
9571 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9572 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009573 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9574 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009575 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009576 }
9577
Chalard Jean46a62372019-12-10 21:25:24 +09009578 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009579
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009580 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009581 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009582 }
9583
9584 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009585 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009586 // The code is never supposed to add two reassignments of the same request. Make
9587 // sure this stays true, but without imposing this expensive check on all
9588 // reassignments on all user devices.
9589 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009590 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009591 throw new IllegalStateException("Trying to reassign ["
9592 + reassignment + "] but already have ["
9593 + existing + "]");
9594 }
9595 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009596 }
Chalard Jean46a62372019-12-10 21:25:24 +09009597 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009598 }
9599
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009600 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009601 // the passed request.
9602 @Nullable
9603 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009604 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009605 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009606 }
9607 return null;
9608 }
Chalard Jean49707572019-12-10 21:07:02 +09009609
9610 public String toString() {
9611 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9612 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009613 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009614 for (final RequestReassignment rr : getRequestReassignments()) {
9615 sj.add(rr.toString());
9616 }
9617 return sj.toString();
9618 }
9619
9620 public String debugString() {
9621 final StringBuilder sb = new StringBuilder();
9622 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009623 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009624 for (final RequestReassignment rr : getRequestReassignments()) {
9625 sb.append("\n ").append(rr);
9626 }
9627 return sb.append("\n").toString();
9628 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009629 }
9630
Chalard Jean24344d72019-12-04 13:32:31 +09009631 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009632 @Nullable final NetworkRequest previousRequest,
9633 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009634 @Nullable final NetworkAgentInfo previousSatisfier,
9635 @Nullable final NetworkAgentInfo newSatisfier,
9636 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009637 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009638 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009639 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009640 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009641 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09009642 }
James Mattisa076c532020-12-02 14:12:41 -08009643 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009644 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009645 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009646 // If this network switch can't be supported gracefully, the request is not
9647 // lingered. This allows letting go of the network sooner to reclaim some
9648 // performance on the new network, since the radio can't do both at the same
9649 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009650 //
9651 // Also don't linger the request if the old network has been destroyed.
9652 // A destroyed network does not provide actual network connectivity, so
9653 // lingering it is not useful. In particular this ensures that a destroyed
9654 // network is outscored by its replacement,
9655 // then it is torn down immediately instead of being lingered, and any apps that
9656 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009657 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9658 }
Chalard Jean24344d72019-12-04 13:32:31 +09009659 } else {
9660 if (VDBG || DDBG) log(" accepting network in place of null");
9661 }
junyulai0ac374f2020-12-14 18:41:52 +08009662
9663 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9664 // and immediately satisfies a request then remove the timer. This will happen for
9665 // all networks except in the case of an underlying network for a VCN.
9666 if (newSatisfier.isNascent()) {
9667 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009668 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009669 }
9670
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009671 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009672 newSatisfier.unlingerRequest(newRequest.requestId);
9673 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009674 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009675 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009676 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009677 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009678 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009679 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009680 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009681 }
James Mattisa076c532020-12-02 14:12:41 -08009682 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009683 }
James Mattisa076c532020-12-02 14:12:41 -08009684 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009685 }
9686
James Mattisa076c532020-12-02 14:12:41 -08009687 /**
9688 * This function is triggered when something can affect what network should satisfy what
9689 * request, and it computes the network reassignment from the passed collection of requests to
9690 * network match to the one that the system should now have. That data is encoded in an
9691 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9692 * satisfier.
9693 *
9694 * After the reassignment is computed, it is applied to the state objects.
9695 *
9696 * @param networkRequests the nri objects to evaluate for possible network reassignment
9697 * @return NetworkReassignment listing of proposed network assignment changes
9698 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009699 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009700 private NetworkReassignment computeNetworkReassignment(
9701 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009702 final NetworkReassignment changes = new NetworkReassignment();
9703
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009704 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009705 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009706 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009707 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009708 }
Chalard Jean857a1712019-12-10 21:08:07 +09009709
James Mattisa076c532020-12-02 14:12:41 -08009710 for (final NetworkRequestInfo nri : networkRequests) {
9711 // Non-multilayer listen requests can be ignored.
9712 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9713 continue;
9714 }
9715 NetworkAgentInfo bestNetwork = null;
9716 NetworkRequest bestRequest = null;
9717 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009718 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009719 // Stop evaluating as the highest possible priority request is satisfied.
9720 if (null != bestNetwork) {
9721 bestRequest = req;
9722 break;
9723 }
9724 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009725 if (null == bestNetwork && isDefaultBlocked(nri)) {
9726 // Remove default networking if disallowed for managed default requests.
9727 bestNetwork = mNoServiceNetwork;
9728 }
9729 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009730 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009731 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009732 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009733 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009734 }
9735 return changes;
9736 }
9737
James Mattisa076c532020-12-02 14:12:41 -08009738 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9739 return new HashSet<>(mNetworkRequests.values());
9740 }
9741
Paul Jensenc88b39b2015-06-16 14:27:36 -04009742 /**
James Mattisa076c532020-12-02 14:12:41 -08009743 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009744 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009745 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009746 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009747 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9748 }
9749
9750 /**
9751 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9752 * being disconnected.
9753 */
9754 private void rematchNetworksAndRequests(
9755 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9756 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009757 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009758 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009759 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009760 final long computed = SystemClock.elapsedRealtime();
9761 applyNetworkReassignment(changes, start);
9762 final long applied = SystemClock.elapsedRealtime();
9763 issueNetworkNeeds();
9764 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009765 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009766 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9767 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009768 log(changes.debugString());
9769 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009770 // Shorter form, only one line of log
9771 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9772 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009773 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009774 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009775
Chalard Jeand7f762d2019-12-10 19:01:29 +09009776 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009777 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009778 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009779
9780 // Since most of the time there are only 0 or 1 background networks, it would probably
9781 // be more efficient to just use an ArrayList here. TODO : measure performance
9782 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9783 for (final NetworkAgentInfo nai : nais) {
9784 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9785 }
9786
Chalard Jeand7f762d2019-12-10 19:01:29 +09009787 // First, update the lists of satisfied requests in the network agents. This is necessary
9788 // because some code later depends on this state to be correct, most prominently computing
9789 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009790 for (final NetworkReassignment.RequestReassignment event :
9791 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009792 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9793 event.mOldNetworkRequest, event.mNewNetworkRequest,
9794 event.mOldNetwork, event.mNewNetwork,
9795 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009796 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009797
James Mattise3ef1912020-12-20 11:09:58 -08009798 // Process default network changes if applicable.
9799 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009800
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009801 // Notify requested networks are available after the default net is switched, but
9802 // before LegacyTypeTracker sends legacy broadcasts
9803 for (final NetworkReassignment.RequestReassignment event :
9804 changes.getRequestReassignments()) {
9805 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009806 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009807 } else {
James Mattisa076c532020-12-02 14:12:41 -08009808 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009809 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009810 }
9811 }
9812
junyulai0ac374f2020-12-14 18:41:52 +08009813 // Update the inactivity state before processing listen callbacks, because the background
9814 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009815 // just yet though, because they have to be sent after the listens are processed to keep
9816 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009817 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009818 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009819 // Rematching may have altered the inactivity state of some networks, so update all
9820 // inactivity timers. updateInactivityState reads the state from the network agent
9821 // and does nothing if the state has not changed : the source of truth is controlled
9822 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9823 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009824 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009825 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009826 }
9827 }
9828
Chalard Jeanb10ab412019-12-11 14:12:30 +09009829 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009830 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009831 // Process listen requests and update capabilities if the background state has
9832 // changed for this network. For consistency with previous behavior, send onLost
9833 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009834 processNewlyLostListenRequests(nai);
9835 if (oldBackground != nai.isBackgroundNetwork()) {
9836 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009837 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009838 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009839 }
9840
junyulai0ac374f2020-12-14 18:41:52 +08009841 for (final NetworkAgentInfo nai : inactiveNetworks) {
9842 // For nascent networks, if connecting with no foreground request, skip broadcasting
9843 // LOSING for backward compatibility. This is typical when mobile data connected while
9844 // wifi connected with mobile data always-on enabled.
9845 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009846 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009847 }
9848
James Mattise3ef1912020-12-20 11:09:58 -08009849 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009850
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009851 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +00009852 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009853 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009854 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009855 // This network has active linger timers and no requests, but is not
9856 // lingering. Linger it.
9857 //
9858 // One way (the only way?) this can happen if this network is unvalidated
9859 // and became unneeded due to another network improving its score to the
9860 // point where this network will no longer be able to satisfy any requests
9861 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009862 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009863 notifyNetworkLosing(nai, now);
9864 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009865 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009866 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009867 teardownUnneededNetwork(nai);
9868 }
9869 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009870 }
9871 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009872
Chalard Jean62edfd82019-12-02 18:39:29 +09009873 /**
9874 * Apply a change in background state resulting from rematching networks with requests.
9875 *
9876 * During rematch, a network may change background states by starting to satisfy or stopping
9877 * to satisfy a foreground request. Listens don't count for this. When a network changes
9878 * background states, its capabilities need to be updated and callbacks fired for the
9879 * capability change.
9880 *
9881 * @param nai The network that changed background states
9882 */
9883 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
9884 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
9885 if (Objects.equals(nai.networkCapabilities, newNc)) return;
9886 updateNetworkPermissions(nai, newNc);
9887 nai.getAndSetNetworkCapabilities(newNc);
9888 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
9889 }
9890
Chalard Jeanf0344532019-11-19 19:23:38 +09009891 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08009892 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009893 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09009894 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
9895 changes.getReassignment(mDefaultRequest);
9896 final NetworkAgentInfo oldDefaultNetwork =
9897 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
9898 final NetworkAgentInfo newDefaultNetwork =
9899 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08009900
Chalard Jean5b409c72021-02-04 13:12:59 +09009901 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009902 // Maintain the illusion : since the legacy API only understands one network at a time,
9903 // if the default network changed, apps should see a disconnected broadcast for the
9904 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009905 if (oldDefaultNetwork != null) {
9906 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9907 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009908 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009909 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009910 // The new default network can be newly null if and only if the old default
9911 // network doesn't satisfy the default request any more because it lost a
9912 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009913 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009914 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009915 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009916 }
9917 }
9918
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009919 // Now that all the callbacks have been sent, send the legacy network broadcasts
9920 // as needed. This is necessary so that legacy requests correctly bind dns
9921 // requests to this network. The legacy users are listening for this broadcast
9922 // and will generally do a dns request so they can ensureRouteToHost and if
9923 // they do that before the callbacks happen they'll use the default network.
9924 //
9925 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
9926 // callbacks, but if apps can receive the broadcast before the callback, they still might
9927 // have an inconsistent view of networking.
9928 //
9929 // This *does* introduce a race where if the user uses the new api
9930 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
9931 // they may get old info. Reverse this after the old startUsing api is removed.
9932 // This is on top of the multiple intent sequencing referenced in the todo above.
9933 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09009934 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009935 addNetworkToLegacyTypeTracker(nai);
9936 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08009937 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009938 }
9939
Chalard Jean0354d8c2021-01-12 10:58:56 +09009940 private void issueNetworkNeeds() {
9941 ensureRunningOnConnectivityServiceThread();
9942 for (final NetworkOfferInfo noi : mNetworkOffers) {
9943 issueNetworkNeeds(noi);
9944 }
9945 }
9946
9947 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
9948 ensureRunningOnConnectivityServiceThread();
9949 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9950 informOffer(nri, noi.offer, mNetworkRanker);
9951 }
9952 }
9953
9954 /**
9955 * Inform a NetworkOffer about any new situation of a request.
9956 *
9957 * This function handles updates to offers. A number of events may happen that require
9958 * updating the registrant for this offer about the situation :
9959 * • The offer itself was updated. This may lead the offer to no longer being able
9960 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
9961 * or conversely being strengthened enough to beat the satisfier (and therefore
9962 * start being needed)
9963 * • The network satisfying a request changed (including cases where the request
9964 * starts or stops being satisfied). The new network may be a stronger or weaker
9965 * match than the old one, possibly affecting whether the offer is needed.
9966 * • The network satisfying a request updated their score. This may lead the offer
9967 * to no longer be able to beat it if the current satisfier got better, or
9968 * conversely start being a good choice if the current satisfier got weaker.
9969 *
9970 * @param nri The request
9971 * @param offer The offer. This may be an updated offer.
9972 */
9973 private static void informOffer(@NonNull NetworkRequestInfo nri,
9974 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9975 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9976 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009977
9978 // Multi-layer requests have a currently active request, the one being satisfied.
9979 // Since the system will try to bring up a better network than is currently satisfying
9980 // the request, NetworkProviders need to be told the offers matching the requests *above*
9981 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9982 // not needed, and the offer is needed for the active request iff the offer can beat
9983 // the satisfier.
9984 // For non-multilayer requests, the logic above gracefully degenerates to only the
9985 // last case.
9986 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9987 // providers that the offer is needed for this request, until the active request is found.
9988 // In a second phase, deal with the currently active request. In a third phase, inform
9989 // the providers that offer is unneeded for the remaining requests.
9990
9991 // First phase : inform providers of all requests above the active request.
9992 int i;
9993 for (i = 0; nri.mRequests.size() > i; ++i) {
9994 final NetworkRequest request = nri.mRequests.get(i);
9995 if (activeRequest == request) break; // Found the active request : go to phase 2
9996 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9997 // Since this request is higher-priority than the one currently satisfied, if the
9998 // offer can satisfy it, the provider should try and bring up the network for sure ;
9999 // no need to even ask the ranker – an offer that can satisfy is always better than
10000 // no network. Hence tell the provider so unless it already knew.
10001 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10002 offer.onNetworkNeeded(request);
10003 }
10004 }
10005
10006 // Second phase : deal with the active request (if any)
10007 if (null != activeRequest && activeRequest.isRequest()) {
10008 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010009 // If an offer can satisfy the request, it is considered needed if it is currently
10010 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010011 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010012 && satisfier.factorySerialNumber == offer.providerId
10013 && activeRequest.canBeSatisfiedBy(offer.caps);
10014 final boolean newNeeded = currentlyServing
10015 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010016 if (newNeeded != oldNeeded) {
10017 if (newNeeded) {
10018 offer.onNetworkNeeded(activeRequest);
10019 } else {
10020 // The offer used to be able to beat the satisfier. Now it can't.
10021 offer.onNetworkUnneeded(activeRequest);
10022 }
10023 }
10024 }
10025
10026 // Third phase : inform the providers that the offer isn't needed for any request
10027 // below the active one.
10028 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10029 final NetworkRequest request = nri.mRequests.get(i);
10030 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10031 // Since this request is lower-priority than the one currently satisfied, if the
10032 // offer can satisfy it, the provider should not try and bring up the network.
10033 // Hence tell the provider so unless it already knew.
10034 if (offer.neededFor(request)) {
10035 offer.onNetworkUnneeded(request);
10036 }
10037 }
10038 }
10039
Chalard Jean61c79252019-11-07 23:07:32 +090010040 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10041 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10042 NetworkRequest nr = nai.requestAt(i);
10043 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10044 // legacy type tracker filters out repeat adds
10045 mLegacyTypeTracker.add(nr.legacyType, nai);
10046 }
10047 }
10048
10049 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010050 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010051 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10052 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10053 if (nai.isVPN()) {
10054 mLegacyTypeTracker.add(TYPE_VPN, nai);
10055 }
10056 }
10057
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010058 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010059 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010060 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010061 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010062 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010063 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010064
Chalard Jean254bd162022-08-25 13:04:51 +090010065 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010066 // Don't repeat publish.
10067 if (newInetCondition == mDefaultInetConditionPublished) return;
10068
10069 mDefaultInetConditionPublished = newInetCondition;
10070 sendInetConditionBroadcast(nai.networkInfo);
10071 }
10072
Chalard Jeand61375d2020-01-14 22:46:36 +090010073 @NonNull
10074 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10075 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010076 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010077 final boolean suspended =
10078 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10079 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10080 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10081 // state. This is because the network could have been suspended before connecting,
10082 // or it could be disconnecting while being suspended, and in both these cases
10083 // the state should not be overridden. Note that the only detailed state that
10084 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10085 // worry about multiple different substates of CONNECTED.
10086 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10087 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010088 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10089 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10090 // network agent is created, then goes to suspended, then goes out of suspended without
10091 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010092 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010093 ? NetworkInfo.DetailedState.CONNECTED
10094 : NetworkInfo.DetailedState.CONNECTING,
10095 info.getReason(),
10096 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010097 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010098 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010099 return newInfo;
10100 }
10101
10102 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10103 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10104
Erik Kline99f301b2017-02-15 19:59:17 +090010105 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010106 NetworkInfo oldInfo = null;
10107 synchronized (networkAgent) {
10108 oldInfo = networkAgent.networkInfo;
10109 networkAgent.networkInfo = newInfo;
10110 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010111
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010112 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010113 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10114 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010115 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010116
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010117 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010118 // A network that has just connected has zero requests and is thus a foreground network.
10119 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10120
Luke Huangfdd11f82019-04-09 18:41:49 +080010121 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010122
10123 networkAgent.setCreated();
10124
10125 // If the network is created immediately on register, then apply the LinkProperties now.
10126 // Otherwise, this is done further down when the network goes into connected state.
10127 // Applying the LinkProperties means that the network is ready to carry traffic -
10128 // interfaces and routing rules have been added, DNS servers programmed, etc.
10129 // For VPNs, this must be done before the capabilities are updated, because as soon as
10130 // that happens, UIDs are routed to the network.
10131 if (shouldCreateNetworksImmediately()) {
10132 applyInitialLinkProperties(networkAgent);
10133 }
10134
10135 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10136 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010137 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010138 // Initialize the network's capabilities to their starting values according to the
10139 // underlying networks. This ensures that the capabilities are correct before
10140 // anything happens to the network.
10141 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010142 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010143 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010144 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010145 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010146 }
10147
Chalard Jean254bd162022-08-25 13:04:51 +090010148 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10149 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010150
lucaslin45e639b2019-04-03 17:09:28 +080010151 // NetworkCapabilities need to be set before sending the private DNS config to
10152 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010153 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10154
Erik Kline9a62f012018-03-21 07:18:33 -070010155 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010156 if (!shouldCreateNetworksImmediately()) {
10157 applyInitialLinkProperties(networkAgent);
10158 } else {
10159 // The network was created when the agent registered, and the LinkProperties are
10160 // already up-to-date. However, updateLinkProperties also makes some changes only
10161 // when the network connects. Apply those changes here. On T and below these are
10162 // handled by the applyInitialLinkProperties call just above.
10163 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10164 // If something depends on both LinkProperties and connected state, it should be in
10165 // this method as well.
10166 networkAgent.clatd.update();
10167 updateProxy(networkAgent.linkProperties, null);
10168 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010169
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010170 // If a rate limit has been configured and is applicable to this network (network
10171 // provides internet connectivity), apply it. The tc police filter cannot be attached
10172 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
10173 // updateInterfaces -> INetd#networkAddInterface.
10174 // Note: in case of a system server crash, the NetworkController constructor in netd
10175 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10176 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10177 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10178 mIngressRateLimit);
10179 }
10180
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010181 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10182 // command must be sent after updating LinkProperties to maximize chances of
10183 // NetworkMonitor seeing the correct LinkProperties when starting.
10184 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010185 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010186 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010187 }
Chalard Jeand4900722022-02-06 12:25:38 +090010188 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10189 params.networkAgentConfig = networkAgent.networkAgentConfig;
10190 params.networkCapabilities = networkAgent.networkCapabilities;
10191 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10192 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010193 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10194 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10195 // call that would cause a Log.wtf to be emitted from the system_server process, and
10196 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10197 // process to check the interface version, just use an SDK check. NetworkStack will
10198 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010199 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010200 networkAgent.networkMonitor().notifyNetworkConnected(params);
10201 } else {
10202 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10203 params.networkCapabilities);
10204 }
Chalard Jean0f141332023-06-05 19:26:17 +090010205 final long evaluationDelay;
10206 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10207 // If the network is anything other than pure wifi, use the default timeout.
10208 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10209 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10210 // If the network is explicitly selected, use the default timeout because it's
10211 // shorter and the user is likely staring at the screen expecting it to validate
10212 // right away.
10213 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10214 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10215 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10216 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10217 } else {
10218 // It's wifi, automatically connected, and bad wifi is preferred : use the
10219 // longer timeout to avoid the device switching to captive portals with bad
10220 // signal or very slow response.
10221 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10222 }
10223 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010224
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010225 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10226 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10227 // capabilities, so it only needs to be done once on initial connect, not every time the
10228 // network's capabilities change. Note that we do this before rematching the network,
10229 // so we could decide to tear it down immediately afterwards. That's fine though - on
10230 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10231 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010232 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010233
junyulai0ac374f2020-12-14 18:41:52 +080010234 // Before first rematching networks, put an inactivity timer without any request, this
10235 // allows {@code updateInactivityState} to update the state accordingly and prevent
10236 // tearing down for any {@code unneeded} evaluation in this period.
10237 // Note that the timer will not be rescheduled since the expiry time is
10238 // fixed after connection regardless of the network satisfying other requests or not.
10239 // But it will be removed as soon as the network satisfies a request for the first time.
10240 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10241 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010242 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010243
Paul Jensen05e85ee2014-09-11 11:00:39 -040010244 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010245 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010246
10247 // This has to happen after matching the requests, because callbacks are just requests.
10248 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010249 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010250 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010251 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010252 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010253 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010254 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010255 if (networkAgent.isVPN()) {
10256 // As the active or bound network changes for apps, broadcast the default proxy, as
10257 // apps may need to update their proxy data. This is called after disconnecting from
10258 // VPN to make sure we do not broadcast the old proxy data.
10259 // TODO(b/122649188): send the broadcast only to VPN users.
10260 mProxyTracker.sendProxyBroadcast();
10261 }
Chalard Jean254bd162022-08-25 13:04:51 +090010262 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10263 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010264 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010265 }
10266 }
10267
Chalard Jean28018572020-12-21 18:36:52 +090010268 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010269 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10270 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010271 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010272 }
10273
Erik Kline99f301b2017-02-15 19:59:17 +090010274 // Notify only this one new request of the current state. Transfer all the
10275 // current state by calling NetworkCapabilities and LinkProperties callbacks
10276 // so that callers can be guaranteed to have as close to atomicity in state
10277 // transfer as can be supported by this current API.
10278 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010279 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010280 if (nri.mPendingIntent != null) {
10281 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10282 // Attempt no subsequent state pushes where intents are involved.
10283 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010284 }
Erik Kline99f301b2017-02-15 19:59:17 +090010285
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010286 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010287 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010288 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10289 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10290 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010291 }
10292
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010293 // Notify the requests on this NAI that the network is now lingered.
10294 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010295 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010296 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10297 }
10298
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010299 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10300 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10301 return vpnBlocked
10302 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10303 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10304 }
10305
10306 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10307 if (blockedReasons == BLOCKED_REASON_NONE) {
10308 mUidBlockedReasons.delete(uid);
10309 } else {
10310 mUidBlockedReasons.put(uid, blockedReasons);
10311 }
10312 }
10313
junyulaif2c67e42018-08-07 19:50:45 +080010314 /**
10315 * Notify of the blocked state apps with a registered callback matching a given NAI.
10316 *
10317 * Unlike other callbacks, blocked status is different between each individual uid. So for
10318 * any given nai, all requests need to be considered according to the uid who filed it.
10319 *
10320 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010321 * @param oldMetered True if the previous network capabilities were metered.
10322 * @param newMetered True if the current network capabilities are metered.
10323 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10324 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010325 */
10326 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010327 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10328 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010329
10330 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10331 NetworkRequest nr = nai.requestAt(i);
10332 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010333
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010334 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10335 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10336 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010337 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010338 : oldVpnBlocked;
10339
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010340 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10341 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10342 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010343 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010344 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010345 }
10346 }
10347 }
10348
10349 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010350 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010351 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010352 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010353 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010354 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010355 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010356 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010357 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010358
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010359 final int oldBlockedState = getBlockedState(
10360 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10361 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10362 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010363 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010364 }
junyulaif2c67e42018-08-07 19:50:45 +080010365 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10366 NetworkRequest nr = nai.requestAt(i);
10367 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010368 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010369 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10370 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010371 }
10372 }
10373 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010374 }
10375
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010376 @VisibleForTesting
10377 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010378 // The NetworkInfo we actually send out has no bearing on the real
10379 // state of affairs. For example, if the default connection is mobile,
10380 // and a request for HIPRI has just gone away, we need to pretend that
10381 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10382 // the state to DISCONNECTED, even though the network is of type MOBILE
10383 // and is still connected.
10384 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10385 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010386 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010387 if (state != DetailedState.DISCONNECTED) {
10388 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010389 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010390 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010391 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010392 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10393 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10394 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10395 if (info.isFailover()) {
10396 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10397 nai.networkInfo.setFailover(false);
10398 }
10399 if (info.getReason() != null) {
10400 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10401 }
10402 if (info.getExtraInfo() != null) {
10403 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10404 }
10405 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010406 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010407 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010408 if (newDefaultAgent != null) {
10409 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10410 newDefaultAgent.networkInfo);
10411 } else {
10412 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10413 }
10414 }
10415 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10416 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010417 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010418 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010419 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010420 }
10421 }
10422 }
10423
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010424 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010425 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010426 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010427 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010428 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010429 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10430 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010431 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10432 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010433 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010434 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010435 } else {
10436 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10437 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010438 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010439 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010440
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010441 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10442 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10443 }
10444
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010445 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010446 * Returns the list of all interfaces that could be used by network traffic that does not
10447 * explicitly specify a network. This includes the default network, but also all VPNs that are
10448 * currently connected.
10449 *
10450 * Must be called on the handler thread.
10451 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010452 @NonNull
10453 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010454 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010455 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010456 final Set<Integer> activeNetIds = new ArraySet<>();
10457 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10458 if (nri.isBeingSatisfied()) {
10459 activeNetIds.add(nri.getSatisfier().network().netId);
10460 }
10461 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010462 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010463 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010464 defaultNetworks.add(nai.network);
10465 }
10466 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010467 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010468 }
10469
10470 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010471 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10472 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010473 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010474 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010475 ensureRunningOnConnectivityServiceThread();
10476 String activeIface = null;
10477 LinkProperties activeLinkProperties = getActiveLinkProperties();
10478 if (activeLinkProperties != null) {
10479 activeIface = activeLinkProperties.getInterfaceName();
10480 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010481
junyulai2050bed2021-01-23 09:46:34 +080010482 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010483 try {
junyulaide41fc22021-01-22 22:46:01 +080010484 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010485 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010486 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10487 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010488 } catch (Exception ignored) {
10489 }
10490 }
10491
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010492 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010493 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010494 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010495 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010496 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010497
10498 if (!TextUtils.isEmpty(settingUrl)) {
10499 return settingUrl;
10500 }
10501
10502 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010503 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010504 if (!TextUtils.isEmpty(settingUrl)) {
10505 return settingUrl;
10506 }
10507
10508 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010509 }
10510
10511 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010512 public void startNattKeepalive(Network network, int intervalSeconds,
10513 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010514 enforceKeepalivePermission();
10515 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010516 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010517 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10518 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010519 // false and set the underpinned network to null because there is no way and no
10520 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10521 // deprecated method.
10522 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010523 }
10524
10525 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010526 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010527 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010528 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010529 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010530 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010531 mKeepaliveTracker.startNattKeepalive(
10532 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010533 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10534 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010535 } finally {
10536 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10537 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010538 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10539 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010540 }
10541 }
junyulaid05a1922019-01-15 11:32:44 +080010542 }
10543
10544 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010545 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010546 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010547 try {
10548 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010549 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010550 mKeepaliveTracker.startTcpKeepalive(
10551 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10552 } finally {
10553 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10554 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010555 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10556 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010557 }
10558 }
junyulai0835a1e2019-01-08 20:04:33 +080010559 }
10560
10561 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010562 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010563 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010564 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10565 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010566 }
10567
10568 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090010569 public int[] getSupportedKeepalives() {
10570 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10571 // Backwards compatibility with CTS 13
10572 android.Manifest.permission.QUERY_ALL_PACKAGES);
10573
10574 return BinderUtils.withCleanCallingIdentity(() ->
10575 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10576 }
10577
10578 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010579 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010580 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010581
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010582 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010583 final long token = Binder.clearCallingIdentity();
10584 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010585 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10586 UserHandle.getUserHandleForUid(uid))) {
10587 return;
10588 }
10589
Heemin Seogdb8489d2019-06-12 09:21:44 -070010590 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10591 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010592
10593 // Turn airplane mode off
10594 setAirplaneMode(false);
10595
10596 // restore private DNS settings to default mode (opportunistic)
10597 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10598 UserHandle.getUserHandleForUid(uid))) {
10599 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10600 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10601 }
10602
10603 Settings.Global.putString(mContext.getContentResolver(),
10604 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010605 } finally {
10606 Binder.restoreCallingIdentity(token);
10607 }
Stuart Scottd5463642015-04-02 18:00:02 -070010608 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010609
Ricky Wai7097cc92018-01-23 04:09:45 +000010610 @Override
10611 public byte[] getNetworkWatchlistConfigHash() {
10612 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10613 if (nwm == null) {
10614 loge("Unable to get NetworkWatchlistManager");
10615 return null;
10616 }
10617 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10618 return nwm.getWatchlistConfigHash();
10619 }
10620
Hugo Benichibe0c7652016-05-31 16:28:06 +090010621 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010622 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010623 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010624 }
Hugo Benichif4210292017-04-21 15:07:12 +090010625
10626 private static boolean toBool(int encodedBoolean) {
10627 return encodedBoolean != 0; // Only 0 means false.
10628 }
10629
10630 private static int encodeBool(boolean b) {
10631 return b ? 1 : 0;
10632 }
mswest4632928412018-03-12 10:34:34 -070010633
10634 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010635 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10636 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10637 @NonNull String[] args) {
10638 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10639 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010640 }
10641
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010642 private Boolean parseBooleanArgument(final String arg) {
10643 if ("true".equals(arg)) {
10644 return true;
10645 } else if ("false".equals(arg)) {
10646 return false;
10647 } else {
10648 return null;
10649 }
10650 }
10651
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010652 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010653 @Override
10654 public int onCommand(String cmd) {
10655 if (cmd == null) {
10656 return handleDefaultCommands(cmd);
10657 }
10658 final PrintWriter pw = getOutPrintWriter();
10659 try {
10660 switch (cmd) {
10661 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010662 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
10663 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070010664 final String action = getNextArg();
10665 if ("enable".equals(action)) {
10666 setAirplaneMode(true);
10667 return 0;
10668 } else if ("disable".equals(action)) {
10669 setAirplaneMode(false);
10670 return 0;
10671 } else if (action == null) {
10672 final ContentResolver cr = mContext.getContentResolver();
10673 final int enabled = Settings.Global.getInt(cr,
10674 Settings.Global.AIRPLANE_MODE_ON);
10675 pw.println(enabled == 0 ? "disabled" : "enabled");
10676 return 0;
10677 } else {
10678 onHelp();
10679 return -1;
10680 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010681 case "set-chain3-enabled": {
10682 final Boolean enabled = parseBooleanArgument(getNextArg());
10683 if (null == enabled) {
10684 onHelp();
10685 return -1;
10686 }
10687 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
10688 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
10689 enabled);
10690 return 0;
10691 }
10692 case "get-chain3-enabled": {
10693 final boolean chainEnabled = getFirewallChainEnabled(
10694 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
10695 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
10696 return 0;
10697 }
10698 case "set-package-networking-enabled": {
10699 final Boolean enabled = parseBooleanArgument(getNextArg());
10700 final String packageName = getNextArg();
10701 if (null == enabled || null == packageName) {
10702 onHelp();
10703 return -1;
10704 }
10705 // Throws NameNotFound if the package doesn't exist.
10706 final int appId = setPackageFirewallRule(
10707 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
10708 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
10709 final String msg = (enabled ? "Enabled" : "Disabled")
10710 + " networking for " + packageName + ", appId " + appId;
10711 Log.i(TAG, msg);
10712 pw.println(msg);
10713 return 0;
10714 }
10715 case "get-package-networking-enabled": {
10716 final String packageName = getNextArg();
10717 final int rule = getPackageFirewallRule(
10718 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
10719 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
10720 pw.println(packageName + ":" + "allow");
10721 } else if (FIREWALL_RULE_DENY == rule) {
10722 pw.println(packageName + ":" + "deny");
10723 } else {
10724 throw new IllegalStateException("Unknown rule " + rule + " for package "
10725 + packageName);
10726 }
10727 return 0;
10728 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010729 case "reevaluate":
10730 // Usage : adb shell cmd connectivity reevaluate <netId>
10731 // If netId is omitted, then reevaluate the default network
10732 final String netId = getNextArg();
10733 final NetworkAgentInfo nai;
10734 if (null == netId) {
10735 // Note that the command is running on the wrong thread to call this,
10736 // so this could in principle return stale data. But it can't crash.
10737 nai = getDefaultNetwork();
10738 } else {
10739 // If netId can't be parsed, this throws NumberFormatException, which
10740 // is passed back to adb who prints it.
10741 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10742 }
10743 if (null == nai) {
10744 pw.println("Unknown network (net ID not found or no default network)");
10745 return 0;
10746 }
10747 Log.d(TAG, "Reevaluating network " + nai.network);
10748 reportNetworkConnectivity(nai.network, !nai.isValidated());
10749 return 0;
mswest4632928412018-03-12 10:34:34 -070010750 default:
10751 return handleDefaultCommands(cmd);
10752 }
10753 } catch (Exception e) {
10754 pw.println(e);
10755 }
10756 return -1;
10757 }
10758
10759 @Override
10760 public void onHelp() {
10761 PrintWriter pw = getOutPrintWriter();
10762 pw.println("Connectivity service commands:");
10763 pw.println(" help");
10764 pw.println(" Print this help text.");
10765 pw.println(" airplane-mode [enable|disable]");
10766 pw.println(" Turn airplane mode on or off.");
10767 pw.println(" airplane-mode");
10768 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010769 pw.println(" set-chain3-enabled [true|false]");
10770 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
10771 pw.println(" get-chain3-enabled");
10772 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
10773 pw.println(" set-package-networking-enabled [true|false] [package name]");
10774 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
10775 + " no effect if the chain is disabled.");
10776 pw.println(" get-package-networking-enabled [package name]");
10777 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
mswest4632928412018-03-12 10:34:34 -070010778 }
10779 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010780
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010781 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010782 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10783 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10784 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010785 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010786 }
10787
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010788 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10789 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010790 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10791 final TransportInfo newInfo = nc.getTransportInfo();
10792 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10793 return;
10794 }
10795 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010796 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010797 }
10798 }
10799
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010800 /**
10801 * @param connectionInfo the connection to resolve.
10802 * @return {@code uid} if the connection is found and the app has permission to observe it
10803 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10804 * connection is not found.
10805 */
10806 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010807 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10808 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10809 }
10810
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010811 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010812 connectionInfo.local, connectionInfo.remote);
10813
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010814 if (uid == INVALID_UID) return uid; // Not found.
10815
10816 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10817 // VPN, if any, that applies to the UID that owns the connection.
10818 if (checkNetworkStackPermission()) return uid;
10819
10820 final NetworkAgentInfo vpn = getVpnForUid(uid);
10821 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010822 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010823 return INVALID_UID;
10824 }
10825
10826 return uid;
10827 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010828
Benedict Wong493e04b2018-11-09 14:45:34 -080010829 /**
10830 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10831 *
10832 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10833 */
10834 @Override
10835 public IBinder startOrGetTestNetworkService() {
10836 synchronized (mTNSLock) {
10837 TestNetworkService.enforceTestNetworkPermissions(mContext);
10838
10839 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010840 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010841 }
10842
10843 return mTNS;
10844 }
10845 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010846
Cody Kesting73708bf2019-12-18 10:57:50 -080010847 /**
10848 * Handler used for managing all Connectivity Diagnostics related functions.
10849 *
10850 * @see android.net.ConnectivityDiagnosticsManager
10851 *
10852 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10853 */
10854 @VisibleForTesting
10855 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010856 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10857
Cody Kesting73708bf2019-12-18 10:57:50 -080010858 /**
10859 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10860 * android.net.ConnectivityDiagnosticsManager}.
10861 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10862 * NetworkRequestInfo to be registered
10863 */
10864 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10865
10866 /**
10867 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10868 * android.net.ConnectivityDiagnosticsManager}.
10869 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10870 * arg1 = the uid of the caller
10871 */
10872 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10873
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010874 /**
10875 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010876 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010877 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10878 * NetworkMonitor.
10879 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010880 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010881 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010882
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010883 /**
10884 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10885 * been detected on the network.
10886 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10887 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10888 * arg2 = NetID.
10889 * data = PersistableBundle of extras passed from NetworkMonitor.
10890 */
10891 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10892
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010893 /**
10894 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10895 * the platform. This event will invoke {@link
10896 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10897 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070010898 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010899 */
10900 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
10901
Cody Kesting73708bf2019-12-18 10:57:50 -080010902 private ConnectivityDiagnosticsHandler(Looper looper) {
10903 super(looper);
10904 }
10905
10906 @Override
10907 public void handleMessage(Message msg) {
10908 switch (msg.what) {
10909 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10910 handleRegisterConnectivityDiagnosticsCallback(
10911 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
10912 break;
10913 }
10914 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10915 handleUnregisterConnectivityDiagnosticsCallback(
10916 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
10917 break;
10918 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010919 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010920 final ConnectivityReportEvent reportEvent =
10921 (ConnectivityReportEvent) msg.obj;
10922
Aaron Huang959d3642021-01-21 15:47:41 +080010923 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010924 break;
10925 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010926 case EVENT_DATA_STALL_SUSPECTED: {
10927 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080010928 final Pair<Long, PersistableBundle> arg =
10929 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010930 if (nai == null) break;
10931
Aaron Huang959d3642021-01-21 15:47:41 +080010932 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010933 break;
10934 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010935 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070010936 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010937 break;
10938 }
10939 default: {
10940 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
10941 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010942 }
10943 }
10944 }
10945
10946 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
10947 @VisibleForTesting
10948 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
10949 @NonNull private final IConnectivityDiagnosticsCallback mCb;
10950 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010951 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010952
10953 @VisibleForTesting
10954 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010955 @NonNull IConnectivityDiagnosticsCallback cb,
10956 @NonNull NetworkRequestInfo nri,
10957 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010958 mCb = cb;
10959 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010960 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010961 }
10962
10963 @Override
10964 public void binderDied() {
10965 log("ConnectivityDiagnosticsCallback IBinder died.");
10966 unregisterConnectivityDiagnosticsCallback(mCb);
10967 }
10968 }
10969
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010970 /**
10971 * Class used for sending information from {@link
10972 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
10973 */
10974 private static class NetworkTestedResults {
10975 private final int mNetId;
10976 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010977 @Nullable private final String mRedirectUrl;
10978
10979 private NetworkTestedResults(
10980 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
10981 mNetId = netId;
10982 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010983 mRedirectUrl = redirectUrl;
10984 }
10985 }
10986
10987 /**
10988 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
10989 * ConnectivityDiagnosticsHandler}.
10990 */
10991 private static class ConnectivityReportEvent {
10992 private final long mTimestampMillis;
10993 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080010994 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010995
Aaron Huang959d3642021-01-21 15:47:41 +080010996 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
10997 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010998 mTimestampMillis = timestampMillis;
10999 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011000 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011001 }
11002 }
11003
Cody Kestingf1120be2020-08-03 18:01:40 -070011004 /**
11005 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11006 * ConnectivityDiagnosticsHandler}.
11007 */
11008 private static class ReportedNetworkConnectivityInfo {
11009 public final boolean hasConnectivity;
11010 public final boolean isNetworkRevalidating;
11011 public final int reporterUid;
11012 @NonNull public final NetworkAgentInfo nai;
11013
11014 private ReportedNetworkConnectivityInfo(
11015 boolean hasConnectivity,
11016 boolean isNetworkRevalidating,
11017 int reporterUid,
11018 @NonNull NetworkAgentInfo nai) {
11019 this.hasConnectivity = hasConnectivity;
11020 this.isNetworkRevalidating = isNetworkRevalidating;
11021 this.reporterUid = reporterUid;
11022 this.nai = nai;
11023 }
11024 }
11025
Cody Kesting73708bf2019-12-18 10:57:50 -080011026 private void handleRegisterConnectivityDiagnosticsCallback(
11027 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11028 ensureRunningOnConnectivityServiceThread();
11029
11030 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011031 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011032 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11033
James Mattis64b8b0f2020-11-24 17:40:49 -080011034 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11035 // confusing for these networks to change when an NRI is satisfied in another layer.
11036 if (nri.isMultilayerRequest()) {
11037 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11038 + "network requests.");
11039 }
11040
Cody Kesting73708bf2019-12-18 10:57:50 -080011041 // This means that the client registered the same callback multiple times. Do
11042 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011043 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011044 if (VDBG) log("Diagnostics callback is already registered");
11045
11046 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11047 // incremented when the NetworkRequestInfo is created as part of
11048 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011049 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011050 return;
11051 }
11052
Cody Kesting31f1ff62020-03-05 10:46:02 -080011053 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011054
11055 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011056 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011057 } catch (RemoteException e) {
11058 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011059 return;
11060 }
11061
11062 // Once registered, provide ConnectivityReports for matching Networks
11063 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11064 synchronized (mNetworkForNetId) {
11065 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11066 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011067 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11068 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011069 matchingNetworks.add(nai);
11070 }
11071 }
11072 }
11073 for (final NetworkAgentInfo nai : matchingNetworks) {
11074 final ConnectivityReport report = nai.getConnectivityReport();
11075 if (report == null) {
11076 continue;
11077 }
11078 if (!checkConnectivityDiagnosticsPermissions(
11079 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11080 continue;
11081 }
11082
11083 try {
11084 cb.onConnectivityReportAvailable(report);
11085 } catch (RemoteException e) {
11086 // Exception while sending the ConnectivityReport. Move on to the next network.
11087 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011088 }
11089 }
11090
11091 private void handleUnregisterConnectivityDiagnosticsCallback(
11092 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11093 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011094 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011095
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011096 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11097 mConnectivityDiagnosticsCallbacks.remove(iCb);
11098 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011099 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11100 return;
11101 }
11102
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011103 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011104
Cody Kesting70fa2b22020-12-02 12:16:56 -080011105 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11106 // (if the Binder died)
11107 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11108 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011109 return;
11110 }
11111
Cody Kesting46cb1672020-03-04 13:35:20 -080011112 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11113 // incremented when the NetworkRequestInfo is created as part of
11114 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011115 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011116
Cody Kesting31f1ff62020-03-05 10:46:02 -080011117 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011118 }
11119
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011120 private void handleNetworkTestedWithExtras(
11121 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11122 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011123 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011124 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011125 final ConnectivityReport report =
11126 new ConnectivityReport(
11127 reportEvent.mNai.network,
11128 reportEvent.mTimestampMillis,
11129 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011130 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011131 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011132 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011133
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011134 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011135 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011136 for (final IConnectivityDiagnosticsCallback cb : results) {
11137 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011138 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011139 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011140 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011141 }
11142 }
11143 }
11144
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011145 private void handleDataStallSuspected(
11146 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11147 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011148 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011149 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011150 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011151 new DataStallReport(
11152 nai.network,
11153 timestampMillis,
11154 detectionMethod,
11155 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011156 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011157 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011158 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011159 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011160 for (final IConnectivityDiagnosticsCallback cb : results) {
11161 try {
11162 cb.onDataStallSuspected(report);
11163 } catch (RemoteException ex) {
11164 loge("Error invoking onDataStallSuspected", ex);
11165 }
11166 }
11167 }
11168
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011169 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011170 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11171 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11172 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11173
11174 // If the Network is being re-validated as a result of this call to
11175 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11176 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011177 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011178 getMatchingPermissionedCallbacks(
11179 nai,
11180 reportedNetworkConnectivityInfo.isNetworkRevalidating
11181 ? Process.INVALID_UID
11182 : reportedNetworkConnectivityInfo.reporterUid);
11183
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011184 for (final IConnectivityDiagnosticsCallback cb : results) {
11185 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011186 cb.onNetworkConnectivityReported(
11187 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011188 } catch (RemoteException ex) {
11189 loge("Error invoking onNetworkConnectivityReported", ex);
11190 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011191
11192 // If the Network isn't re-validating, also provide the cached report. If there is no
11193 // cached report, the Network is still being validated and a report will be sent once
11194 // validation is complete. Note that networks which never undergo validation will still
11195 // have a cached ConnectivityReport with RESULT_SKIPPED.
11196 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11197 try {
11198 cb.onConnectivityReportAvailable(cachedReport);
11199 } catch (RemoteException ex) {
11200 loge("Error invoking onConnectivityReportAvailable", ex);
11201 }
11202 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011203 }
11204 }
11205
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011206 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011207 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11208 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011209 sanitized.setUids(null);
11210 sanitized.setAdministratorUids(new int[0]);
11211 sanitized.setOwnerUid(Process.INVALID_UID);
11212 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011213 }
11214
Cody Kestingf1120be2020-08-03 18:01:40 -070011215 /**
11216 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11217 *
11218 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11219 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011220 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011221 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011222 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011223 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011224 mConnectivityDiagnosticsCallbacks.entrySet()) {
11225 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11226 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011227
James Mattis64b8b0f2020-11-24 17:40:49 -080011228 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011229 if (!nai.satisfies(nri.mRequests.get(0))) {
11230 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011231 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011232
11233 // UID for this callback must either be:
11234 // - INVALID_UID (which sends callbacks to all UIDs), or
11235 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11236 // notified as a result)
11237 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11238 continue;
11239 }
11240
11241 if (!checkConnectivityDiagnosticsPermissions(
11242 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11243 continue;
11244 }
11245
11246 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011247 }
11248 return results;
11249 }
11250
Cody Kesting7474f672021-05-11 14:22:40 -070011251 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11252 @NonNull NetworkAgentInfo nai) {
11253 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11254 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11255 }
11256
Cody Kesting160ef392021-05-05 13:17:22 -070011257 private boolean hasLocationPermission(String packageName, int uid) {
11258 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11259 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11260 // call in a try-catch.
11261 try {
11262 if (!mLocationPermissionChecker.checkLocationPermission(
11263 packageName, null /* featureId */, uid, null /* message */)) {
11264 return false;
11265 }
11266 } catch (SecurityException e) {
11267 return false;
11268 }
11269
11270 return true;
11271 }
11272
11273 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11274 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011275 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011276 && virtual.networkCapabilities.getOwnerUid() == uid
11277 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11278 return true;
11279 }
11280 }
11281
11282 return false;
11283 }
11284
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011285 @VisibleForTesting
11286 boolean checkConnectivityDiagnosticsPermissions(
11287 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
11288 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
11289 return true;
11290 }
11291
Cody Kesting160ef392021-05-05 13:17:22 -070011292 // Administrator UIDs also contains the Owner UID
11293 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11294 if (!CollectionUtils.contains(administratorUids, callbackUid)
11295 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011296 return false;
11297 }
11298
Cody Kesting7474f672021-05-11 14:22:40 -070011299 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11300 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011301 }
11302
Cody Kestingd199a9d2019-12-17 12:55:28 -080011303 @Override
11304 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011305 @NonNull IConnectivityDiagnosticsCallback callback,
11306 @NonNull NetworkRequest request,
11307 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011308 Objects.requireNonNull(callback, "callback must not be null");
11309 Objects.requireNonNull(request, "request must not be null");
11310 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11311
Cody Kesting73708bf2019-12-18 10:57:50 -080011312 if (request.legacyType != TYPE_NONE) {
11313 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11314 + " Please use NetworkCapabilities instead.");
11315 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011316 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011317 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011318
11319 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11320 // and administrator uids to be safe.
11321 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011322 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011323
11324 final NetworkRequest requestWithId =
11325 new NetworkRequest(
11326 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11327
11328 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11329 //
11330 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11331 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11332 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011333 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011334 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011335 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011336
11337 mConnectivityDiagnosticsHandler.sendMessage(
11338 mConnectivityDiagnosticsHandler.obtainMessage(
11339 ConnectivityDiagnosticsHandler
11340 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11341 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011342 }
11343
11344 @Override
11345 public void unregisterConnectivityDiagnosticsCallback(
11346 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011347 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011348 mConnectivityDiagnosticsHandler.sendMessage(
11349 mConnectivityDiagnosticsHandler.obtainMessage(
11350 ConnectivityDiagnosticsHandler
11351 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011352 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011353 0,
11354 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011355 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011356
Yan Yanfe96dde2022-12-05 23:00:01 +000011357 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11358 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11359 if (underlyingNetworks == null) return false;
11360
11361 for (Network network : underlyingNetworks) {
11362 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11363 return true;
11364 }
11365 }
11366 return false;
11367 }
11368
Cody Kestingf53a0752020-04-15 12:33:28 -070011369 @Override
11370 public void simulateDataStall(int detectionMethod, long timestampMillis,
11371 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011372 Objects.requireNonNull(network, "network must not be null");
11373 Objects.requireNonNull(extras, "extras must not be null");
11374
paulhu3ffffe72021-09-16 10:15:22 +080011375 enforceAnyPermissionOf(mContext,
11376 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011377 android.Manifest.permission.NETWORK_STACK);
11378 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011379 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11380 throw new SecurityException(
11381 "Data Stall simulation is only possible for test networks or networks built on"
11382 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011383 }
11384
11385 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011386 if (nai == null
11387 || (nai.creatorUid != mDeps.getCallingUid()
11388 && nai.creatorUid != Process.SYSTEM_UID)) {
11389 throw new SecurityException(
11390 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011391 }
11392
Cody Kesting652e3ec2020-05-21 12:08:21 -070011393 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11394 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11395 // Data Stall information as a DataStallReportParcelable and passing to
11396 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11397 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011398 final DataStallReportParcelable p = new DataStallReportParcelable();
11399 p.timestampMillis = timestampMillis;
11400 p.detectionMethod = detectionMethod;
11401
11402 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11403 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11404 }
11405 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11406 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11407 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11408 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11409 }
11410
Serik Beketayevec8ad212020-12-07 22:43:07 -080011411 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011412 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011413
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011414 /**
11415 * Class to hold the information for network activity change event from idle timers
11416 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
11417 */
11418 private static final class NetworkActivityParams {
11419 public final boolean isActive;
11420 // Label used for idle timer. Transport type is used as label.
11421 // label is int since NMS was using the identifier as int, and it has not been changed
11422 public final int label;
11423 public final long timestampNs;
11424 // Uid represents the uid that was responsible for waking the radio.
11425 // -1 for no uid and uid is -1 if isActive is false.
11426 public final int uid;
11427
11428 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
11429 this.isActive = isActive;
11430 this.label = label;
11431 this.timestampNs = timestampNs;
11432 this.uid = uid;
11433 }
11434 }
11435
lucaslin66f44212021-02-23 01:12:55 +080011436 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11437 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011438 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080011439 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011440 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
11441 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080011442 }
lucaslin37a16d92021-01-21 19:48:09 +080011443
11444 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011445 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011446 mHandler.post(() -> {
11447 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011448 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011449 }
11450 });
lucaslin37a16d92021-01-21 19:48:09 +080011451 }
11452
11453 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011454 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011455 mHandler.post(() -> {
11456 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011457 nai.clatd.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011458 }
11459 });
lucaslin66f44212021-02-23 01:12:55 +080011460 }
11461 }
11462
lucaslin1a8b4c62021-01-21 02:02:55 +080011463 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11464
11465 /**
11466 * Class used for updating network activity tracking with netd and notify network activity
11467 * changes.
11468 */
11469 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011470 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011471 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011472 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011473 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080011474 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11475 new RemoteCallbackList<>();
11476 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090011477 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011478 // If there is no default network, default network is considered active to keep the existing
11479 // behavior. Initial value is used until first connect to the default network.
11480 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011481 // Key is netId. Value is configured idle timer information.
11482 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080011483
Chalard Jean46bfbf02022-02-02 00:56:25 +090011484 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011485 public final int timeout;
11486 public final int transportType;
11487
11488 IdleTimerParams(int timeout, int transport) {
11489 this.timeout = timeout;
11490 this.transportType = transport;
11491 }
11492 }
11493
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011494 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011495 @NonNull Handler handler) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011496 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011497 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011498 mHandler = handler;
11499 }
11500
11501 private void ensureRunningOnConnectivityServiceThread() {
11502 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
11503 throw new IllegalStateException("Not running on ConnectivityService thread: "
11504 + Thread.currentThread().getName());
11505 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011506 }
11507
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011508 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011509 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011510 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011511 // This activity change is not for the current default network.
11512 // This can happen if netd callback post activity change event message but
11513 // the default network is lost before processing this message.
11514 return;
11515 }
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011516 sendDataActivityBroadcast(transportTypeToLegacyType(activityParams.label),
11517 activityParams.isActive, activityParams.timestampNs);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011518 mIsDefaultNetworkActive = activityParams.isActive;
11519 if (mIsDefaultNetworkActive) {
11520 reportNetworkActive();
lucaslin66f44212021-02-23 01:12:55 +080011521 }
11522 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011523
lucaslin1193a5d2021-01-21 02:04:15 +080011524 private void reportNetworkActive() {
11525 final int length = mNetworkActivityListeners.beginBroadcast();
11526 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
11527 try {
11528 for (int i = 0; i < length; i++) {
11529 try {
11530 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
11531 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011532 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080011533 }
11534 }
11535 } finally {
11536 mNetworkActivityListeners.finishBroadcast();
11537 }
11538 }
11539
lucaslin1a8b4c62021-01-21 02:02:55 +080011540 // This is deprecated and only to support legacy use cases.
11541 private int transportTypeToLegacyType(int type) {
11542 switch (type) {
11543 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011544 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080011545 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011546 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080011547 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011548 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080011549 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011550 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080011551 default:
11552 loge("Unexpected transport in transportTypeToLegacyType: " + type);
11553 }
11554 return ConnectivityManager.TYPE_NONE;
11555 }
11556
11557 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
11558 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
11559 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
11560 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
11561 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
11562 final long ident = Binder.clearCallingIdentity();
11563 try {
11564 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
11565 RECEIVE_DATA_ACTIVITY_CHANGE,
11566 null /* resultReceiver */,
11567 null /* scheduler */,
11568 0 /* initialCode */,
11569 null /* initialData */,
11570 null /* initialExtra */);
11571 } finally {
11572 Binder.restoreCallingIdentity(ident);
11573 }
11574 }
11575
11576 /**
11577 * Setup data activity tracking for the given network.
11578 *
11579 * Every {@code setupDataActivityTracking} should be paired with a
11580 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090011581 *
11582 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080011583 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090011584 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011585 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011586 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080011587
11588 final int timeout;
11589 final int type;
11590
11591 if (networkAgent.networkCapabilities.hasTransport(
11592 NetworkCapabilities.TRANSPORT_CELLULAR)) {
11593 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011594 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080011595 10);
11596 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11597 } else if (networkAgent.networkCapabilities.hasTransport(
11598 NetworkCapabilities.TRANSPORT_WIFI)) {
11599 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011600 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080011601 15);
11602 type = NetworkCapabilities.TRANSPORT_WIFI;
11603 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011604 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080011605 }
11606
lucaslinb961efc2021-01-21 02:03:17 +080011607 updateRadioPowerState(true /* isActive */, type);
11608
lucaslin1a8b4c62021-01-21 02:02:55 +080011609 if (timeout > 0 && iface != null) {
11610 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011611 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, type));
Motomu Utsumic298cf02023-05-31 12:06:12 +090011612 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
Motomu Utsumi6225d572023-05-29 15:08:57 +090011613 return true;
lucaslin1a8b4c62021-01-21 02:02:55 +080011614 } catch (Exception e) {
11615 // You shall not crash!
11616 loge("Exception in setupDataActivityTracking " + e);
11617 }
11618 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011619 return false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011620 }
11621
11622 /**
11623 * Remove data activity tracking when network disconnects.
11624 */
11625 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
11626 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011627 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080011628 final NetworkCapabilities caps = networkAgent.networkCapabilities;
11629
lucaslinb961efc2021-01-21 02:03:17 +080011630 if (iface == null) return;
11631
11632 final int type;
11633 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
11634 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11635 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
11636 type = NetworkCapabilities.TRANSPORT_WIFI;
11637 } else {
11638 return; // do not track any other networks
11639 }
11640
11641 try {
11642 updateRadioPowerState(false /* isActive */, type);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011643 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011644 if (params == null) {
11645 // IdleTimer is not added if the configured timeout is 0 or negative value
11646 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080011647 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011648 mActiveIdleTimers.remove(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011649 // The call fails silently if no idle timer setup for this interface
11650 mNetd.idletimerRemoveInterface(iface, params.timeout,
11651 Integer.toString(params.transportType));
lucaslinb961efc2021-01-21 02:03:17 +080011652 } catch (Exception e) {
11653 // You shall not crash!
11654 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080011655 }
11656 }
11657
Motomu Utsumi6225d572023-05-29 15:08:57 +090011658 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
11659 boolean hasIdleTimer) {
11660 if (defaultNetwork != null) {
11661 mIsDefaultNetworkActive = true;
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011662 // Callbacks are called only when the network has the idle timer.
11663 if (hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011664 reportNetworkActive();
11665 }
11666 } else {
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011667 // If there is no default network, default network is considered active to keep the
11668 // existing behavior.
11669 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090011670 }
11671 }
11672
lucaslin1a8b4c62021-01-21 02:02:55 +080011673 /**
11674 * Update data activity tracking when network state is updated.
11675 */
11676 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
11677 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011678 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi6225d572023-05-29 15:08:57 +090011679 boolean hasIdleTimer = false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011680 if (newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011681 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080011682 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011683 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
lucaslin1a8b4c62021-01-21 02:02:55 +080011684 if (oldNetwork != null) {
11685 removeDataActivityTracking(oldNetwork);
11686 }
11687 }
lucaslinb961efc2021-01-21 02:03:17 +080011688
11689 private void updateRadioPowerState(boolean isActive, int transportType) {
11690 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
11691 switch (transportType) {
11692 case NetworkCapabilities.TRANSPORT_CELLULAR:
11693 bs.reportMobileRadioPowerState(isActive, NO_UID);
11694 break;
11695 case NetworkCapabilities.TRANSPORT_WIFI:
11696 bs.reportWifiRadioPowerState(isActive, NO_UID);
11697 break;
11698 default:
11699 logw("Untracked transport type:" + transportType);
11700 }
11701 }
lucaslin1193a5d2021-01-21 02:04:15 +080011702
11703 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011704 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080011705 }
11706
11707 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
11708 mNetworkActivityListeners.register(l);
11709 }
11710
11711 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
11712 mNetworkActivityListeners.unregister(l);
11713 }
lucaslin012f7a12021-01-21 02:04:35 +080011714
11715 public void dump(IndentingPrintWriter pw) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011716 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
11717 pw.println("Idle timers:");
11718 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011719 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
11720 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
11721 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080011722 pw.print(" timeout="); pw.print(params.timeout);
11723 pw.print(" type="); pw.println(params.transportType);
11724 }
Motomu Utsumic298cf02023-05-31 12:06:12 +090011725 } catch (Exception e) {
11726 // mActiveIdleTimers should only be accessed from handler thread, except dump().
11727 // As dump() is never called in normal usage, it would be needlessly expensive
11728 // to lock the collection only for its benefit.
11729 // Also, mActiveIdleTimers is not expected to be updated frequently.
11730 // So catching the exception and logging.
11731 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080011732 }
11733 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011734 }
James Mattis47db0582021-01-01 14:13:35 -080011735
Daniel Brightf9e945b2020-06-15 16:10:01 -070011736 /**
11737 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
11738 *
11739 * @param socketInfo the socket information
11740 * @param callback the callback to register
11741 */
11742 @Override
11743 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
11744 @NonNull final IQosCallback callback) {
11745 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
11746 if (nai == null || nai.networkCapabilities == null) {
11747 try {
11748 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
11749 } catch (final RemoteException ex) {
11750 loge("registerQosCallbackInternal: RemoteException", ex);
11751 }
11752 return;
11753 }
11754 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
11755 }
11756
11757 /**
11758 * Register a {@link IQosCallback} with base {@link QosFilter}.
11759 *
11760 * @param filter the filter to register
11761 * @param callback the callback to register
11762 * @param nai the agent information related to the filter's network
11763 */
11764 @VisibleForTesting
11765 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
11766 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011767 Objects.requireNonNull(filter, "filter must be non-null");
11768 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011769
11770 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080011771 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
11772 // on this network is unregistered when the app loses permission or b) no QoS
11773 // callbacks are sent for restricted networks unless the app currently has permission
11774 // to access restricted networks.
11775 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070011776 }
11777 mQosCallbackTracker.registerCallback(callback, filter, nai);
11778 }
11779
11780 /**
11781 * Unregisters the given callback.
11782 *
11783 * @param callback the callback to unregister
11784 */
11785 @Override
11786 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011787 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011788 mQosCallbackTracker.unregisterCallback(callback);
11789 }
James Mattis47db0582021-01-01 14:13:35 -080011790
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011791 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
11792 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
11793 // Enterprise device can be fully managed like device owner and such use case
11794 // also should be supported. Calling app check for work profile and fully managed device
11795 // is already done in DevicePolicyManager.
11796 // This check is an extra caution to be sure device is fully managed or not.
11797 final UserManager um = mContext.getSystemService(UserManager.class);
11798 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
11799 if (um.isManagedProfile(profile.getIdentifier())) {
11800 return true;
11801 }
Chalard Jeandf29a852023-05-29 17:02:43 +090011802 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011803 return false;
11804 }
11805
James Mattis45d81842021-01-10 14:24:24 -080011806 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011807 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011808 *
11809 * See the documentation for the individual preferences for a description of the supported
11810 * behaviors.
11811 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011812 * @param profile If the device owner is set, any profile is allowed.
11813 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011814 * @param preferences the list of profile network preferences for the
11815 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011816 * @param listener an optional listener to listen for completion of the operation.
11817 */
11818 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011819 public void setProfileNetworkPreferences(
11820 @NonNull final UserHandle profile,
11821 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090011822 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011823 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011824 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011825
11826 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011827 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11828 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11829 .build();
11830 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011831 }
11832
paulhu3ffffe72021-09-16 10:15:22 +080011833 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011834 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011835 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011836 }
11837 if (profile.getIdentifier() < 0) {
11838 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11839 + "UserHandle.CURRENT not supported)");
11840 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011841 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11842 throw new IllegalArgumentException("Profile must be a managed profile "
11843 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011844 }
paulhuaa0743d2021-05-26 21:56:03 +080011845
Chalard Jean0606fc82022-12-14 20:34:43 +090011846 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011847 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011848 for (final ProfileNetworkPreference preference : preferences) {
11849 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011850 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011851 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011852 switch (preference.getPreference()) {
11853 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11854 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011855 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011856 if (preference.getPreferenceEnterpriseId() != 0) {
11857 throw new IllegalArgumentException(
11858 "Invalid enterprise identifier in setProfileNetworkPreferences");
11859 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011860 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011861 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11862 blockingNonEnterprise = true;
11863 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011864 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11865 allowFallback = false;
11866 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011867 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011868 // This code is needed even though there is a check later on,
11869 // because isRangeAlreadyInPreferenceList assumes that every preference
11870 // has a UID list.
11871 if (hasDefaultPreference) {
11872 throw new IllegalArgumentException(
11873 "Default profile preference should not be set along with other "
11874 + "preference");
11875 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011876 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11877 throw new IllegalArgumentException(
11878 "Invalid enterprise identifier in setProfileNetworkPreferences");
11879 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011880 final Set<UidRange> uidRangeSet =
11881 getUidListToBeAppliedForNetworkPreference(profile, preference);
11882 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11883 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11884 } else {
11885 throw new IllegalArgumentException(
11886 "Overlapping uid range in setProfileNetworkPreferences");
11887 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011888 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011889 nc.addEnterpriseId(
11890 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011891 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11892 break;
11893 default:
11894 throw new IllegalArgumentException(
11895 "Invalid preference in setProfileNetworkPreferences");
11896 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011897 preferenceList.add(new ProfileNetworkPreferenceInfo(
11898 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011899 if (hasDefaultPreference && preferenceList.size() > 1) {
11900 throw new IllegalArgumentException(
11901 "Default profile preference should not be set along with other preference");
11902 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011903 }
11904 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011905 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011906 }
11907
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011908 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
11909 @NonNull final UserHandle profile,
11910 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
11911 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080011912 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
11913 profileNetworkPreference.getIncludedUids());
11914
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011915 if (uidRangeSet.size() > 0) {
11916 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
11917 throw new IllegalArgumentException(
11918 "Allow uid range is outside the uid range of profile.");
11919 }
11920 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080011921 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011922 profileNetworkPreference.getExcludedUids());
11923 if (disallowUidRangeSet.size() > 0) {
11924 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
11925 throw new IllegalArgumentException(
11926 "disallow uid range is outside the uid range of profile.");
11927 }
11928 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
11929 disallowUidRangeSet);
11930 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011931 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011932 uidRangeSet.add(profileUids);
11933 }
11934 }
11935 return uidRangeSet;
11936 }
11937
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011938 private boolean isEnterpriseIdentifierValid(
11939 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011940 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011941 return true;
11942 }
11943 return false;
11944 }
11945
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011946 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090011947 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011948 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090011949 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011950 // The NRI for a user should contain the request for capabilities.
11951 // If fallback to default network is needed then NRI should include
11952 // the request for the default network. Create an image of it to
11953 // have the correct UIDs in it (also a request can only be part of one NRI, because
11954 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011955 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
11956 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011957 if (pref.allowFallback) {
11958 nrs.add(createDefaultInternetRequestForTransport(
11959 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11960 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011961 if (VDBG) {
11962 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
11963 pref.capabilities.getUids()));
11964 }
11965
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011966 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080011967 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080011968 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011969 result.add(nri);
11970 }
11971 return result;
11972 }
11973
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011974 /**
11975 * Compare if the given UID range sets have the same UIDs.
11976 *
11977 */
11978 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090011979 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011980 @NonNull Set<UidRange> uidRangeSet) {
11981 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
11982 return false;
11983 }
Chalard Jean0606fc82022-12-14 20:34:43 +090011984 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011985 if (UidRangeUtils.doesRangeSetOverlap(
11986 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
11987 return true;
11988 }
11989 }
11990 return false;
11991 }
11992
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011993 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090011994 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011995 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011996 /*
11997 * handleSetProfileNetworkPreference is always called for single user.
11998 * preferenceList only contains preferences for different uids within the same user
11999 * (enforced by getUidListToBeAppliedForNetworkPreference).
12000 * Clear all the existing preferences for the user before applying new preferences.
12001 *
12002 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012003 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12004 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012005 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12006 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012007
paulhu74128522021-09-28 02:29:03 +000012008 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12009 addPerAppDefaultNetworkRequests(
12010 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012011 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012012
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012013 // Finally, rematch.
12014 rematchAllNetworksAndRequests();
12015
12016 if (null != listener) {
12017 try {
12018 listener.onComplete();
12019 } catch (RemoteException e) {
12020 loge("Listener for setProfileNetworkPreference has died");
12021 }
12022 }
12023 }
12024
paulhu51f77dc2021-06-07 02:34:20 +000012025 @VisibleForTesting
12026 @NonNull
12027 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12028 @NonNull final Set<Integer> uids) {
12029 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12030 if (uids.size() == 0) {
12031 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12032 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
12033 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
12034 return nris;
12035 }
12036
12037 final List<NetworkRequest> requests = new ArrayList<>();
12038 // The NRI should be comprised of two layers:
12039 // - The request for the mobile network preferred.
12040 // - The request for the default network, for fallback.
12041 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012042 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012043 requests.add(createDefaultInternetRequestForTransport(
12044 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12045 final Set<UidRange> ranges = new ArraySet<>();
12046 for (final int uid : uids) {
12047 ranges.add(new UidRange(uid, uid));
12048 }
12049 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080012050 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080012051 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000012052 return nris;
12053 }
12054
12055 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012056 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012057 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12058 addPerAppDefaultNetworkRequests(
12059 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012060 // Finally, rematch.
12061 rematchAllNetworksAndRequests();
12062 }
12063
Patrick Rohr2857ac42022-01-21 14:58:16 +010012064 private void handleIngressRateLimitChanged() {
12065 final long oldIngressRateLimit = mIngressRateLimit;
12066 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12067 mContext);
12068 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12069 if (canNetworkBeRateLimited(networkAgent)) {
12070 // If rate limit has previously been enabled, remove the old limit first.
12071 if (oldIngressRateLimit >= 0) {
12072 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12073 }
12074 if (mIngressRateLimit >= 0) {
12075 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12076 mIngressRateLimit);
12077 }
12078 }
12079 }
12080 }
12081
12082 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012083 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090012084 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012085
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012086 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12087 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12088 // internet connectivity can be rate limited.
12089 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12090 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012091 return false;
12092 }
12093
12094 final String iface = networkAgent.linkProperties.getInterfaceName();
12095 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012096 // This may happen in tests, but if there is no interface then there is nothing that
12097 // can be rate limited.
12098 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012099 return false;
12100 }
12101 return true;
12102 }
12103
James Mattis45d81842021-01-10 14:24:24 -080012104 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012105 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12106 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012107 }
12108
12109 /**
12110 * Used by automotive devices to set the network preferences used to direct traffic at an
12111 * application level as per the given OemNetworkPreferences. An example use-case would be an
12112 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12113 * vehicle via a particular network.
12114 *
12115 * Calling this will overwrite the existing preference.
12116 *
James Mattisda32cfe2021-01-26 16:23:52 -080012117 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012118 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012119 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012120 */
James Mattis47db0582021-01-01 14:13:35 -080012121 @Override
James Mattis45d81842021-01-10 14:24:24 -080012122 public void setOemNetworkPreference(
12123 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012124 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012125
James Mattisfa270db2021-05-31 17:11:10 -070012126 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12127 // Only bypass the permission/device checks if this is a valid test request.
12128 if (isValidTestOemNetworkPreference(preference)) {
12129 enforceManageTestNetworksPermission();
12130 } else {
12131 enforceAutomotiveDevice();
12132 enforceOemNetworkPreferencesPermission();
12133 validateOemNetworkPreferences(preference);
12134 }
James Mattis45d81842021-01-10 14:24:24 -080012135
James Mattis45d81842021-01-10 14:24:24 -080012136 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12137 new Pair<>(preference, listener)));
12138 }
12139
James Mattisfa270db2021-05-31 17:11:10 -070012140 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012141 * Sets the specified UIDs to get/receive the VPN as the only default network.
12142 *
12143 * Calling this will overwrite the existing network preference for this session, and the
12144 * specified UIDs won't get any default network when no VPN is connected.
12145 *
12146 * @param session The VPN session which manages the passed UIDs.
12147 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12148 * setting for this session if the array is empty. Null is not allowed, the
12149 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12150 * @hide
12151 */
12152 @Override
12153 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12154 Objects.requireNonNull(ranges);
12155 enforceNetworkStackOrSettingsPermission();
12156 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12157 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12158 throw new IllegalArgumentException(
12159 "setVpnNetworkPreference: Passed UID ranges overlap");
12160 }
12161
12162 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12163 new VpnNetworkPreferenceInfo(session,
12164 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12165 }
12166
12167 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12168 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12169
12170 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12171 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12172
12173 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12174 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12175 // Finally, rematch.
12176 rematchAllNetworksAndRequests();
12177 }
12178
12179 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12180 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12181 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12182 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
12183 final List<NetworkRequest> requests = new ArrayList<>();
12184 // Request VPN only, so other networks won't be the fallback options when VPN is not
12185 // connected temporarily.
12186 requests.add(createVpnRequest());
12187 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
12188 setNetworkRequestUids(requests, uidRanges);
12189 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
12190 }
12191 return nris;
12192 }
12193
12194 /**
James Mattisfa270db2021-05-31 17:11:10 -070012195 * Check the validity of an OEM network preference to be used for testing purposes.
12196 * @param preference the preference to validate
12197 * @return true if this is a valid OEM network preference test request.
12198 */
12199 private boolean isValidTestOemNetworkPreference(
12200 @NonNull final OemNetworkPreferences preference) {
12201 // Allow for clearing of an existing OemNetworkPreference used for testing.
12202 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
12203 // changes after this check is complete. This is an unlikely scenario as calling of this API
12204 // is controlled by the OEM therefore the added complexity is not worth adding given those
12205 // circumstances. That said, it is an edge case to be aware of hence this comment.
12206 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
12207 && isTestOemNetworkPreference(mOemNetworkPreferences);
12208 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
12209 }
12210
12211 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
12212 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
12213 return prefMap.size() == 1
12214 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
12215 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
12216 }
12217
James Mattis45d81842021-01-10 14:24:24 -080012218 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
12219 for (@OemNetworkPreferences.OemNetworkPreference final int pref
12220 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070012221 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
12222 throw new IllegalArgumentException(
12223 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
12224 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080012225 }
12226 }
12227 }
12228
12229 private void handleSetOemNetworkPreference(
12230 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012231 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080012232 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12233 if (DBG) {
12234 log("set OEM network preferences :" + preference.toString());
12235 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012236
James Mattiscb1e0362021-04-06 17:07:42 -070012237 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012238 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12239 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12240 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012241 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012242
12243 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012244 try {
12245 listener.onComplete();
12246 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012247 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012248 }
James Mattis45d81842021-01-10 14:24:24 -080012249 }
12250 }
12251
paulhu74128522021-09-28 02:29:03 +000012252 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012253 // Skip the requests which are set by other network preference. Because the uid range rules
12254 // should stay in netd.
12255 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012256 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012257 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012258 }
12259
James Mattis3ce3d3c2021-02-09 18:18:28 -080012260 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12261 ensureRunningOnConnectivityServiceThread();
12262 mDefaultNetworkRequests.addAll(nris);
12263 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12264 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012265 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012266 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12267 nrisToRegister.addAll(
12268 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12269 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012270 }
12271
12272 /**
12273 * All current requests that are tracking the default network need to be assessed as to whether
12274 * or not the current set of per-application default requests will be changing their default
12275 * network. If so, those requests will need to be updated so that they will send callbacks for
12276 * default network changes at the appropriate time. Additionally, those requests tracking the
12277 * default that were previously updated by this flow will need to be reassessed.
12278 * @return the nris which will need to be updated.
12279 */
12280 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12281 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12282 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12283 // same nri in the map's values for each of its NetworkRequest objects.
12284 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012285 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012286 // Include this nri if it is currently being tracked.
12287 if (isPerAppTrackedNri(nri)) {
12288 defaultCallbackRequests.add(nri);
12289 continue;
12290 }
12291 // We only track callbacks for requests tracking the default.
12292 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12293 continue;
12294 }
12295 // Include this nri if it will be tracked by the new per-app default requests.
12296 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012297 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012298 if (isNriGoingToBeTracked) {
12299 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012300 }
12301 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012302 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012303 }
12304
James Mattis3ce3d3c2021-02-09 18:18:28 -080012305 /**
12306 * Create nris for those network requests that are currently tracking the default network that
12307 * are being controlled by a per-application default.
12308 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12309 * foundation when creating the nri. Important items include the calling uid's original
12310 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12311 * requests are assumed to have already been validated as needing to be updated.
12312 * @return the Set of nris to use when registering network requests.
12313 */
12314 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12315 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12316 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12317 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12318 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012319 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012320
Chalard Jean9473c982021-07-29 20:03:04 +090012321 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012322 if (trackingNri == mDefaultRequest) {
12323 callbackRequestsToRegister.add(new NetworkRequestInfo(
12324 callbackRequest,
12325 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12326 continue;
12327 }
12328
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012329 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012330 callbackRequestsToRegister.add(new NetworkRequestInfo(
12331 callbackRequest,
12332 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012333 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012334 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012335 }
12336 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012337 }
12338
Chalard Jean17215832021-03-01 14:06:28 +090012339 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12340 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012341 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012342 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012343 }
12344 }
12345
James Mattis45d81842021-01-10 14:24:24 -080012346 /**
12347 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12348 */
12349 @VisibleForTesting
12350 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012351 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080012352 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012353 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080012354 final SparseArray<Set<Integer>> uids =
12355 createUidsFromOemNetworkPreferences(preference);
12356 for (int i = 0; i < uids.size(); i++) {
12357 final int key = uids.keyAt(i);
12358 final Set<Integer> value = uids.valueAt(i);
12359 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
12360 // No need to add an nri without any requests.
12361 if (0 == nri.mRequests.size()) {
12362 continue;
12363 }
12364 nris.add(nri);
12365 }
12366
12367 return nris;
12368 }
12369
12370 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
12371 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070012372 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080012373 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080012374 final List<UserHandle> users =
12375 mContext.getSystemService(UserManager.class).getUserHandles(true);
12376 if (null == users || users.size() == 0) {
12377 if (VDBG || DDBG) {
12378 log("No users currently available for setting the OEM network preference.");
12379 }
James Mattisb6b6a432021-06-01 22:30:36 -070012380 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080012381 }
James Mattis45d81842021-01-10 14:24:24 -080012382 for (final Map.Entry<String, Integer> entry :
12383 preference.getNetworkPreferences().entrySet()) {
12384 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070012385 // Add the rules for all users as this policy is device wide.
12386 for (final UserHandle user : users) {
12387 try {
12388 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
12389 if (!prefToUids.contains(pref)) {
12390 prefToUids.put(pref, new ArraySet<>());
12391 }
12392 prefToUids.get(pref).add(uid);
12393 } catch (PackageManager.NameNotFoundException e) {
12394 // Although this may seem like an error scenario, it is ok that uninstalled
12395 // packages are sent on a network preference as the system will watch for
12396 // package installations associated with this network preference and update
12397 // accordingly. This is done to minimize race conditions on app install.
12398 continue;
James Mattis45d81842021-01-10 14:24:24 -080012399 }
James Mattis45d81842021-01-10 14:24:24 -080012400 }
12401 }
James Mattisb6b6a432021-06-01 22:30:36 -070012402 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080012403 }
12404
12405 private NetworkRequestInfo createNriFromOemNetworkPreferences(
12406 @OemNetworkPreferences.OemNetworkPreference final int preference,
12407 @NonNull final Set<Integer> uids) {
12408 final List<NetworkRequest> requests = new ArrayList<>();
12409 // Requests will ultimately be evaluated by order of insertion therefore it matters.
12410 switch (preference) {
12411 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
12412 requests.add(createUnmeteredNetworkRequest());
12413 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070012414 requests.add(createDefaultInternetRequestForTransport(
12415 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080012416 break;
12417 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
12418 requests.add(createUnmeteredNetworkRequest());
12419 requests.add(createOemPaidNetworkRequest());
12420 break;
12421 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
12422 requests.add(createOemPaidNetworkRequest());
12423 break;
12424 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
12425 requests.add(createOemPrivateNetworkRequest());
12426 break;
James Mattisfa270db2021-05-31 17:11:10 -070012427 case OEM_NETWORK_PREFERENCE_TEST:
12428 requests.add(createUnmeteredNetworkRequest());
12429 requests.add(createTestNetworkRequest());
12430 requests.add(createDefaultRequest());
12431 break;
12432 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
12433 requests.add(createTestNetworkRequest());
12434 break;
James Mattis45d81842021-01-10 14:24:24 -080012435 default:
12436 // This should never happen.
12437 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
12438 + " called with invalid preference of " + preference);
12439 }
12440
James Mattisfa270db2021-05-31 17:11:10 -070012441 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090012442 for (final int uid : uids) {
12443 ranges.add(new UidRange(uid, uid));
12444 }
12445 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080012446 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080012447 }
12448
12449 private NetworkRequest createUnmeteredNetworkRequest() {
12450 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12451 .addCapability(NET_CAPABILITY_NOT_METERED)
12452 .addCapability(NET_CAPABILITY_VALIDATED);
12453 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
12454 }
12455
12456 private NetworkRequest createOemPaidNetworkRequest() {
12457 // NET_CAPABILITY_OEM_PAID is a restricted capability.
12458 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12459 .addCapability(NET_CAPABILITY_OEM_PAID)
12460 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12461 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12462 }
12463
12464 private NetworkRequest createOemPrivateNetworkRequest() {
12465 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
12466 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12467 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
12468 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12469 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12470 }
12471
12472 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070012473 final NetworkCapabilities netcap = new NetworkCapabilities();
12474 netcap.addCapability(NET_CAPABILITY_INTERNET);
12475 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
12476 return netcap;
12477 }
12478
12479 private NetworkRequest createTestNetworkRequest() {
12480 final NetworkCapabilities netcap = new NetworkCapabilities();
12481 netcap.clearAll();
12482 netcap.addTransportType(TRANSPORT_TEST);
12483 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080012484 }
James Mattis47db0582021-01-01 14:13:35 -080012485 }
markchien738ad912021-12-09 18:15:45 +080012486
12487 @Override
12488 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
12489 enforceNetworkStackOrSettingsPermission();
12490
12491 try {
12492 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012493 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012494 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012495 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012496 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012497 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012498 throw new IllegalStateException(e);
12499 }
12500 }
12501
12502 @Override
12503 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
12504 enforceNetworkStackOrSettingsPermission();
12505
12506 try {
12507 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012508 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012509 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012510 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012511 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012512 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012513 throw new IllegalStateException(e);
12514 }
12515 }
markchiene1561fa2021-12-09 22:00:56 +080012516
Chalard Jeanc8fefb32023-09-05 21:41:13 +090012517 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
12518 throws PackageManager.NameNotFoundException {
12519 final PackageManager pm = mContext.getPackageManager();
12520 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
12521 if (appId < Process.FIRST_APPLICATION_UID) {
12522 throw new RuntimeException("Can't set package firewall rule for system app "
12523 + packageName + " with appId " + appId);
12524 }
12525 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
12526 final int uid = uh.getUid(appId);
12527 setUidFirewallRule(chain, uid, rule);
12528 }
12529 return appId;
12530 }
12531
markchiene1561fa2021-12-09 22:00:56 +080012532 @Override
markchien3c04e662022-03-22 16:29:56 +080012533 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080012534 enforceNetworkStackOrSettingsPermission();
12535
markchien3c04e662022-03-22 16:29:56 +080012536 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
12537 int firewallRule = getFirewallRuleType(chain, rule);
12538
12539 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
12540 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
12541 }
12542
markchiene1561fa2021-12-09 22:00:56 +080012543 try {
markchien3c04e662022-03-22 16:29:56 +080012544 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012545 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080012546 throw new IllegalStateException(e);
12547 }
12548 }
markchien98a6f952022-01-13 23:43:53 +080012549
Chalard Jeanc8fefb32023-09-05 21:41:13 +090012550 private int getPackageFirewallRule(final int chain, final String packageName)
12551 throws PackageManager.NameNotFoundException {
12552 final PackageManager pm = mContext.getPackageManager();
12553 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
12554 return getUidFirewallRule(chain, appId);
12555 }
12556
Motomu Utsumi900b8062023-01-19 16:16:49 +090012557 @Override
12558 public int getUidFirewallRule(final int chain, final int uid) {
12559 enforceNetworkStackOrSettingsPermission();
12560 return mBpfNetMaps.getUidRule(chain, uid);
12561 }
12562
markchien3c04e662022-03-22 16:29:56 +080012563 private int getFirewallRuleType(int chain, int rule) {
12564 final int defaultRule;
12565 switch (chain) {
12566 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000012567 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
12568 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000012569 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080012570 defaultRule = FIREWALL_RULE_ALLOW;
12571 break;
12572 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
12573 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
12574 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
12575 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
12576 defaultRule = FIREWALL_RULE_DENY;
12577 break;
12578 default:
12579 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
12580 }
12581 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
12582
12583 return rule;
12584 }
12585
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012586 private void closeSocketsForFirewallChainLocked(final int chain)
12587 throws ErrnoException, SocketException, InterruptedIOException {
12588 if (mBpfNetMaps.isFirewallAllowList(chain)) {
12589 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
12590 // So, close all non-system socket owned by uids that are not explicitly allowed
12591 Set<Range<Integer>> ranges = new ArraySet<>();
12592 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
12593 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
12594 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
12595 } else {
12596 // Denylist means the firewall allows all by default, uids must be explicitly denied
12597 // So, close socket owned by uids that are explicitly denied
12598 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
12599 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
12600 }
12601 }
12602
markchien98a6f952022-01-13 23:43:53 +080012603 @Override
12604 public void setFirewallChainEnabled(final int chain, final boolean enable) {
12605 enforceNetworkStackOrSettingsPermission();
12606
12607 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012608 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012609 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080012610 throw new IllegalStateException(e);
12611 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012612
Chalard Jeandf29a852023-05-29 17:02:43 +090012613 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012614 try {
12615 closeSocketsForFirewallChainLocked(chain);
12616 } catch (ErrnoException | SocketException | InterruptedIOException e) {
12617 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
12618 }
12619 }
markchien98a6f952022-01-13 23:43:53 +080012620 }
12621
markchien00a0bed2022-01-13 23:46:13 +080012622 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012623 public boolean getFirewallChainEnabled(final int chain) {
12624 enforceNetworkStackOrSettingsPermission();
12625
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000012626 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012627 }
12628
12629 @Override
markchien00a0bed2022-01-13 23:46:13 +080012630 public void replaceFirewallChain(final int chain, final int[] uids) {
12631 enforceNetworkStackOrSettingsPermission();
12632
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000012633 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080012634 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080012635
12636 @Override
12637 public IBinder getCompanionDeviceManagerProxyService() {
12638 enforceNetworkStackPermission(mContext);
12639 return mCdmps;
12640 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070012641}