blob: 3a4d055a69b54f3415335d4c14f0f4324715e0b4 [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;
Jeff Sharkey07e19362017-10-27 17:22:59 -0600100
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;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +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;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800113import android.annotation.TargetApi;
Mark Fasheh7c999d82023-05-04 20:23:11 +0000114import android.app.ActivityManager;
115import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800116import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800117import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700118import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700119import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900120import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800121import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700122import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800123import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800124import android.content.ContentResolver;
125import android.content.Context;
126import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700127import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800128import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900129import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700130import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900131import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900132import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700133import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800134import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800135import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800136import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900137import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800138import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900139import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800140import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900141import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800142import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700143import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900144import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800145import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800146import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800147import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800148import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800149import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900150import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900151import android.net.INetworkMonitor;
152import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900153import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900154import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700155import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800156import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900157import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900158import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900159import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800160import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100161import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800162import android.net.NativeNetworkConfig;
163import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800164import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700165import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700166import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900167import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700168import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800169import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700170import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900171import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900172import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000173import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900174import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700175import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900176import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700177import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900178import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700179import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800180import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900181import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700182import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000183import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800184import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900185import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800186import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400187import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700188import android.net.QosCallbackException;
189import android.net.QosFilter;
190import android.net.QosSocketFilter;
191import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700192import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800193import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800194import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800195import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900196import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400197import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800198import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800199import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400200import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800201import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900202import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900203import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900204import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900205import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800206import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900207import android.net.networkstack.ModuleNetworkStackClient;
208import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900209import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800210import android.net.resolv.aidl.DnsHealthEventParcel;
211import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
212import android.net.resolv.aidl.Nat64PrefixEventParcel;
213import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900214import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900215import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800216import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800217import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800218import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700219import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000220import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800221import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700222import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700223import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800224import android.os.Looper;
225import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700226import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700227import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900228import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800229import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700230import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700231import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800232import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700233import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900234import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900235import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700236import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700237import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400238import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800239import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900240import android.stats.connectivity.MeteredState;
241import android.stats.connectivity.RequestType;
242import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900243import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700244import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700245import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700246import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800247import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900248import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000249import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600250import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900251import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900252import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700253import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700254import android.util.SparseIntArray;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900255import android.util.StatsEvent;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800256
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800257import androidx.annotation.RequiresApi;
258
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900259import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400260import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400261import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700262import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900263import com.android.internal.util.MessageUtils;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900264import com.android.metrics.ConnectionDurationForTransports;
265import com.android.metrics.ConnectionDurationPerTransports;
266import com.android.metrics.ConnectivitySampleMetricsHelper;
267import com.android.metrics.ConnectivityStateSample;
268import com.android.metrics.NetworkCountForTransports;
269import com.android.metrics.NetworkCountPerTransports;
270import com.android.metrics.NetworkDescription;
271import com.android.metrics.NetworkList;
272import com.android.metrics.NetworkRequestCount;
273import com.android.metrics.RequestCountForType;
Chiachang Wang62740142020-11-02 16:51:24 +0800274import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900275import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800276import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000277import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900278import com.android.net.module.util.BitUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900279import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900280import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100281import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900282import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
283import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900284import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800285import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800286import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100287import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000288import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800289import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
290import com.android.networkstack.apishim.ConstantsShim;
291import com.android.networkstack.apishim.common.BroadcastOptionsShim;
292import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900293import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900294import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000295import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900296import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800297import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800298import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900299import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900300import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900301import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500302import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700303import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900304import com.android.server.connectivity.FullScore;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900305import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900306import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000307import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100308import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700309import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900310import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700311import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600312import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900313import com.android.server.connectivity.NetworkNotificationManager;
314import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900315import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900316import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900317import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700318import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900319import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900320import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700321import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800322import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000323import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800324import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600325
Josh Gao461a1222020-06-16 15:58:11 -0700326import libcore.io.IoUtils;
327
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900328import org.xmlpull.v1.XmlPullParserException;
329
The Android Open Source Project28527d22009-03-03 19:31:44 -0800330import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100331import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900332import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800333import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900334import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700335import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700336import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900337import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900338import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700339import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700340import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700341import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700342import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800343import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900344import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800345import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700346import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700347import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700348import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700349import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900350import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700351import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900352import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600353import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900354import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600355import java.util.TreeSet;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900356import java.util.concurrent.TimeUnit;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900357import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800358
359/**
360 * @hide
361 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800362public class ConnectivityService extends IConnectivityManager.Stub
363 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900364 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800365
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900366 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900367 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900368 private static final String NETWORK_ARG = "networks";
369 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800370 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900371
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900372 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900373 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
374 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800375
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900376 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700377
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100378 /**
379 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
380 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800381 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100382 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
383 * (preferably via runtime resource overlays).
384 */
385 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
386 "http://connectivitycheck.gstatic.com/generate_204";
387
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700388 // TODO: create better separation between radio types and network types
389
Robert Greenwalt2034b912009-08-12 16:08:25 -0700390 // how long to wait before switching back to a radio's default network
391 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
392 // system property that can override the above value
393 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
394 "android.telephony.apn-restore";
395
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900396 // How long to wait before putting up a "This network doesn't have an Internet connection,
397 // connect anyway?" dialog after the user selects a network that doesn't validate.
398 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
399
Chalard Jean5fb43c72022-09-08 19:03:14 +0900400 // How long to wait before considering that a network is bad in the absence of any form
401 // of connectivity (valid, partial, captive portal). If none has been detected after this
402 // delay, the stack considers this network bad, which may affect how it's handled in ranking
403 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900404 // Timeout in case the "actively prefer bad wifi" feature is on
405 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
406 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900407 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900408
junyulai0ac374f2020-12-14 18:41:52 +0800409 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900410 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
411 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800412 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700413
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800414 // Delimiter used when creating the broadcast delivery group for sending
415 // CONNECTIVITY_ACTION broadcast.
416 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
417
he_won.hwang881307a2022-03-15 21:23:52 +0900418 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900419 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900420
Daniel Brightf9e945b2020-06-15 16:10:01 -0700421 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900422 @VisibleForTesting
423 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700424
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900425 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700426 @VisibleForTesting
427 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900428
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900429 @VisibleForTesting
430 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800431 @VisibleForTesting
432 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900433 // True if the cell radio of the device is capable of time-sharing.
434 @VisibleForTesting
435 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900436
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800437 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800438 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800439 private final int mReleasePendingIntentDelayMs;
440
Chalard Jean46bfbf02022-02-02 00:56:25 +0900441 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900442
Motomu Utsumif360aa62023-01-30 17:52:20 +0900443 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700444
Chalard Jean9473c982021-07-29 20:03:04 +0900445 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800446 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700447 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800448 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700449
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900450 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700451
junyulaif2c67e42018-08-07 19:50:45 +0800452 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000453 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
454 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800455 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900456 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800457
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900458 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900459 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000460 private final int mWakeUpMark;
461 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000462 // The Context is created for UserHandle.ALL.
463 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900464 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900465 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700466 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700467 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800468
Chenbo Feng15416292018-11-08 17:36:21 -0800469 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800470 protected IDnsResolver mDnsResolver;
471 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800472 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700473 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900474 private final NetworkStatsManager mStatsManager;
475 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800476 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700477
Benedict Wong493e04b2018-11-09 14:45:34 -0800478 /**
479 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
480 * instances.
481 */
482 @GuardedBy("mTNSLock")
483 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800484 private final CompanionDeviceManagerProxyService mCdmps;
Benedict Wong493e04b2018-11-09 14:45:34 -0800485
486 private final Object mTNSLock = new Object();
487
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700488 private String mCurrentTcpBufferSizes;
489
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900490 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000491 new Class[] {
492 ConnectivityService.class,
493 NetworkAgent.class,
494 NetworkAgentInfo.class,
495 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900496
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500497 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400498 // Tear down networks that have no chance (e.g. even if validated) of becoming
499 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500500 // all networks have been rematched against all NetworkRequests.
501 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400502 // Don't reap networks. This should be passed when some networks have not yet been
503 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500504 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900505 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500506
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900507 private enum UnneededFor {
508 LINGER, // Determine whether this network is unneeded and should be lingered.
509 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
510 }
511
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700512 /**
paulhuaa0743d2021-05-26 21:56:03 +0800513 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800514 * should have priority. The order is passed to netd which will use it together
515 * with UID ranges to generate the corresponding IP rule. This serves to
516 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800517 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800518 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000519 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800520 *
paulhu48291862021-07-14 14:53:57 +0800521 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
522 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800523 */
paulhu48291862021-07-14 14:53:57 +0800524 // Used when sending to netd to code for "no order".
525 static final int PREFERENCE_ORDER_NONE = 0;
526 // Order for requests that don't code for a per-app preference. As it is
527 // out of the valid range, the corresponding order should be
528 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800529 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800530 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800531 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800532 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
533 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800534 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800535 static final int PREFERENCE_ORDER_OEM = 10;
536 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800537 // See {@link #setProfileNetworkPreference}.
538 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800539 static final int PREFERENCE_ORDER_PROFILE = 20;
540 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800541 // better scores are connected.
542 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800543 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800544 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900545 // Preference order that signifies the network shouldn't be set as a default network for
546 // the UIDs, only give them access to it. TODO : replace this with a boolean
547 // in NativeUidRangeConfig
548 @VisibleForTesting
549 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
550 // Bound for the lowest valid preference order.
551 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800552
553 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700554 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700555 * from one net to another. Clear happens when we get a new
556 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
557 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700558 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700559 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700560
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700561 /**
562 * used internally to reload global proxy settings
563 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700564 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700565
Robert Greenwalt34848c02011-03-25 13:09:25 -0700566 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400567 * PAC manager has received new port.
568 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800569 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400570
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700571 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900572 * used internally when registering NetworkProviders
573 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700574 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900575 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700576
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700577 /**
578 * used internally when registering NetworkAgents
579 * obj = Messenger
580 */
581 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
582
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700583 /**
584 * used to add a network request
585 * includes a NetworkRequestInfo
586 */
587 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
588
589 /**
590 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900591 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700592 * cancel it.
593 * includes a NetworkRequestInfo
594 */
595 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
596
597 /**
598 * used to add a network listener - no request
599 * includes a NetworkRequestInfo
600 */
601 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
602
603 /**
604 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400605 * arg1 = UID of caller
606 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700607 */
608 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
609
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700610 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900611 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700612 * obj = Messenger
613 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900614 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700615
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700616 /**
617 * used internally to expire a wakelock when transitioning
618 * from one net to another. Expire happens when we fail to find
619 * a new network (typically after 1 minute) -
620 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
621 * a replacement network.
622 */
623 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
624
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700625 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800626 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400627 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800628 */
629 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
630
631 /**
632 * used to remove a pending intent and its associated network request.
633 * arg1 = UID of caller
634 * obj = PendingIntent
635 */
636 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
637
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900638 /**
639 * used to specify whether a network should be used even if unvalidated.
640 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
641 * arg2 = whether to remember this choice in the future (1 or 0)
642 * obj = network
643 */
644 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
645
646 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700647 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900648 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700649 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900650
Paul Jensenc8873fc2015-06-17 14:15:39 -0400651 /**
652 * used to add a network listener with a pending intent
653 * obj = NetworkRequestInfo
654 */
655 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
656
Hugo Benichid6b510a2017-04-06 17:22:18 +0900657 /**
658 * used to specify whether a network should not be penalized when it becomes unvalidated.
659 */
660 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
661
662 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700663 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900664 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700665 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900666
Erik Kline31b4a9e2018-01-11 21:07:29 +0900667 // Handle changes in Private DNS settings.
668 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
669
dalyk1720e542018-03-05 12:42:22 -0500670 // Handle private DNS validation status updates.
671 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
672
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900673 /**
674 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
675 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800676 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
677 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
678 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900679 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900680 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900681
682 /**
683 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
684 * config was resolved.
685 * obj = PrivateDnsConfig
686 * arg2 = netid
687 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900688 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900689
690 /**
691 * Request ConnectivityService display provisioning notification.
692 * arg1 = Whether to make the notification visible.
693 * arg2 = NetID.
694 * obj = Intent to be launched when notification selected by user, null if !arg1.
695 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900696 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900697
698 /**
lucaslin2240ef62019-03-12 13:08:03 +0800699 * Used to specify whether a network should be used even if connectivity is partial.
700 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
701 * false)
702 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
703 * obj = network
704 */
lucaslin444d43a2020-02-20 16:56:59 +0800705 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800706
707 /**
lucasline117e2e2019-10-22 18:27:33 +0800708 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
709 * Both of the arguments are bitmasks, and the value of bits come from
710 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900711 * arg1 = unused
712 * arg2 = netId
713 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800714 */
lucaslin444d43a2020-02-20 16:56:59 +0800715 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800716
717 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900718 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
719 * arg1 = unused
720 * arg2 = netId
721 * obj = captive portal data
722 */
lucaslin444d43a2020-02-20 16:56:59 +0800723 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900724
725 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900726 * Used by setRequireVpnForUids.
727 * arg1 = whether the specified UID ranges are required to use a VPN.
728 * obj = Array of UidRange objects.
729 */
730 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
731
732 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900733 * Used internally when setting the default networks for OemNetworkPreferences.
734 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800735 */
736 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
737
738 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800739 * Used to indicate the system default network becomes active.
740 */
741 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
742
743 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900744 * Used internally when setting a network preference for a user profile.
745 * obj = Pair<ProfileNetworkPreference, Listener>
746 */
747 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
748
749 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000750 * Event to specify that reasons for why an uid is blocked changed.
751 * arg1 = uid
752 * arg2 = blockedReasons
753 */
754 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
755
756 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900757 * Event to register a new network offer
758 * obj = NetworkOffer
759 */
760 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
761
762 /**
763 * Event to unregister an existing network offer
764 * obj = INetworkOfferCallback
765 */
766 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
767
768 /**
paulhu51f77dc2021-06-07 02:34:20 +0000769 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
770 */
771 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
772
773 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800774 * Event to set temporary allow bad wifi within a limited time to override
775 * {@code config_networkAvoidBadWifi}.
776 */
777 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
778
779 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100780 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
781 */
782 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
783
784 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900785 * The initial evaluation period is over for this network.
786 *
787 * If no form of connectivity has been found on this network (valid, partial, captive portal)
788 * then the stack will now consider it to have been determined bad.
789 */
790 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
791
792 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000793 * Used internally when the user does not want the network from captive portal app.
794 * obj = Network
795 */
796 private static final int EVENT_USER_DOES_NOT_WANT = 58;
797
798 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000799 * Event to set VPN as preferred network for specific apps.
800 * obj = VpnNetworkPreferenceInfo
801 */
802 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
803
804 /**
chiachangwange0192a72023-02-06 13:25:01 +0000805 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
806 */
807 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
808
809 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000810 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
811 */
812 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
813
814 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900815 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
816 * should be shown.
817 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900818 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900819
820 /**
821 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
822 * should be hidden.
823 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900824 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900825
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800826 /**
827 * The maximum alive time to allow bad wifi configuration for testing.
828 */
829 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
830
Patrick Rohr2857ac42022-01-21 14:58:16 +0100831 /**
chiachangwange0192a72023-02-06 13:25:01 +0000832 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
833 * testing.
834 */
835 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
836
837 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100838 * The priority of the tc police rate limiter -- smaller value is higher priority.
839 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
840 */
841 private static final short TC_PRIO_POLICE = 1;
842
843 /**
844 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
845 */
846 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700847 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100848
Hugo Benichi47011212017-03-30 10:46:05 +0900849 private static String eventName(int what) {
850 return sMagicDecoderRing.get(what, Integer.toString(what));
851 }
852
paulhua10d8212020-11-10 15:32:56 +0800853 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900854 final DnsResolverServiceManager dsm = context.getSystemService(
855 DnsResolverServiceManager.class);
856 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800857 }
858
Cody Kesting73708bf2019-12-18 10:57:50 -0800859 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900860 @VisibleForTesting
861 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700862 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700863 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700864 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700865 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800866 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
867 @VisibleForTesting
868 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
869
Erik Kline32120082017-12-13 19:40:49 +0900870 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900871 @VisibleForTesting
872 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700873
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400874 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800875 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400876
Chalard Jean46bfbf02022-02-02 00:56:25 +0900877 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800878 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700879
Chalard Jean5d70ba42018-06-07 16:44:04 +0900880 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
881 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800882 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400883
Erik Kline05f2b402015-04-30 12:58:40 +0900884 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700885
Chalard Jean46bfbf02022-02-02 00:56:25 +0900886 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400887
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700888 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900889 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700890
Valentin Iftime9fa35092019-09-24 13:32:13 +0200891 private Set<String> mWolSupportedInterfaces;
892
Roshan Pius08c94fb2020-01-16 12:17:17 -0800893 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800894 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800895 private final AppOpsManager mAppOpsManager;
896
897 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400898
chiachangwang3d60bac2023-01-17 14:38:08 +0000899 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900900 private final QosCallbackTracker mQosCallbackTracker;
901 private final NetworkNotificationManager mNotifier;
902 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900903
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700904 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800905 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700906
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900907 // Sequence number for NetworkProvider IDs.
908 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
909 NetworkProvider.FIRST_PROVIDER_ID);
910
Erik Klineedf878b2015-07-09 18:24:03 +0900911 // NetworkRequest activity String log entries.
912 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
913 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
914
Hugo Benichid159fdd2016-07-11 11:05:12 +0900915 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900916 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900917 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
918
Hugo Benichi47011212017-03-30 10:46:05 +0900919 private static final int MAX_WAKELOCK_LOGS = 20;
920 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900921 private int mTotalWakelockAcquisitions = 0;
922 private int mTotalWakelockReleases = 0;
923 private long mTotalWakelockDurationMs = 0;
924 private long mMaxWakelockDurationMs = 0;
925 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900926
Hugo Benichi208c0102016-07-28 17:53:06 +0900927 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900928
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700929 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900930 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700931
Erik Kline95ecfee2016-10-02 18:02:14 +0900932 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900933 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900934
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900935 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800936 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
937 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800938
Patrick Rohr2857ac42022-01-21 14:58:16 +0100939 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
940 // configured via {@link
941 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
942 // Only the handler thread is allowed to access this field.
943 private long mIngressRateLimit = -1;
944
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900945 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
946 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900947 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900948 @GuardedBy("mSelfCertifiedCapabilityCache")
949 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
950 mSelfCertifiedCapabilityCache = new HashMap<>();
951
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900952 // Flag to enable the feature of closing frozen app sockets.
953 private final boolean mDestroyFrozenSockets;
954
955 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
956 private final boolean mDelayDestroyFrozenSockets;
957
958 // Uids that ConnectivityService is pending to close sockets of.
959 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
960
Robert Greenwalt802c1102014-06-02 15:32:02 -0700961 /**
962 * Implements support for the legacy "one network per network type" model.
963 *
964 * We used to have a static array of NetworkStateTrackers, one for each
965 * network type, but that doesn't work any more now that we can have,
966 * for example, more that one wifi network. This class stores all the
967 * NetworkAgentInfo objects that support a given type, but the legacy
968 * API will only see the first one.
969 *
970 * It serves two main purposes:
971 *
972 * 1. Provide information about "the network for a given type" (since this
973 * API only supports one).
974 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
975 * the first network for a given type changes, or if the default network
976 * changes.
977 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900978 @VisibleForTesting
979 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900980
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900981 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900982 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900983
Robert Greenwalt802c1102014-06-02 15:32:02 -0700984 /**
985 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
986 * Each list holds references to all NetworkAgentInfos that are used to
987 * satisfy requests for that network type.
988 *
989 * This array is built out at startup such that an unsupported network
990 * doesn't get an ArrayList instance, making this a tristate:
991 * unsupported, supported but not active and active.
992 *
993 * The actual lists are populated when we scan the network types that
994 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900995 *
996 * Threading model:
997 * - addSupportedType() is only called in the constructor
998 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
999 * They are therefore not thread-safe with respect to each other.
1000 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1001 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001002 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001003 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001004 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001005 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001006 @NonNull
1007 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001008
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001009 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1010 // an entry have no timer (equivalent to -1). Lazily loaded.
1011 @NonNull
1012 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1013
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001014 LegacyTypeTracker(@NonNull ConnectivityService service) {
1015 mService = service;
1016 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001017 }
1018
Chiachang Wang3bc52762021-11-25 14:17:57 +08001019 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1020 // addressed.
1021 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001022 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1023 final PackageManager pm = ctx.getPackageManager();
1024 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1025 addSupportedType(TYPE_WIFI);
1026 }
1027 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1028 addSupportedType(TYPE_WIFI_P2P);
1029 }
1030 if (tm.isDataCapable()) {
1031 // Telephony does not have granular support for these types: they are either all
1032 // supported, or none is supported
1033 addSupportedType(TYPE_MOBILE);
1034 addSupportedType(TYPE_MOBILE_MMS);
1035 addSupportedType(TYPE_MOBILE_SUPL);
1036 addSupportedType(TYPE_MOBILE_DUN);
1037 addSupportedType(TYPE_MOBILE_HIPRI);
1038 addSupportedType(TYPE_MOBILE_FOTA);
1039 addSupportedType(TYPE_MOBILE_IMS);
1040 addSupportedType(TYPE_MOBILE_CBS);
1041 addSupportedType(TYPE_MOBILE_IA);
1042 addSupportedType(TYPE_MOBILE_EMERGENCY);
1043 }
1044 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1045 addSupportedType(TYPE_BLUETOOTH);
1046 }
1047 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1048 // TYPE_PROXY is only used on Wear
1049 addSupportedType(TYPE_PROXY);
1050 }
1051 // Ethernet is often not specified in the configs, although many devices can use it via
1052 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001053 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001054 addSupportedType(TYPE_ETHERNET);
1055 }
1056
1057 // Always add TYPE_VPN as a supported type
1058 addSupportedType(TYPE_VPN);
1059 }
1060
1061 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001062 if (mTypeLists[type] != null) {
1063 throw new IllegalStateException(
1064 "legacy list for type " + type + "already initialized");
1065 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001066 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001067 }
1068
Robert Greenwalt802c1102014-06-02 15:32:02 -07001069 public boolean isTypeSupported(int type) {
1070 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1071 }
1072
1073 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001074 synchronized (mTypeLists) {
1075 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1076 return mTypeLists[type].get(0);
1077 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001078 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001079 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001080 }
1081
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001082 public int getRestoreTimerForType(int type) {
1083 synchronized (mTypeLists) {
1084 if (mRestoreTimers == null) {
1085 mRestoreTimers = loadRestoreTimers();
1086 }
1087 return mRestoreTimers.getOrDefault(type, -1);
1088 }
1089 }
1090
1091 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1092 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001093 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001094 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1095 for (final String config : configs) {
1096 final String[] splits = TextUtils.split(config, ",");
1097 if (splits.length != 2) {
1098 logwtf("Invalid restore timer token count: " + config);
1099 continue;
1100 }
1101 try {
1102 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1103 } catch (NumberFormatException e) {
1104 logwtf("Invalid restore timer number format: " + config, e);
1105 }
1106 }
1107 return ret;
1108 }
1109
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001110 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001111 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001112 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001113 log("Sending " + state
1114 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001115 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001116 }
1117 }
1118
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001119 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1120 // network type, to preserve previous behaviour.
1121 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1122 if (vpnNai != mService.getLegacyLockdownNai()) return;
1123
1124 if (vpnNai.declaredUnderlyingNetworks == null
1125 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1126 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1127 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1128 return;
1129 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001130 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001131 vpnNai.declaredUnderlyingNetworks[0]);
1132 if (underlyingNai == null) return;
1133
1134 final int type = underlyingNai.networkInfo.getType();
1135 final DetailedState state = DetailedState.CONNECTED;
1136 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1137 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1138 }
1139
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001140 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001141 public void add(int type, NetworkAgentInfo nai) {
1142 if (!isTypeSupported(type)) {
1143 return; // Invalid network type.
1144 }
1145 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1146
1147 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1148 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001149 return;
1150 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001151 synchronized (mTypeLists) {
1152 list.add(nai);
1153 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001154
Chalard Jean5b409c72021-02-04 13:12:59 +09001155 // Send a broadcast if this is the first network of its type or if it's the default.
1156 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001157
1158 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1159 // to preserve previous behaviour.
1160 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001161 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001162 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1163 mService.sendLegacyNetworkBroadcast(nai, state, type);
1164 }
1165
1166 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1167 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001168 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001169 }
1170
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001171 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001172 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001173 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1174 if (list == null || list.isEmpty()) {
1175 return;
1176 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001177 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001178
Hugo Benichi389633f2016-06-21 09:48:07 +09001179 synchronized (mTypeLists) {
1180 if (!list.remove(nai)) {
1181 return;
1182 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001183 }
1184
Lorenzo Colitti49767722015-05-01 00:30:10 +09001185 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001186 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1187 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001188 }
1189
1190 if (!list.isEmpty() && wasFirstNetwork) {
1191 if (DBG) log("Other network available for type " + type +
1192 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001193 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001194 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001195 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001196 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001197 }
1198 }
1199
1200 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001201 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1202 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001203 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001204 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001205 }
1206 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001207
Chalard Jean46bfbf02022-02-02 00:56:25 +09001208 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001209 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001210 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001211 final DetailedState state = nai.networkInfo.getDetailedState();
1212 for (int type = 0; type < mTypeLists.length; type++) {
1213 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001214 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001215 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001216 if (isFirst || contains && isDefault) {
1217 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001218 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001219 }
1220 }
1221 }
1222
Robert Greenwalt94e22142014-07-30 16:31:24 -07001223 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001224 pw.println("mLegacyTypeTracker:");
1225 pw.increaseIndent();
1226 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001227 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001228 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001229 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001230 pw.println();
1231 pw.println("Current state:");
1232 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001233 synchronized (mTypeLists) {
1234 for (int type = 0; type < mTypeLists.length; type++) {
1235 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1236 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001237 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001238 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001239 }
1240 }
1241 pw.decreaseIndent();
1242 pw.decreaseIndent();
1243 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001244 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001245 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001246 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001247
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001248 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001249 /**
1250 * Helper class which parses out priority arguments and dumps sections according to their
1251 * priority. If priority arguments are omitted, function calls the legacy dump command.
1252 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001253 private class LocalPriorityDump {
1254 private static final String PRIORITY_ARG = "--dump-priority";
1255 private static final String PRIORITY_ARG_HIGH = "HIGH";
1256 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1257
1258 LocalPriorityDump() {}
1259
1260 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1261 doDump(fd, pw, new String[] {DIAG_ARG});
1262 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001263 }
1264
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001265 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1266 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001267 }
1268
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001269 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1270 if (args == null) {
1271 dumpNormal(fd, pw, args);
1272 return;
1273 }
1274
1275 String priority = null;
1276 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1277 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1278 argIndex++;
1279 priority = args[argIndex];
1280 }
1281 }
1282
1283 if (PRIORITY_ARG_HIGH.equals(priority)) {
1284 dumpHigh(fd, pw);
1285 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1286 dumpNormal(fd, pw, args);
1287 } else {
1288 // ConnectivityService publishes binder service using publishBinderService() with
1289 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001290 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1291 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001292 // TODO: Integrate into signal dump.
1293 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001294 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001295 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001296 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001297
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001298 /**
1299 * Dependencies of ConnectivityService, for injection in tests.
1300 */
1301 @VisibleForTesting
1302 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001303 public int getCallingUid() {
1304 return Binder.getCallingUid();
1305 }
1306
Chalard Jeandf29a852023-05-29 17:02:43 +09001307 public boolean isAtLeastS() {
1308 return SdkLevel.isAtLeastS();
1309 }
1310
1311 public boolean isAtLeastT() {
1312 return SdkLevel.isAtLeastT();
1313 }
1314
1315 public boolean isAtLeastU() {
1316 return SdkLevel.isAtLeastU();
1317 }
1318
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001319 /**
1320 * Get system properties to use in ConnectivityService.
1321 */
1322 public MockableSystemProperties getSystemProperties() {
1323 return new MockableSystemProperties();
1324 }
1325
1326 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001327 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1328 */
1329 public ConnectivityResources getResources(@NonNull Context ctx) {
1330 return new ConnectivityResources(ctx);
1331 }
1332
1333 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001334 * Create a HandlerThread to use in ConnectivityService.
1335 */
1336 public HandlerThread makeHandlerThread() {
1337 return new HandlerThread("ConnectivityServiceThread");
1338 }
1339
1340 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001341 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001342 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001343 public NetworkStackClientBase getNetworkStack() {
1344 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001345 }
1346
1347 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001348 * @see ProxyTracker
1349 */
1350 public ProxyTracker makeProxyTracker(@NonNull Context context,
1351 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001352 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001353 }
1354
1355 /**
1356 * @see NetIdManager
1357 */
1358 public NetIdManager makeNetIdManager() {
1359 return new NetIdManager();
1360 }
1361
1362 /**
1363 * @see NetworkUtils#queryUserAccess(int, int)
1364 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001365 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1366 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001367 }
1368
1369 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001370 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1371 * requires CAP_NET_ADMIN, which the unit tests do not have.
1372 */
1373 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1374 InetSocketAddress remote) {
1375 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1376 }
1377
1378 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001379 * @see MultinetworkPolicyTracker
1380 */
1381 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1382 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1383 return new MultinetworkPolicyTracker(c, h, r);
1384 }
1385
Aaron Huang330a4c02020-10-27 03:36:19 +08001386 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001387 * @see AutomaticOnOffKeepaliveTracker
1388 */
1389 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1390 @NonNull Context c, @NonNull Handler h) {
1391 return new AutomaticOnOffKeepaliveTracker(c, h);
1392 }
1393
1394 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001395 * @see BatteryStatsManager
1396 */
1397 public void reportNetworkInterfaceForTransports(Context context, String iface,
1398 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001399 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001400 context.getSystemService(BatteryStatsManager.class);
1401 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1402 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001403
1404 public boolean getCellular464XlatEnabled() {
1405 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1406 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001407
1408 /**
1409 * @see PendingIntent#intentFilterEquals
1410 */
1411 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1412 return a.intentFilterEquals(b);
1413 }
1414
1415 /**
1416 * @see LocationPermissionChecker
1417 */
1418 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1419 return new LocationPermissionChecker(context);
1420 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001421
1422 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001423 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001424 *
1425 * This method returns null in versions before T, where carrier privilege
1426 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001427 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001428 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001429 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1430 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001431 if (isAtLeastT()) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09001432 return new CarrierPrivilegeAuthenticator(context, tm);
1433 } else {
1434 return null;
1435 }
1436 }
1437
1438 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001439 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001440 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001441 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001442 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001443 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001444
1445 /**
1446 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001447 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001448 * @return BpfNetMaps implementation.
1449 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001450 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1451 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001452 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001453
1454 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001455 * @see ClatCoordinator
1456 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001457 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001458 public ClatCoordinator getClatCoordinator(INetd netd) {
1459 return new ClatCoordinator(
1460 new ClatCoordinator.Dependencies() {
1461 @NonNull
1462 public INetd getNetd() {
1463 return netd;
1464 }
1465 });
1466 }
1467
1468 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001469 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1470 */
1471 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1472 final InterfaceParams params = InterfaceParams.getByName(iface);
1473 if (params == null) {
1474 // the interface might have disappeared.
1475 logw("Failed to get interface params for interface " + iface);
1476 return;
1477 }
1478 try {
1479 // converting rateInBytesPerSecond from long to int is safe here because the
1480 // setting's range is limited to INT_MAX.
1481 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001482 Log.i(TAG,
1483 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001484 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1485 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1486 } catch (IOException e) {
1487 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1488 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1489 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1490 + ") failure: ", e);
1491 }
1492 }
1493
1494 /**
1495 * Wraps {@link TcUtils#tcFilterDelDev}
1496 */
1497 public void disableIngressRateLimit(String iface) {
1498 final InterfaceParams params = InterfaceParams.getByName(iface);
1499 if (params == null) {
1500 // the interface might have disappeared.
1501 logw("Failed to get interface params for interface " + iface);
1502 return;
1503 }
1504 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001505 Log.i(TAG,
1506 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001507 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1508 } catch (IOException e) {
1509 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1510 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1511 }
1512 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001513
1514 /**
1515 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1516 */
1517 // TODO: when available in all active branches:
1518 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1519 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1520 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1521 return BroadcastOptionsShimImpl.newInstance(options);
1522 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001523
1524 /**
1525 * Wrapper method for
1526 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1527 *
1528 * @param changeId The ID of the compatibility change in question.
1529 * @param packageName The package name of the app in question.
1530 * @param user The user that the operation is done for.
1531 * @return {@code true} if the change is enabled for the specified package.
1532 */
1533 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1534 @NonNull final UserHandle user) {
1535 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1536 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001537
1538 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001539 * As above but with a UID.
1540 * @see CompatChanges#isChangeEnabled(long, int)
1541 */
1542 public boolean isChangeEnabled(final long changeId, final int uid) {
1543 return CompatChanges.isChangeEnabled(changeId, uid);
1544 }
1545
1546 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001547 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1548 *
1549 * @param ranges target uid ranges
1550 * @param exemptUids uids to skip close socket
1551 */
1552 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1553 @NonNull final Set<Integer> exemptUids)
1554 throws SocketException, InterruptedIOException, ErrnoException {
1555 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1556 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001557
1558 /**
1559 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1560 *
1561 * @param ownerUids target uids to close sockets
1562 */
1563 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1564 throws SocketException, InterruptedIOException, ErrnoException {
1565 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1566 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001567
1568 /**
1569 * Schedule the evaluation timeout.
1570 *
1571 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1572 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1573 * of these events happen, this time will run out, after which the network is considered
1574 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1575 * on this network and considers it won't provide connectivity. In particular, that means
1576 * it's when the system prefers it to cell if it's wifi and configuration says it should
1577 * prefer bad wifi to cell.
1578 */
1579 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1580 @NonNull final Network network, final long delayMs) {
1581 handler.sendMessageDelayed(
1582 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1583 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001584 }
1585
junyulaie7c7d2a2021-01-26 15:29:15 +08001586 public ConnectivityService(Context context) {
1587 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001588 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1589 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001590 }
1591
1592 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001593 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1594 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001595 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001596
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001597 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001598 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001599 mSystemProperties = mDeps.getSystemProperties();
1600 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001601 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001602 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001603 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1604 // Pass limit - 1 to maintain backward compatibility.
1605 // TODO: Remove the workaround.
1606 mNetworkRequestCounter =
1607 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1608 mSystemNetworkRequestCounter =
1609 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001610
Hugo Benichi208c0102016-07-28 17:53:06 +09001611 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001612 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1613 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001614 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001615 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001616 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001617 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1618 mDefaultNetworkRequests.add(mDefaultRequest);
1619 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001620
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001621 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001622 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001623
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001624 // The default WiFi request is a background request so that apps using WiFi are
1625 // migrated to a better network (typically ethernet) when one comes up, instead
1626 // of staying on WiFi forever.
1627 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1628 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1629
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001630 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1631 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1632 NetworkRequest.Type.BACKGROUND_REQUEST);
1633
Chalard Jean0702f982021-09-16 21:50:07 +09001634 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1635 // TODO: Consider making the timer customizable.
1636 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1637 mCellularRadioTimesharingCapable =
1638 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1639
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001640 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1641 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1642
1643 if (SdkLevel.isAtLeastU()) {
1644 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1645 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1646 final int defaultUMarkMask = 0x80000000; // u32
1647
1648 if ((mark == 0) || (mask == 0)) {
1649 // simply treat unset/disabled as the default U value
1650 mark = defaultUMarkMask;
1651 mask = defaultUMarkMask;
1652 }
1653 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1654 // invalid device overlay settings
1655 throw new IllegalArgumentException(
1656 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1657 }
1658 }
1659
1660 mWakeUpMark = mark;
1661 mWakeUpMask = mask;
1662
Paul Hu51f816b2022-08-11 14:43:47 +00001663 mNetd = netd;
1664 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001665 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001666 mPermissionMonitor =
1667 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001668 mHandlerThread.start();
1669 mHandler = new InternalHandler(mHandlerThread.getLooper());
1670 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001671 mConnectivityDiagnosticsHandler =
1672 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001673
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001674 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001675 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001676
junyulaie7c7d2a2021-01-26 15:29:15 +08001677 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001678 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001679 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001680 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001681
Wink Saville32506bc2013-06-29 21:10:57 -07001682 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001683 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001684 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001685 mCarrierPrivilegeAuthenticator =
1686 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001687
Sudheer Shanka9967d462021-03-18 19:09:25 +00001688 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001689 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1690 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001691 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001692
1693 final PowerManager powerManager = (PowerManager) context.getSystemService(
1694 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001695 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001696 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001697
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001698 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1699 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001700 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001701 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001702 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001703 mProtectedNetworks.add(p);
1704 } else {
1705 if (DBG) loge("Ignoring protectedNetwork " + p);
1706 }
1707 }
1708
soma, kawata29444ae2019-05-23 09:30:40 +09001709 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1710
James Mattis02220e22021-03-13 19:27:21 -08001711 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001712 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001713 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001714 final IntentFilter userIntentFilter = new IntentFilter();
1715 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1716 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1717 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1718 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001719
James Mattis02220e22021-03-13 19:27:21 -08001720 // Listen to package add/removes for netd
1721 final IntentFilter packageIntentFilter = new IntentFilter();
1722 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1723 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1724 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1725 packageIntentFilter.addDataScheme("package");
1726 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001727 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001728
Motomu Utsumi1e51a642023-07-18 15:11:41 +09001729 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001730
Chalard Jean46bfbf02022-02-02 00:56:25 +09001731 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001732 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001733 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001734 } catch (RemoteException | ServiceSpecificException e) {
1735 loge("Error registering event listener :" + e);
1736 }
1737
Erik Kline05f2b402015-04-30 12:58:40 +09001738 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1739 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001740
chiachangwang7c17c282023-02-02 05:58:59 +00001741 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001742 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001743 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001744
1745 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001746 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001747 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1748 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001749 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001750 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1751 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001752
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001753 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001754 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001755 mNetworkRanker =
1756 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1757
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001758 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001759
Chiachang Wangc1215d32020-10-20 15:38:58 +08001760 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001761 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001762
Chalard Jean28018572020-12-21 18:36:52 +09001763 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1764 // request that doesn't allow fallback to the default network. It should never be visible
1765 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1766 // arguments like the handler or the DnsResolver.
1767 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001768 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001769 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001770 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001771 new LinkProperties(), new NetworkCapabilities(),
1772 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001773 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1774 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001775
1776 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001777 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1778 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1779 // Even if it could, running on S would at least require mocking out the BPF map,
1780 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1781 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001782 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001783 mDscpPolicyTracker = new DscpPolicyTracker();
1784 }
Tyler Wear72388212021-09-09 14:49:02 -07001785 } catch (ErrnoException e) {
1786 loge("Unable to create DscpPolicyTracker");
1787 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001788
1789 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1790 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001791
Chalard Jeandf29a852023-05-29 17:02:43 +09001792 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001793 mCdmps = new CompanionDeviceManagerProxyService(context);
1794 } else {
1795 mCdmps = null;
1796 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001797
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001798 mDestroyFrozenSockets = mDeps.isAtLeastU()
1799 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
1800 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1801 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
1802 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001803 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1804 new UidFrozenStateChangedCallback() {
1805 @Override
1806 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1807 if (uids.length != frozenStates.length) {
1808 Log.wtf(TAG, "uids has length " + uids.length
1809 + " but frozenStates has length " + frozenStates.length);
1810 return;
1811 }
1812
1813 final UidFrozenStateChangedArgs args =
1814 new UidFrozenStateChangedArgs(uids, frozenStates);
1815
1816 mHandler.sendMessage(
1817 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1818 }
1819 };
1820
1821 final ActivityManager activityManager =
1822 mContext.getSystemService(ActivityManager.class);
1823 activityManager.registerUidFrozenStateChangedCallback(
1824 (Runnable r) -> r.run(), frozenStateChangedCallback);
1825 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001826 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001827
Xiao Ma0a171c02022-01-23 16:14:51 +00001828 /**
1829 * Check whether or not the device supports Ethernet transport.
1830 */
1831 public static boolean deviceSupportsEthernet(final Context context) {
1832 final PackageManager pm = context.getPackageManager();
1833 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1834 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1835 }
1836
Chalard Jean46adcf32018-04-18 20:18:38 +09001837 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001838 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1839 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001840 }
1841
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001842 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1843 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001844 final NetworkCapabilities netCap = new NetworkCapabilities();
1845 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001846 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001847 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001848 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001849 return netCap;
1850 }
1851
James Mattis45d81842021-01-10 14:24:24 -08001852 private NetworkRequest createDefaultRequest() {
1853 return createDefaultInternetRequestForTransport(
1854 TYPE_NONE, NetworkRequest.Type.REQUEST);
1855 }
1856
lucaslin3ba7cc22022-12-19 02:35:33 +00001857 private NetworkRequest createVpnRequest() {
1858 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1859 .withoutDefaultCapabilities()
1860 .addTransportType(TRANSPORT_VPN)
1861 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1862 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1863 .build();
1864 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1865 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1866 }
1867
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001868 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001869 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001870 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001871 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001872 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001873 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001874 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001875 netCap.addTransportType(transportType);
1876 }
James Mattis45d81842021-01-10 14:24:24 -08001877 return createNetworkRequest(type, netCap);
1878 }
1879
1880 private NetworkRequest createNetworkRequest(
1881 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001882 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001883 }
1884
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001885 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1886 NetworkRequest.Type type) {
1887 final NetworkCapabilities netCap = new NetworkCapabilities();
1888 netCap.clearAll();
1889 netCap.addCapability(capability);
1890 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1891 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1892 }
1893
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001894 // Used only for testing.
1895 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001896 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001897 // changing ContentResolver to make registerContentObserver non-final).
1898 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1899 // by subclassing SettingsObserver.
1900 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001901 void updateAlwaysOnNetworks() {
1902 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001903 }
1904
Erik Kline9a62f012018-03-21 07:18:33 -07001905 // See FakeSettingsProvider comment above.
1906 @VisibleForTesting
1907 void updatePrivateDnsSettings() {
1908 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1909 }
1910
paulhu51f77dc2021-06-07 02:34:20 +00001911 @VisibleForTesting
1912 void updateMobileDataPreferredUids() {
1913 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1914 }
1915
Patrick Rohr2857ac42022-01-21 14:58:16 +01001916 @VisibleForTesting
1917 void updateIngressRateLimit() {
1918 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1919 }
1920
Aaron Huang40b52442021-06-08 04:34:24 +08001921 @VisibleForTesting
1922 void simulateUpdateProxyInfo(@Nullable final Network network,
1923 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001924 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08001925 new Pair<>(network, proxyInfo)).sendToTarget();
1926 }
1927
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001928 private void handleAlwaysOnNetworkRequest(
1929 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001930 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001931 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001932 handleAlwaysOnNetworkRequest(networkRequest, enable);
1933 }
1934
1935 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001936 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001937 if (enable == isEnabled) {
1938 return; // Nothing to do.
1939 }
1940
1941 if (enable) {
1942 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001943 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001944 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001945 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001946 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001947 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1948 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001949 }
1950 }
1951
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001952 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001953 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1954 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1955 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1956 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001957 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1958 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001959 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001960 }
1961
paulhu51f77dc2021-06-07 02:34:20 +00001962 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001963 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001964 private void registerSettingsCallbacks() {
1965 // Watch for global HTTP proxy changes.
1966 mSettingsObserver.observe(
1967 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1968 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1969
Chalard Jean46bfbf02022-02-02 00:56:25 +09001970 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001971 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001972 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001973 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1974
Chalard Jean46bfbf02022-02-02 00:56:25 +09001975 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001976 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001977 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001978 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001979
1980 // Watch for mobile data preferred uids changes.
1981 mSettingsObserver.observe(
1982 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1983 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001984
1985 // Watch for ingress rate limit changes.
1986 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01001987 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01001988 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1989 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001990 }
1991
Erik Kline31b4a9e2018-01-11 21:07:29 +09001992 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001993 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1994 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001995 }
1996 }
1997
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001998 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001999 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2000 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002001 return mNextNetworkRequestId++;
2002 }
2003
junyulai74f9a8b2018-06-13 15:00:37 +08002004 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002005 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002006 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002007 if (network == null) {
2008 return null;
2009 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002010 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002011 }
2012
2013 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002014 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002015 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002016 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002017 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002018
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002019 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002020 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002021 private NetworkAgentInfo getVpnForUid(int uid) {
2022 synchronized (mNetworkForNetId) {
2023 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2024 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002025 if (nai.isVPN() && nai.everConnected()
2026 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002027 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002028 }
2029 }
2030 }
2031 return null;
2032 }
2033
Chalard Jean46bfbf02022-02-02 00:56:25 +09002034 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002035 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002036 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002037 final NetworkAgentInfo nai = getVpnForUid(uid);
2038 if (nai != null) return nai.declaredUnderlyingNetworks;
2039 return null;
2040 }
2041
Lorenzo Colittia7574052021-01-19 01:33:05 +09002042 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002043 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002044
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002045 final Network[] networks = getVpnUnderlyingNetworks(uid);
2046 if (networks != null) {
2047 // getUnderlyingNetworks() returns:
2048 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2049 // empty array => the VPN explicitly said "no default network".
2050 // non-empty array => the VPN specified one or more default networks; we use the
2051 // first one.
2052 if (networks.length > 0) {
2053 nai = getNetworkAgentInfoForNetwork(networks[0]);
2054 } else {
2055 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002056 }
2057 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002058 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002059 }
2060
2061 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002062 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002063 */
paulhu7aeba372020-12-30 00:42:19 +08002064 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2065 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002066 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002067 if (ignoreBlocked) {
2068 return false;
2069 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002070 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002071 final long ident = Binder.clearCallingIdentity();
2072 try {
2073 final boolean metered = nc == null ? true : nc.isMetered();
2074 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2075 } finally {
2076 Binder.restoreCallingIdentity(ident);
2077 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002078 }
2079
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002080 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002081 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2082 return;
2083 }
Hugo Benichi47011212017-03-30 10:46:05 +09002084 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002085 synchronized (mBlockedAppUids) {
2086 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002087 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002088 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002089 blocked = false;
2090 } else {
2091 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002092 }
2093 }
Hugo Benichi47011212017-03-30 10:46:05 +09002094 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2095 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2096 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002097 }
2098
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002099 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002100 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2101 return;
2102 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002103 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002104 final int requestId = nri.getActiveRequest() != null
2105 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002106 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002107 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002108 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002109 }
2110
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002111 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002112 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002113 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002114 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002115 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002116 @NonNull
2117 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2118 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002119 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2120 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2121 // but only exists if an app asks about them or requests them. Ensure the requesting app
2122 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002123 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002124 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2125 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2126 null /* extraInfo */);
2127 }
2128 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002129 return filtered;
2130 }
2131
2132 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2133 boolean ignoreBlocked) {
2134 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2135 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002136 }
2137
2138 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002139 * Return NetworkInfo for the active (i.e., connected) network interface.
2140 * It is assumed that at most one network is active at a time. If more
2141 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002142 * @return the info for the active network, or {@code null} if none is
2143 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002144 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002145 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002146 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002147 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002148 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002149 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002150 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2151 if (nai == null) return null;
2152 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2153 maybeLogBlockedNetworkInfo(networkInfo, uid);
2154 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002155 }
2156
Paul Jensen1f567382015-02-13 14:18:39 -05002157 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002158 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002159 public Network getActiveNetwork() {
2160 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002161 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002162 }
2163
2164 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002165 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002166 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002167 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002168 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002169 }
2170
Chalard Jean46bfbf02022-02-02 00:56:25 +09002171 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002172 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002173 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2174 if (vpnNai != null) {
2175 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2176 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2177 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002178 }
Paul Jensen1f567382015-02-13 14:18:39 -05002179 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002180
James Mattis2516da32021-01-31 17:06:19 -08002181 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002182 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2183 ignoreBlocked)) {
2184 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002185 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002186 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002187 }
2188
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002189 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002190 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002191 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002192 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002193 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2194 if (nai == null) return null;
2195 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002196 }
2197
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002198 /** Returns a NetworkInfo object for a network that doesn't exist. */
2199 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2200 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2201 getNetworkTypeName(networkType), "" /* subtypeName */);
2202 info.setIsAvailable(true);
2203 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2204 // background data is restricted.
2205 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2206 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2207 ? DetailedState.BLOCKED
2208 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002209 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2210 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002211 return info;
2212 }
2213
Lorenzo Colittia7574052021-01-19 01:33:05 +09002214 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002215 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2216 return null;
2217 }
2218 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002219 if (nai == null) {
2220 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002221 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002222 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2223 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002224 }
2225
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002226 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002227 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002228 public NetworkInfo getNetworkInfo(int networkType) {
2229 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002230 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002231 if (getVpnUnderlyingNetworks(uid) != null) {
2232 // A VPN is active, so we may need to return one of its underlying networks. This
2233 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002234 // getNetworkAgentInfoForUid.
2235 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2236 if (nai == null) return null;
2237 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2238 if (networkInfo.getType() == networkType) {
2239 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002240 }
2241 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002242 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002243 }
2244
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002245 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002246 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002247 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002248 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002249 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002250 if (nai == null) return null;
2251 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002252 }
2253
2254 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002255 public NetworkInfo[] getAllNetworkInfo() {
2256 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002257 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002258 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2259 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002260 NetworkInfo info = getNetworkInfo(networkType);
2261 if (info != null) {
2262 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002263 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002264 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002265 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002266 }
2267
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002268 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002269 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002270 public Network getNetworkForType(int networkType) {
2271 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002272 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2273 return null;
2274 }
2275 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2276 if (nai == null) {
2277 return null;
2278 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002279 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002280 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2281 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002282 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002283 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002284 }
2285
2286 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002287 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002288 public Network[] getAllNetworks() {
2289 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002290 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002291 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002292 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002293 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002294 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002295 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002296 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002297 }
2298
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002299 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002300 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002301 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002302 // The basic principle is: if an app's traffic could possibly go over a
2303 // network, without the app doing anything multinetwork-specific,
2304 // (hence, by "default"), then include that network's capabilities in
2305 // the array.
2306 //
2307 // In the normal case, app traffic only goes over the system's default
2308 // network connection, so that's the only network returned.
2309 //
2310 // With a VPN in force, some app traffic may go into the VPN, and thus
2311 // over whatever underlying networks the VPN specifies, while other app
2312 // traffic may go over the system default network (e.g.: a split-tunnel
2313 // VPN, or an app disallowed by the VPN), so the set of networks
2314 // returned includes the VPN's underlying networks and the system
2315 // default.
2316 enforceAccessPermission();
2317
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002318 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002319
James Mattis2516da32021-01-31 17:06:19 -08002320 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2321 if (!nri.isBeingSatisfied()) {
2322 continue;
2323 }
2324 final NetworkAgentInfo nai = nri.getSatisfier();
2325 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2326 if (null != nc
2327 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2328 && !result.containsKey(nai.network)) {
2329 result.put(
2330 nai.network,
2331 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002332 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002333 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2334 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002335 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002336 }
2337
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002338 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002339 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002340 if (null != networks) {
2341 for (final Network network : networks) {
2342 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2343 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002344 result.put(
2345 network,
2346 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002347 nc,
2348 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002349 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002350 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002351 }
2352 }
2353 }
2354
2355 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2356 out = result.values().toArray(out);
2357 return out;
2358 }
2359
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002360 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2361 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2362 // can call sampleConnectivityState and make the checks on it.
2363 @NonNull
2364 private StatsEvent sampleConnectivityStateToStatsEvent() {
2365 final ConnectivityStateSample sample = sampleConnectivityState();
2366 return ConnectivityStatsLog.buildStatsEvent(
2367 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2368 sample.getNetworkCountPerTransports().toByteArray(),
2369 sample.getConnectionDurationPerTransports().toByteArray(),
2370 sample.getNetworkRequestCount().toByteArray(),
2371 sample.getNetworks().toByteArray());
2372 }
2373
2374 /**
2375 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2376 *
2377 * This is used for metrics. These snapshots will be sampled and constitute a base for
2378 * statistics about connectivity state of devices.
2379 */
2380 @VisibleForTesting
2381 @NonNull
2382 public ConnectivityStateSample sampleConnectivityState() {
2383 ensureRunningOnConnectivityServiceThread();
2384 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2385 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2386 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2387 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2388 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2389 return builder.build();
2390 }
2391
2392 private static NetworkCountPerTransports sampleNetworkCount(
2393 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2394 final SparseIntArray countPerTransports = new SparseIntArray();
2395 for (final NetworkAgentInfo nai : nais) {
2396 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2397 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2398 }
2399 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2400 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2401 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2402 c.setTransportTypes(countPerTransports.keyAt(i));
2403 c.setNetworkCount(countPerTransports.valueAt(i));
2404 builder.addNetworkCountForTransports(c);
2405 }
2406 return builder.build();
2407 }
2408
2409 private static ConnectionDurationPerTransports sampleConnectionDuration(
2410 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2411 final ConnectionDurationPerTransports.Builder builder =
2412 ConnectionDurationPerTransports.newBuilder();
2413 for (final NetworkAgentInfo nai : nais) {
2414 final ConnectionDurationForTransports.Builder c =
2415 ConnectionDurationForTransports.newBuilder();
2416 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2417 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2418 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2419 // Add millisPerSecond/2 to round up or down to the nearest value
2420 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2421 builder.addConnectionDurationForTransports(c);
2422 }
2423 return builder.build();
2424 }
2425
2426 private static NetworkRequestCount sampleNetworkRequestCount(
2427 @NonNull final Collection<NetworkRequestInfo> nris) {
2428 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2429 final SparseIntArray countPerType = new SparseIntArray();
2430 for (final NetworkRequestInfo nri : nris) {
2431 final int type;
2432 if (Process.SYSTEM_UID == nri.mAsUid) {
2433 // The request is filed "as" the system, so it's the system on its own behalf.
2434 type = RequestType.RT_SYSTEM.getNumber();
2435 } else if (Process.SYSTEM_UID == nri.mUid) {
2436 // The request is filed by the system as some other app, so it's the system on
2437 // behalf of an app.
2438 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2439 } else {
2440 // Not the system, so it's an app requesting on its own behalf.
2441 type = RequestType.RT_APP.getNumber();
2442 }
2443 countPerType.put(type, countPerType.get(type, 0));
2444 }
2445 for (int i = countPerType.size() - 1; i >= 0; --i) {
2446 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2447 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2448 r.setRequestCount(countPerType.valueAt(i));
2449 builder.addRequestCountForType(r);
2450 }
2451 return builder.build();
2452 }
2453
2454 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2455 final NetworkList.Builder builder = NetworkList.newBuilder();
2456 for (final NetworkAgentInfo nai : nais) {
2457 final NetworkCapabilities nc = nai.networkCapabilities;
2458 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2459 d.setTransportTypes((int) nc.getTransportTypesInternal());
2460 final MeteredState meteredState;
2461 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2462 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2463 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2464 meteredState = MeteredState.METERED_NO;
2465 } else {
2466 meteredState = MeteredState.METERED_YES;
2467 }
2468 d.setMeteredState(meteredState);
2469 final ValidatedState validatedState;
2470 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2471 validatedState = ValidatedState.VS_PORTAL;
2472 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2473 validatedState = ValidatedState.VS_PARTIAL;
2474 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2475 validatedState = ValidatedState.VS_VALID;
2476 } else {
2477 validatedState = ValidatedState.VS_INVALID;
2478 }
2479 d.setValidatedState(validatedState);
2480 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2481 d.setCapabilities(nc.getCapabilitiesInternal());
2482 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2483 builder.addNetworkDescription(d);
2484 }
2485 return builder.build();
2486 }
2487
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002488 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002489 public boolean isNetworkSupported(int networkType) {
2490 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002491 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002492 }
2493
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002494 /**
2495 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002496 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002497 * @return the ip properties for the active network, or {@code null} if
2498 * none is active
2499 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002500 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002501 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002502 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002503 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002504 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2505 if (nai == null) return null;
2506 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002507 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002508 }
2509
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002510 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002511 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002512 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002513 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002514 final LinkProperties lp = getLinkProperties(nai);
2515 if (lp == null) return null;
2516 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002517 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002518 }
2519
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002520 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002521 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002522 public LinkProperties getLinkProperties(Network network) {
2523 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002524 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2525 if (lp == null) return null;
2526 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002527 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002528 }
2529
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002530 @Nullable
2531 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002532 if (nai == null) {
2533 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002534 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002535 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002536 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002537 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002538 }
2539
lucaslinc582d502022-01-27 09:07:00 +08002540 @Override
2541 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002542 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002543 @NonNull String packageName, @Nullable String callingAttributionTag) {
2544 Objects.requireNonNull(packageName);
2545 Objects.requireNonNull(lp);
2546 enforceNetworkStackOrSettingsPermission();
2547 if (!checkAccessPermission(-1 /* pid */, uid)) {
2548 return null;
2549 }
2550 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2551 }
2552
Qingxi Lib2748102020-01-08 12:51:49 -08002553 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2554 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2555 }
2556
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002557 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002558 if (nai == null) return null;
2559 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002560 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002561 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002562 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002563 }
2564
2565 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002566 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2567 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002568 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002569 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002570 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002571 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002572 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002573 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002574 }
2575
lucaslinc582d502022-01-27 09:07:00 +08002576 @Override
lucaslind2b06132022-03-02 10:56:57 +08002577 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2578 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2579 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002580 Objects.requireNonNull(nc);
2581 Objects.requireNonNull(packageName);
2582 enforceNetworkStackOrSettingsPermission();
2583 if (!checkAccessPermission(-1 /* pid */, uid)) {
2584 return null;
2585 }
2586 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2587 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2588 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2589 callingAttributionTag);
2590 }
2591
lucaslin69e1aa92022-03-22 18:15:09 +08002592 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2593 if (nc.getUnderlyingNetworks() != null
2594 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2595 nc.setUnderlyingNetworks(null);
2596 }
2597 }
2598
Qingxi Libb8da982020-01-17 17:54:27 -08002599 @VisibleForTesting
2600 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002601 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002602 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2603 // this would be expensive (one more permission check every time any NC callback is
2604 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2605 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2606 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002607 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002608 if (!checkSettingsPermission(callerPid, callerUid)) {
2609 newNc.setUids(null);
2610 newNc.setSSID(null);
2611 }
Etan Cohen107ae952018-12-30 17:59:59 -08002612 if (newNc.getNetworkSpecifier() != null) {
2613 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2614 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002615 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2616 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002617 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2618 newNc.setAdministratorUids(new int[0]);
2619 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002620 if (!checkAnyPermissionOf(mContext,
Benedict Wong53de25f2021-03-24 14:01:51 -07002621 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002622 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002623 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002624 }
lucaslin69e1aa92022-03-22 18:15:09 +08002625 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002626
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002627 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002628 }
2629
Roshan Pius98f59ec2021-02-23 08:47:39 -08002630 /**
2631 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002632 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002633 * NetworkCapabilities.
2634 * Note: This wrapper does not support any sort of invalidation and thus must not be
2635 * persistent or long-lived. It may only be used for the time necessary to
2636 * compute the redactions required by one particular NetworkCallback or
2637 * synchronous call.
2638 */
2639 private class RedactionPermissionChecker {
2640 private final int mCallingPid;
2641 private final int mCallingUid;
2642 @NonNull private final String mCallingPackageName;
2643 @Nullable private final String mCallingAttributionTag;
2644
2645 private Boolean mHasLocationPermission = null;
2646 private Boolean mHasLocalMacAddressPermission = null;
2647 private Boolean mHasSettingsPermission = null;
2648
2649 RedactionPermissionChecker(int callingPid, int callingUid,
2650 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2651 mCallingPid = callingPid;
2652 mCallingUid = callingUid;
2653 mCallingPackageName = callingPackageName;
2654 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002655 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002656
2657 private boolean hasLocationPermissionInternal() {
2658 final long token = Binder.clearCallingIdentity();
2659 try {
2660 return mLocationPermissionChecker.checkLocationPermission(
2661 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2662 null /* message */);
2663 } finally {
2664 Binder.restoreCallingIdentity(token);
2665 }
2666 }
2667
2668 /**
2669 * Returns whether the app holds location permission or not (might return cached result
2670 * if the permission was already checked before).
2671 */
2672 public boolean hasLocationPermission() {
2673 if (mHasLocationPermission == null) {
2674 // If there is no cached result, perform the check now.
2675 mHasLocationPermission = hasLocationPermissionInternal();
2676 }
2677 return mHasLocationPermission;
2678 }
2679
2680 /**
2681 * Returns whether the app holds local mac address permission or not (might return cached
2682 * result if the permission was already checked before).
2683 */
2684 public boolean hasLocalMacAddressPermission() {
2685 if (mHasLocalMacAddressPermission == null) {
2686 // If there is no cached result, perform the check now.
2687 mHasLocalMacAddressPermission =
2688 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2689 }
2690 return mHasLocalMacAddressPermission;
2691 }
2692
2693 /**
2694 * Returns whether the app holds settings permission or not (might return cached
2695 * result if the permission was already checked before).
2696 */
2697 public boolean hasSettingsPermission() {
2698 if (mHasSettingsPermission == null) {
2699 // If there is no cached result, perform the check now.
2700 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2701 }
2702 return mHasSettingsPermission;
2703 }
2704 }
2705
2706 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2707 @NetworkCapabilities.NetCapability long redaction) {
2708 return (redactions & redaction) != 0;
2709 }
2710
2711 /**
2712 * Use the provided |applicableRedactions| to check the receiving app's
2713 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2714 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2715 * before being sent to the corresponding app.
2716 */
2717 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2718 @NetworkCapabilities.RedactionType long applicableRedactions,
2719 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2720 boolean includeLocationSensitiveInfo) {
2721 long redactions = applicableRedactions;
2722 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2723 if (includeLocationSensitiveInfo
2724 && redactionPermissionChecker.hasLocationPermission()) {
2725 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2726 }
2727 }
2728 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2729 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2730 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2731 }
2732 }
2733 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2734 if (redactionPermissionChecker.hasSettingsPermission()) {
2735 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2736 }
2737 }
2738 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002739 }
2740
Qingxi Lib2748102020-01-08 12:51:49 -08002741 @VisibleForTesting
2742 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002743 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002744 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002745 int callingPid, int callingUid, @NonNull String callingPkgName,
2746 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002747 if (nc == null) {
2748 return null;
2749 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002750 // Avoid doing location permission check if the transport info has no location sensitive
2751 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002752 final RedactionPermissionChecker redactionPermissionChecker =
2753 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2754 callingAttributionTag);
2755 final long redactions = retrieveRequiredRedactions(
2756 nc.getApplicableRedactions(), redactionPermissionChecker,
2757 includeLocationSensitiveInfo);
2758 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002759 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002760 // TODO : calling UID is redacted because apps should generally not know what UID is
2761 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002762 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002763 newNc.setOwnerUid(INVALID_UID);
2764 return newNc;
2765 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002766 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2767 if (nc.hasTransport(TRANSPORT_VPN)) {
2768 // Owner UIDs already checked above. No need to re-check.
2769 return newNc;
2770 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002771 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2772 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002773 // compatibility for older apps.
2774 if (!includeLocationSensitiveInfo
2775 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002776 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002777 newNc.setOwnerUid(INVALID_UID);
2778 return newNc;
2779 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002780 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002781 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002782 newNc.setOwnerUid(INVALID_UID);
2783 }
Qingxi Lib2748102020-01-08 12:51:49 -08002784 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002785 }
2786
lucaslinc582d502022-01-27 09:07:00 +08002787 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002788 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2789 LinkProperties lp, int callerPid, int callerUid) {
2790 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002791 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2792 // this would be expensive (one more permission check every time any LP callback is
2793 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2794 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2795 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002796
2797 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2798 final boolean needsSanitization =
2799 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2800 if (!needsSanitization) {
2801 return new LinkProperties(lp);
2802 }
2803
2804 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002805 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002806 }
2807
2808 final LinkProperties newLp = new LinkProperties(lp);
2809 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2810 // object gets parceled.
2811 newLp.setCaptivePortalApiUrl(null);
2812 newLp.setCaptivePortalData(null);
2813 return newLp;
2814 }
2815
Roshan Pius08c94fb2020-01-16 12:17:17 -08002816 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2817 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002818 // There is no need to track the effective UID of the request here. If the caller
2819 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002820 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002821 // Unprivileged apps can only pass in null or their own UID.
2822 if (nc.getUids() == null) {
2823 // If the caller passes in null, the callback will also match networks that do not
2824 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2825 // In this case, redact everything in the request immediately. This ensures that the
2826 // app is not able to get any redacted information by filing an unredacted request
2827 // and observing whether the request matches something.
2828 if (nc.getNetworkSpecifier() != null) {
2829 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2830 }
2831 } else {
2832 nc.setSingleUid(callerUid);
2833 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002834 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002835 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002836 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002837
2838 // Clear owner UID; this can never come from an app.
2839 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002840 }
2841
Chalard Jean38354d12018-03-20 19:13:57 +09002842 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002843 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002844 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2845 }
2846 }
2847
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002848 @Override
2849 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2850 enforceAccessPermission();
2851 final int callerUid = Binder.getCallingUid();
2852 final long token = Binder.clearCallingIdentity();
2853 try {
2854 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2855 } finally {
2856 Binder.restoreCallingIdentity(token);
2857 }
2858 }
2859
junyulaiebd15162021-03-03 12:09:05 +08002860 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002861 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002862 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002863 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002864 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002865
Serik Beketayev05130302021-01-15 16:47:25 -08002866 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002867 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002868 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2869 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002870 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002871 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002872 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002873 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2874 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002875 }
2876 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002877 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002878 }
2879
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002880 @Override
junyulaiebd15162021-03-03 12:09:05 +08002881 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002882 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002883 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002884 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002885
2886 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2887 for (Network network : getAllNetworks()) {
2888 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09002889 final boolean includeNetwork = (nai != null) && nai.isCreated();
2890 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002891 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2892 // NetworkCapabilities, which may contain UIDs of apps to which the
2893 // network applies. Should the UIDs be cleared so as not to leak or
2894 // interfere ?
2895 result.add(nai.getNetworkStateSnapshot());
2896 }
2897 }
2898 return result;
2899 }
2900
2901 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002902 public boolean isActiveNetworkMetered() {
2903 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002904
Qingxi Lib2748102020-01-08 12:51:49 -08002905 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002906 if (caps != null) {
2907 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2908 } else {
2909 // Always return the most conservative value
2910 return true;
2911 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002912 }
2913
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002914 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002915 * Ensures that the system cannot call a particular method.
2916 */
2917 private boolean disallowedBecauseSystemCaller() {
2918 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002919 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2920 // for devices launched with Q and above. However, existing devices upgrading to Q and
2921 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002922 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002923 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002924 log("This method exists only for app backwards compatibility"
2925 + " and must not be called by system services.");
2926 return true;
2927 }
2928 return false;
2929 }
2930
paulhub2c28682021-08-18 18:35:54 +08002931 private int getAppUid(final String app, final UserHandle user) {
2932 final PackageManager pm =
2933 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2934 final long token = Binder.clearCallingIdentity();
2935 try {
2936 return pm.getPackageUid(app, 0 /* flags */);
2937 } catch (PackageManager.NameNotFoundException e) {
2938 return -1;
2939 } finally {
2940 Binder.restoreCallingIdentity(token);
2941 }
2942 }
2943
2944 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2945 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2946 if (getAppUid(packageName, user) != callingUid) {
2947 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2948 }
2949 }
2950
Lorenzo Colitti23862912018-09-28 11:31:55 +09002951 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002952 * Ensure that a network route exists to deliver traffic to the specified
2953 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002954 * @param networkType the type of the network over which traffic to the
2955 * specified host is to be routed
2956 * @param hostAddress the IP address of the host to which the route is
2957 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002958 * @return {@code true} on success, {@code false} on failure
2959 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002960 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002961 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2962 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002963 if (disallowedBecauseSystemCaller()) {
2964 return false;
2965 }
paulhub2c28682021-08-18 18:35:54 +08002966 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002967 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002968 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002969 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002970 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002971
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002972 InetAddress addr;
2973 try {
2974 addr = InetAddress.getByAddress(hostAddress);
2975 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002976 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002977 return false;
2978 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002979
The Android Open Source Project28527d22009-03-03 19:31:44 -08002980 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002981 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002982 return false;
2983 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002984
2985 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2986 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002987 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002988 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2989 } else {
2990 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2991 }
2992 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002993 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002994
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002995 DetailedState netState;
2996 synchronized (nai) {
2997 netState = nai.networkInfo.getDetailedState();
2998 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002999
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003000 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003001 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003002 log("requestRouteToHostAddress on down network "
3003 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003004 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003005 }
3006 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003007 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003008
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003009 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003010 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003011 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003012 LinkProperties lp;
3013 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003014 synchronized (nai) {
3015 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003016 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003017 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003018 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003019 if (DBG) {
3020 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3021 }
Wink Saville32506bc2013-06-29 21:10:57 -07003022 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003023 } finally {
3024 Binder.restoreCallingIdentity(token);
3025 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003026 }
3027
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003028 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003029 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003030 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003031 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003032 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003033 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003034 if (bestRoute.getGateway().equals(addr)) {
3035 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003036 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003037 } else {
3038 // if we will connect to this through another route, add a direct route
3039 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003040 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003041 }
3042 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003043 if (DBG) log("Adding legacy route " + bestRoute +
3044 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003045
3046 final String dst = bestRoute.getDestinationLinkAddress().toString();
3047 final String nextHop = bestRoute.hasGateway()
3048 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003049 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003050 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3051 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003052 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003053 return false;
3054 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003055 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003056 }
3057
paulhu7c0a2e62021-01-08 00:51:49 +08003058 class DnsResolverUnsolicitedEventCallback extends
3059 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003060 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003061 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003062 try {
3063 mHandler.sendMessage(mHandler.obtainMessage(
3064 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003065 new PrivateDnsValidationUpdate(event.netId,
3066 InetAddresses.parseNumericAddress(event.ipAddress),
3067 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003068 } catch (IllegalArgumentException e) {
3069 loge("Error parsing ip address in validation event");
3070 }
3071 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003072
3073 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003074 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3075 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003076 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3077 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3078 // event callback for certain nai. e.g. cellular. Register here to pass to
3079 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003080 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003081 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3082 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003083 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003084 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003085 }
3086 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003087
3088 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003089 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3090 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3091 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003092 }
dalyk1720e542018-03-05 12:42:22 -05003093
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003094 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003095 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003096 return this.VERSION;
3097 }
3098
3099 @Override
3100 public String getInterfaceHash() {
3101 return this.HASH;
3102 }
paulhu7c0a2e62021-01-08 00:51:49 +08003103 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003104
3105 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003106 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3107 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003108
paulhu7c0a2e62021-01-08 00:51:49 +08003109 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003110 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003111 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003112 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003113 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003114 }
3115 }
3116
Sudheer Shanka9967d462021-03-18 19:09:25 +00003117 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003118 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003119 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003120 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3121 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003122 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003123 };
3124
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003125 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003126 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003127 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003128 }
3129
Mark Fasheh7c999d82023-05-04 20:23:11 +00003130 static final class UidFrozenStateChangedArgs {
3131 final int[] mUids;
3132 final int[] mFrozenStates;
3133
3134 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3135 mUids = uids;
3136 mFrozenStates = frozenStates;
3137 }
3138 }
3139
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003140 /**
3141 * Check if the cell network is idle.
3142 * @return true if the cell network state is idle
3143 * false if the cell network state is active or unknown
3144 */
3145 private boolean isCellNetworkIdle() {
3146 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3147 if (defaultNai == null
3148 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3149 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3150 // cell network is not the default network, cell network state is unknown.
3151 // TODO(b/279380356): Track cell network state when the cell is not the default network
3152 return false;
3153 }
3154
3155 return !mNetworkActivityTracker.isDefaultNetworkActive();
3156 }
3157
Mark Fasheh7c999d82023-05-04 20:23:11 +00003158 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003159 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003160
3161 for (int i = 0; i < uids.length; i++) {
3162 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003163 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003164 } else {
3165 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003166 }
3167 }
3168
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003169 if (ownerUids.isEmpty()) {
3170 return;
3171 }
3172
3173 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3174 // Delay closing sockets to avoid waking the cell modem up.
3175 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3176 // than waking cell modem up.
3177 mPendingFrozenUids.addAll(ownerUids);
3178 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003179 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003180 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003181 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003182 loge("Exception in socket destroy: " + e);
3183 }
3184 }
3185 }
3186
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003187 private void closePendingFrozenSockets() {
3188 ensureRunningOnConnectivityServiceThread();
3189
3190 try {
3191 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3192 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3193 loge("Failed to close pending frozen app sockets: " + e);
3194 }
3195 mPendingFrozenUids.clear();
3196 }
3197
3198 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3199 mNetworkActivityTracker.handleReportNetworkActivity(params);
3200
3201 if (mDelayDestroyFrozenSockets
3202 && params.isActive
3203 && params.label == TRANSPORT_CELLULAR
3204 && !mPendingFrozenUids.isEmpty()) {
3205 closePendingFrozenSockets();
3206 }
3207 }
3208
3209 /**
3210 * If the cellular network is no longer the default network, close pending frozen sockets.
3211 *
3212 * @param newNetwork new default network
3213 * @param oldNetwork old default network
3214 */
3215 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3216 NetworkAgentInfo oldNetwork) {
3217 final boolean isOldNetworkCellular = oldNetwork != null
3218 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3219 final boolean isNewNetworkCellular = newNetwork != null
3220 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3221
3222 if (isOldNetworkCellular
3223 && !isNewNetworkCellular
3224 && !mPendingFrozenUids.isEmpty()) {
3225 closePendingFrozenSockets();
3226 }
3227 }
3228
3229 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3230 pw.println("CloseFrozenAppSockets:");
3231 pw.increaseIndent();
3232 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3233 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3234 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3235 pw.decreaseIndent();
3236 }
3237
Mark Fasheh7c999d82023-05-04 20:23:11 +00003238 @VisibleForTesting
3239 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003240 @VisibleForTesting
3241 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3242 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003243
Paul Jensen83f5d572014-08-29 09:54:01 -04003244 private void enforceInternetPermission() {
3245 mContext.enforceCallingOrSelfPermission(
3246 android.Manifest.permission.INTERNET,
3247 "ConnectivityService");
3248 }
3249
The Android Open Source Project28527d22009-03-03 19:31:44 -08003250 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003251 mContext.enforceCallingOrSelfPermission(
3252 android.Manifest.permission.ACCESS_NETWORK_STATE,
3253 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003254 }
3255
lucaslinc582d502022-01-27 09:07:00 +08003256 private boolean checkAccessPermission(int pid, int uid) {
3257 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3258 == PERMISSION_GRANTED;
3259 }
3260
paulhua6ee2122021-02-22 15:40:43 +08003261 /**
3262 * Performs a strict and comprehensive check of whether a calling package is allowed to
3263 * change the state of network, as the condition differs for pre-M, M+, and
3264 * privileged/preinstalled apps. The caller is expected to have either the
3265 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3266 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3267 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3268 * permission and cannot be revoked. See http://b/23597341
3269 *
3270 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3271 * of this app will be updated to the current time.
3272 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003273 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003274 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3275 == PackageManager.PERMISSION_GRANTED) {
3276 return;
3277 }
3278
3279 if (callingPkg == null) {
3280 throw new SecurityException("Calling package name is null.");
3281 }
3282
3283 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3284 final int uid = mDeps.getCallingUid();
3285 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3286 callingPkg, callingAttributionTag, null /* message */);
3287
3288 if (mode == AppOpsManager.MODE_ALLOWED) {
3289 return;
3290 }
3291
3292 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3293 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3294 return;
3295 }
3296
3297 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3298 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3299 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003300 }
3301
Charles He9369e612017-05-15 17:07:18 +01003302 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003303 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003304 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003305 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003306 }
3307
Quang Luong98858d62023-02-11 00:25:24 +00003308 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003309 enforceAnyPermissionOf(mContext,
3310 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003311 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003312 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3313 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3314 }
3315
paulhu8e96a752019-08-12 16:25:11 +08003316 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003317 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003318 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003319 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003320 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003321 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003322 }
3323
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003324 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003325 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003326 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003327 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003328 android.Manifest.permission.NETWORK_SETTINGS,
3329 android.Manifest.permission.NETWORK_FACTORY,
3330 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3331 }
3332
3333 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003334 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003335 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003336 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003337 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3338 android.Manifest.permission.NETWORK_FACTORY,
3339 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3340 }
3341
lucaslin69e1aa92022-03-22 18:15:09 +08003342 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3343 return PERMISSION_GRANTED == mContext.checkPermission(
3344 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3345 || PERMISSION_GRANTED == mContext.checkPermission(
3346 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3347 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003348 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003349 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003350 }
3351
Chalard Jean9a396cc2018-02-21 18:43:54 +09003352 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003353 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003354 android.Manifest.permission.NETWORK_SETTINGS,
3355 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003356 }
3357
3358 private boolean checkSettingsPermission(int pid, int uid) {
3359 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003360 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3361 || PERMISSION_GRANTED == mContext.checkPermission(
3362 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003363 }
3364
paulhu8e96a752019-08-12 16:25:11 +08003365 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003366 enforceNetworkStackPermissionOr(mContext,
3367 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003368 }
3369
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003370 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003371 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003372 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003373 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003374 }
3375
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003376 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003377 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003378 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3379 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003380 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003381 }
3382
James Mattis8378aec2021-01-26 14:05:36 -08003383 private void enforceOemNetworkPreferencesPermission() {
3384 mContext.enforceCallingOrSelfPermission(
3385 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3386 "ConnectivityService");
3387 }
3388
James Mattisfa270db2021-05-31 17:11:10 -07003389 private void enforceManageTestNetworksPermission() {
3390 mContext.enforceCallingOrSelfPermission(
3391 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3392 "ConnectivityService");
3393 }
3394
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003395 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003396 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003397 android.Manifest.permission.NETWORK_STACK,
3398 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003399 }
3400
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003401 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003402 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003403 android.Manifest.permission.NETWORK_STACK,
3404 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3405 }
3406
paulhu1a407652019-03-22 16:35:06 +08003407 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003408 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003409 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003410 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3411 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003412 }
3413
Paul Hu8fc2a552022-05-04 18:44:42 +08003414 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3415 boolean checkUidsAllowedList) {
3416 if (PermissionUtils.checkAnyPermissionOf(mContext,
3417 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3418 return true;
3419 }
3420
3421 // fallback to ConnectivityInternalPermission
3422 // TODO: Remove this fallback check after all apps have declared
3423 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3424 if (PermissionUtils.checkAnyPermissionOf(mContext,
3425 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3426 return true;
3427 }
3428
3429 // Check whether uid is in allowed on restricted networks list.
3430 if (checkUidsAllowedList
3431 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3432 return true;
3433 }
3434 return false;
3435 }
3436
3437 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3438 final int callingUid = mDeps.getCallingUid();
3439 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3440 throw new SecurityException("ConnectivityService: user " + callingUid
3441 + " has no permission to access restricted network.");
3442 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003443 }
3444
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003445 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003446 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003447 }
3448
Roshan Pius98f59ec2021-02-23 08:47:39 -08003449 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3450 return PERMISSION_GRANTED == mContext.checkPermission(
3451 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3452 }
3453
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003454 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003455 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003456 }
3457
3458 private void sendInetConditionBroadcast(NetworkInfo info) {
3459 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3460 }
3461
Wink Saville4f0de1e2011-08-04 15:01:58 -07003462 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003463 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003464 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003465 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003466 if (info.isFailover()) {
3467 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3468 info.setFailover(false);
3469 }
3470 if (info.getReason() != null) {
3471 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3472 }
3473 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003474 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3475 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003476 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003477 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003478 return intent;
3479 }
3480
3481 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3482 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3483 }
3484
Chiachang Wang3bc52762021-11-25 14:17:57 +08003485 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3486 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003487 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003488 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003489 if (!mSystemReady
3490 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003491 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003492 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003493 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003494 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003495 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003496 }
3497
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003498 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003499 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003500 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003501 final NetworkInfo ni = intent.getParcelableExtra(
3502 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003503 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3504 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003505 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003506 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003507 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003508 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003509 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003510 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003511 } finally {
3512 Binder.restoreCallingIdentity(ident);
3513 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003514 }
3515 }
3516
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003517 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3518 NetworkInfo info) {
3519 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003520 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003521
3522 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3523 try {
3524 // This allows us to discard older broadcasts still waiting to be delivered
3525 // which have the same namespace and key.
3526 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3527 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3528 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003529 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003530 } catch (UnsupportedApiLevelException e) {
3531 Log.wtf(TAG, "Using unsupported API" + e);
3532 }
3533 }
3534
3535 @VisibleForTesting
3536 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3537 final StringBuilder sb = new StringBuilder();
3538 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3539 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3540 sb.append(info.getExtraInfo());
3541 return sb.toString();
3542 }
3543
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003544 /**
Aaron Huang96011892020-06-27 07:18:23 +08003545 * Called by SystemServer through ConnectivityManager when the system is ready.
3546 */
3547 @Override
3548 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003549 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003550 throw new SecurityException("Calling Uid is not system uid.");
3551 }
3552 systemReadyInternal();
3553 }
3554
3555 /**
3556 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003557 */
3558 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003559 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003560 // Load flags after PackageManager is ready to query module version
3561 mFlags.loadFlags(mDeps, mContext);
3562
Aaron Huang9a57acf2020-12-08 10:03:29 +08003563 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3564 // listening network request which is sent by MultipathPolicyTracker won't be added
3565 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3566 // be called after PermissionMonitor#startMonitoring().
3567 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3568 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3569 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003570 final ConditionVariable startMonitoringDone = new ConditionVariable();
3571 mHandler.post(() -> {
3572 mPermissionMonitor.startMonitoring();
3573 startMonitoringDone.open();
3574 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003575 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003576 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003577
Hugo Benichie5220992017-04-26 14:53:28 +09003578 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003579 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003580 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003581 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003582 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003583 }
3584 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003585
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003586 // Create network requests for always-on networks.
3587 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003588
3589 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003590 // Note that updating can be skipped here if the list is empty only because no uid
3591 // rules are applied before system ready. Normally, the empty uid list means to clear
3592 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003593 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3594 updateMobileDataPreferredUids();
3595 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003596
3597 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003598 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003599 mBpfNetMaps.setPullAtomCallback(mContext);
3600 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003601 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3602 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003603 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3604 // have permission problem. While CV#block() is unbounded in time and can in principle block
3605 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3606 // could have blocked forever too.
3607 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003608 }
3609
The Android Open Source Project28527d22009-03-03 19:31:44 -08003610 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003611 * Start listening for default data network activity state changes.
3612 */
3613 @Override
3614 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003615 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003616 }
3617
3618 /**
3619 * Stop listening for default data network activity state changes.
3620 */
3621 @Override
3622 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003623 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003624 }
3625
3626 /**
3627 * Check whether the default network radio is currently active.
3628 */
3629 @Override
3630 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003631 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003632 }
3633
3634 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003635 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003636 * and set it on it's iface.
3637 */
Junyu Lai970963e2022-10-25 15:46:47 +08003638 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003639 final String iface = newLp.getInterfaceName();
3640 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003641 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003642 // Silently ignore unset MTU value.
3643 return;
3644 }
Hansen Kurli04252032022-12-07 11:21:49 +00003645 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3646 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3647 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003648 return;
3649 }
Hansen Kurli04252032022-12-07 11:21:49 +00003650 // Cannot set MTU without interface name
3651 if (TextUtils.isEmpty(iface)) {
3652 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003653 return;
3654 }
sy.yun4aa73922013-09-02 05:24:09 +09003655
Hansen Kurli04252032022-12-07 11:21:49 +00003656 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3657 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003658 return;
3659 }
3660
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003661 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003662 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003663 mNetd.interfaceSetMtu(iface, mtu);
3664 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003665 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003666 }
3667 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003668
Chenbo Feng15416292018-11-08 17:36:21 -08003669 @VisibleForTesting
3670 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003671
Junyu Lai970963e2022-10-25 15:46:47 +08003672 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003673 String[] values = null;
3674 if (tcpBufferSizes != null) {
3675 values = tcpBufferSizes.split(",");
3676 }
3677
3678 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003679 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003680 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3681 values = tcpBufferSizes.split(",");
3682 }
3683
3684 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3685
3686 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003687 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003688
Chenbo Feng15416292018-11-08 17:36:21 -08003689 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3690 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3691 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003692 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003693 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003694 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003695 }
3696 }
3697
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003698 @Override
3699 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003700 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003701 NETWORK_RESTORE_DELAY_PROP_NAME);
3702 if(restoreDefaultNetworkDelayStr != null &&
3703 restoreDefaultNetworkDelayStr.length() != 0) {
3704 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003705 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003706 } catch (NumberFormatException e) {
3707 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003708 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003709 // if the system property isn't set, use the value for the apn type
3710 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3711
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003712 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3713 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003714 }
3715 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003716 }
3717
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003718 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003719 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003720 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003721 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003722 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003723 // Start gathering diagnostic information.
3724 netDiags.add(new NetworkDiagnostics(
3725 nai.network,
3726 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003727 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003728 DIAG_TIME_MS));
3729 }
3730
3731 for (NetworkDiagnostics netDiag : netDiags) {
3732 pw.println();
3733 netDiag.waitForMeasurements();
3734 netDiag.dump(pw);
3735 }
3736 }
3737
The Android Open Source Project28527d22009-03-03 19:31:44 -08003738 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003739 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3740 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003741 if (!checkDumpPermission(mContext, TAG, writer)) return;
3742
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003743 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003744 }
3745
lucaslin99473f62020-12-10 15:10:54 +08003746 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3747 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3748 != PackageManager.PERMISSION_GRANTED) {
3749 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003750 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003751 + " due to missing android.permission.DUMP permission");
3752 return false;
3753 } else {
3754 return true;
3755 }
3756 }
3757
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003758 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003759 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003760
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003761 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003762 dumpNetworkDiagnostics(pw);
3763 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003764 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003765 dumpNetworks(pw);
3766 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003767 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003768 dumpNetworkRequests(pw);
3769 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003770 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3771 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3772 dumpTrafficController(pw, fd, verbose);
3773 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003774 }
Erik Kline9647f382015-06-05 17:47:34 +09003775
Junyu Lai0da479b2022-04-20 15:06:29 +08003776 pw.println("NetworkProviders for:");
3777 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003778 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003779 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003780 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003781 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003782 pw.println();
3783
Chalard Jean5b409c72021-02-04 13:12:59 +09003784 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003785 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003786 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003787 pw.println("none");
3788 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003789 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003790 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003791 pw.println();
3792
James Mattis8b298a02021-06-01 22:34:04 -07003793 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003794 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003795 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003796 pw.decreaseIndent();
3797 pw.println();
3798
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003799 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003800 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003801 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003802 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003803 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003804
junyulaif2c67e42018-08-07 19:50:45 +08003805 pw.println("Status for known UIDs:");
3806 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003807 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003808 for (int i = 0; i < size; i++) {
3809 // Don't crash if the array is modified while dumping in bugreports.
3810 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003811 final int uid = mUidBlockedReasons.keyAt(i);
3812 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3813 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003814 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003815 } catch (ArrayIndexOutOfBoundsException e) {
3816 pw.println(" ArrayIndexOutOfBoundsException");
3817 } catch (ConcurrentModificationException e) {
3818 pw.println(" ConcurrentModificationException");
3819 }
3820 }
3821 pw.println();
3822 pw.decreaseIndent();
3823
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003824 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003825 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003826 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003827 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003828 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003829
Junyu Lai0da479b2022-04-20 15:06:29 +08003830 pw.println("Network Offers:");
3831 pw.increaseIndent();
3832 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3833 pw.println(offerInfo.offer);
3834 }
3835 pw.decreaseIndent();
3836 pw.println();
3837
Robert Greenwalt94e22142014-07-30 16:31:24 -07003838 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003839
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003840 pw.println();
markchien5e866652019-09-30 14:40:57 +08003841 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003842
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003843 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003844 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003845
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003846 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003847 dumpCloseFrozenAppSockets(pw);
3848
3849 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003850
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003851 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003852 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003853 pw.println("mNetworkRequestInfoLogs (most recent first):");
3854 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003855 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003856 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003857
3858 pw.println();
3859 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3860 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003861 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003862 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003863
3864 pw.println();
3865 pw.println("NetTransition WakeLock activity (most recent first):");
3866 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003867 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3868 pw.println("total releases: " + mTotalWakelockReleases);
3869 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3870 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3871 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3872 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3873 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3874 }
James Mattiscb1e0362021-04-06 17:07:42 -07003875 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003876
3877 pw.println();
3878 pw.println("bandwidth update requests (by uid):");
3879 pw.increaseIndent();
3880 synchronized (mBandwidthRequests) {
3881 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3882 pw.println("[" + mBandwidthRequests.keyAt(i)
3883 + "]: " + mBandwidthRequests.valueAt(i));
3884 }
3885 }
3886 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003887 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003888
James Mattiscb1e0362021-04-06 17:07:42 -07003889 pw.println();
3890 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3891 pw.increaseIndent();
3892 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003893 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003894 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003895
3896 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003897
3898 pw.println();
3899 pw.println("Permission Monitor:");
3900 pw.increaseIndent();
3901 mPermissionMonitor.dump(pw);
3902 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003903
3904 pw.println();
3905 pw.println("Legacy network activity:");
3906 pw.increaseIndent();
3907 mNetworkActivityTracker.dump(pw);
3908 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003909 }
3910
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003911 private void dumpNetworks(IndentingPrintWriter pw) {
3912 for (NetworkAgentInfo nai : networksSortedById()) {
3913 pw.println(nai.toString());
3914 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003915 pw.println("Nat464Xlat:");
3916 pw.increaseIndent();
3917 nai.dumpNat464Xlat(pw);
3918 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003919 pw.println(String.format(
3920 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3921 nai.numForegroundNetworkRequests(),
3922 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3923 nai.numBackgroundNetworkRequests(),
3924 nai.numNetworkRequests()));
3925 pw.increaseIndent();
3926 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3927 pw.println(nai.requestAt(i).toString());
3928 }
3929 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003930 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003931 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003932 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003933 pw.decreaseIndent();
3934 pw.decreaseIndent();
3935 }
3936 }
3937
James Mattis8b298a02021-06-01 22:34:04 -07003938 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3939 if (!mProfileNetworkPreferences.isEmpty()) {
3940 pw.println("Profile preferences:");
3941 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09003942 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07003943 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003944 }
James Mattis8b298a02021-06-01 22:34:04 -07003945 if (!mOemNetworkPreferences.isEmpty()) {
3946 pw.println("OEM preferences:");
3947 pw.increaseIndent();
3948 pw.println(mOemNetworkPreferences);
3949 pw.decreaseIndent();
3950 }
3951 if (!mMobileDataPreferredUids.isEmpty()) {
3952 pw.println("Mobile data preferred UIDs:");
3953 pw.increaseIndent();
3954 pw.println(mMobileDataPreferredUids);
3955 pw.decreaseIndent();
3956 }
James Mattis45d81842021-01-10 14:24:24 -08003957
James Mattis8b298a02021-06-01 22:34:04 -07003958 pw.println("Default requests:");
3959 pw.increaseIndent();
3960 dumpPerAppDefaultRequests(pw);
3961 pw.decreaseIndent();
3962 }
3963
3964 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003965 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3966 if (mDefaultRequest == defaultRequest) {
3967 continue;
3968 }
3969
James Mattis8b298a02021-06-01 22:34:04 -07003970 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3971 final String networkOutput;
3972 if (null == satisfier) {
3973 networkOutput = "null";
3974 } else if (mNoServiceNetwork.equals(satisfier)) {
3975 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003976 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003977 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003978 }
James Mattis8b298a02021-06-01 22:34:04 -07003979 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3980 ? "" : " asUid: " + defaultRequest.mAsUid;
3981 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3982 + defaultRequest.mPid + asUidString + "]";
3983 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3984 + " Preference order: " + defaultRequest.mPreferenceOrder
3985 + " Tracked UIDs: " + defaultRequest.getUids();
3986 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003987 }
3988 }
3989
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003990 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003991 NetworkRequestInfo[] infos = null;
3992 while (infos == null) {
3993 try {
3994 infos = requestsSortedById();
3995 } catch (ConcurrentModificationException e) {
3996 // mNetworkRequests should only be accessed from handler thread, except dump().
3997 // As dump() is never called in normal usage, it would be needlessly expensive
3998 // to lock the collection only for its benefit. Instead, retry getting the
3999 // requests if ConcurrentModificationException is thrown during dump().
4000 }
4001 }
4002 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004003 pw.println(nri.toString());
4004 }
4005 }
4006
Ken Chene6d511f2022-01-25 11:10:42 +08004007 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4008 boolean verbose) {
4009 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004010 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004011 } catch (ServiceSpecificException e) {
4012 pw.println(e.getMessage());
4013 } catch (IOException e) {
4014 loge("Dump BPF maps failed, " + e);
4015 }
4016 }
4017
Chalard Jean524f0b12021-10-25 21:11:56 +09004018 private void dumpAllRequestInfoLogsToLogcat() {
4019 try (PrintWriter logPw = new PrintWriter(new Writer() {
4020 @Override
4021 public void write(final char[] cbuf, final int off, final int len) {
4022 // This method is called with 0-length and 1-length arrays for empty strings
4023 // or strings containing only the DEL character.
4024 if (len <= 1) return;
4025 Log.e(TAG, new String(cbuf, off, len));
4026 }
4027 @Override public void flush() {}
4028 @Override public void close() {}
4029 })) {
4030 mNetworkRequestInfoLogs.dump(logPw);
4031 }
4032 }
4033
Hugo Benichia480ba52018-09-03 08:19:02 +09004034 /**
4035 * Return an array of all current NetworkAgentInfos sorted by network id.
4036 */
4037 private NetworkAgentInfo[] networksSortedById() {
4038 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004039 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004040 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004041 return networks;
4042 }
4043
4044 /**
4045 * Return an array of all current NetworkRequest sorted by request id.
4046 */
James Mattis258ea3c2020-11-15 15:04:40 -08004047 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004048 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004049 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004050 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004051 // Sort the array based off the NRI containing the min requestId in its requests.
4052 Arrays.sort(requests,
4053 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4054 Comparator.comparingInt(req -> req.requestId)).requestId
4055 )
4056 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004057 return requests;
4058 }
4059
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004060 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004061 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004062 if (officialNai != null && officialNai.equals(nai)) return true;
4063 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004064 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004065 " - " + nai);
4066 }
4067 return false;
4068 }
4069
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004070 private boolean isDisconnectRequest(Message msg) {
4071 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4072 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4073 return info.getState() == NetworkInfo.State.DISCONNECTED;
4074 }
4075
Robert Greenwalt2034b912009-08-12 16:08:25 -07004076 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004077 private class NetworkStateTrackerHandler extends Handler {
4078 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004079 super(looper);
4080 }
4081
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004082 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004083 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4084 final NetworkAgentInfo nai = arg.first;
4085 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004086 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004087 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004088 }
4089 return;
4090 }
4091
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004092 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004093 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004094 return;
4095 }
4096
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004097 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004098 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09004099 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
4100 final NetworkCapabilities sanitized =
4101 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004102 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004103 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004104 break;
4105 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004106 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004107 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004108 processLinkPropertiesFromAgent(nai, newLp);
4109 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004110 break;
4111 }
4112 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004113 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004114 updateNetworkInfo(nai, info);
4115 break;
4116 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004117 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004118 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004119 break;
4120 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004121 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004122 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004123 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004124 // Note that if the NAI had been connected, this would affect the
4125 // score, and therefore would require re-mixing the score and performing
4126 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004127 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004128 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4129 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004130 // Mark the network as temporarily accepting partial connectivity so that it
4131 // will be validated (and possibly become default) even if it only provides
4132 // partial internet access. Note that if user connects to partial connectivity
4133 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4134 // out of wifi coverage) and if the same wifi is available again, the device
4135 // will auto connect to this wifi even though the wifi has "no internet".
4136 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004137 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004138 break;
4139 }
junyulai011b1f12019-01-03 18:50:15 +08004140 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004141 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004142 break;
4143 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004144 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004145 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004146 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004147
4148 if (isLegacyLockdownNai(nai)
4149 && (underlying == null || underlying.size() != 1)) {
4150 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4151 + " must have exactly one underlying network: " + underlying);
4152 }
4153
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004154 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4155 nai.declaredUnderlyingNetworks = (underlying != null)
4156 ? underlying.toArray(new Network[0]) : null;
4157
4158 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4159 if (DBG) {
4160 log(nai.toShortString() + " changed underlying networks to "
4161 + Arrays.toString(nai.declaredUnderlyingNetworks));
4162 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004163 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004164 notifyIfacesChangedForNetworkStats();
4165 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004166 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004167 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004168 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4169 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4170 nai.teardownDelayMs = msg.arg1;
4171 } else {
4172 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4173 }
Chalard Jean550b5212021-03-05 23:07:53 +09004174 break;
4175 }
4176 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4177 nai.setLingerDuration((int) arg.second);
4178 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004179 }
Tyler Wear72388212021-09-09 14:49:02 -07004180 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4181 DscpPolicy policy = (DscpPolicy) arg.second;
4182 if (mDscpPolicyTracker != null) {
4183 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4184 }
4185 break;
4186 }
4187 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4188 if (mDscpPolicyTracker != null) {
4189 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4190 }
4191 break;
4192 }
4193 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4194 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004195 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004196 }
4197 break;
4198 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004199 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004200 if (!nai.everConnected()) {
4201 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4202 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004203 teardownUnneededNetwork(nai);
4204 break;
4205 }
4206
4207 if (nai.isDestroyed()) {
4208 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4209 + ", ignoring");
4210 break;
4211 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004212
4213 final int timeoutMs = (int) arg.second;
4214 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4215 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4216 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4217 }
4218
4219 // Marking a network awaiting replacement is used to ensure that any requests
4220 // satisfied by the network do not switch to another network until a
4221 // replacement is available or the wait for a replacement times out.
4222 // If the network is inactive (i.e., nascent or lingering), then there are no
4223 // such requests, and there is no point keeping it. Just tear it down.
4224 // Note that setLingerDuration(0) cannot be used to do this because the network
4225 // could be nascent.
4226 nai.clearInactivityState();
4227 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4228 Log.d(TAG, nai.toShortString()
4229 + " marked awaiting replacement is unneeded, tearing down instead");
4230 teardownUnneededNetwork(nai);
4231 break;
4232 }
4233
4234 Log.d(TAG, "Marking " + nai.toShortString()
4235 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4236 destroyNativeNetwork(nai);
4237
4238 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4239 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4240 // consider the fact that the network could already have disconnected or been
4241 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4242 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4243 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4244 mKeepaliveTracker.handleStopAllKeepalives(nai,
4245 SocketKeepalive.ERROR_INVALID_NETWORK);
4246
4247 nai.updateScoreForNetworkAgentUpdate();
4248 // This rematch is almost certainly not going to result in any changes, because
4249 // the destroyed flag is only just above the "current satisfier wins"
4250 // tie-breaker. But technically anything that affects scoring should rematch.
4251 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004252 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004253 break;
4254 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004255 }
4256 }
4257
4258 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004259 final int netId = msg.arg2;
4260 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004261 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004262 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004263 switch (msg.what) {
4264 default:
4265 return false;
lucasline117e2e2019-10-22 18:27:33 +08004266 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004267 if (nai == null) {
4268 break;
4269 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004270 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4271 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004272 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004273 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004274 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004275 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004276 if (probePrivateDnsCompleted) {
4277 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4278 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004279 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004280 }
4281 // Only show the notification when the private DNS is broken and the
4282 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004283 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004284 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4285 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004286 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004287 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4288 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4289 // private DNS is broken, it means this network is being reevaluated.
4290 // Either probing private DNS is not necessary any more or it hasn't been
4291 // done yet. In either case, the networkCapabilities should be updated to
4292 // reflect the new status.
4293 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004294 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004295 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004296 }
4297 break;
4298 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004299 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004300 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4301
Erik Kline31b4a9e2018-01-11 21:07:29 +09004302 if (nai == null) break;
4303
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004304 handleNetworkTested(nai, results.mTestResult,
4305 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004306 break;
4307 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004308 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004309 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004310 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004311 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004312 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004313 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004314 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4315 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004316 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004317 if (nai == null) {
4318 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4319 break;
4320 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004321 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004322 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004323 (PendingIntent) msg.obj,
4324 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004325 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004326 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004327 break;
4328 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004329 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004330 if (nai == null) break;
4331
Erik Kline9a62f012018-03-21 07:18:33 -07004332 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004333 break;
4334 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004335 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004336 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004337 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004338 break;
4339 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004340 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004341 return true;
4342 }
4343
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004344 private void handleNetworkTested(
4345 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004346 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4347 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004348 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004349
4350 // If there is any kind of working networking, then the NAI has been evaluated
4351 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4352 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004353 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004354 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004355 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4356 // any callback that receives onAvailable for that rematch receives an extra caps
4357 // callback. To prevent that, update the score in the agent so the updates below won't
4358 // see an update to both caps and score at the same time.
4359 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004360 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4361
he_won.hwang881307a2022-03-15 21:23:52 +09004362 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4363 // Assume the validation failure is due to a temporary failure after roaming
4364 // and ignore it. NetworkMonitor will continue to retry validation. If it
4365 // continues to fail after the block timeout expires, the network will be
4366 // marked unvalidated. If it succeeds, then validation state will not change.
4367 return;
4368 }
4369
Chalard Jean254bd162022-08-25 13:04:51 +09004370 final boolean wasValidated = nai.isValidated();
4371 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004372 final boolean wasPortal = nai.captivePortalDetected();
4373 nai.setPartialConnectivity(partial);
4374 nai.setCaptivePortalDetected(portal);
4375 nai.updateScoreForNetworkAgentUpdate();
4376 final boolean partialConnectivityChanged = (wasPartial != partial);
4377 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004378
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004379 if (DBG) {
4380 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4381 ? " with redirect to " + redirectUrl
4382 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004383 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004384 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004385 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004386 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004387 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004388 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004389 if (valid) {
4390 handleFreshlyValidatedNetwork(nai);
4391 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4392 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004393 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004394 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004395 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004396 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004397 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004398 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004399 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004400 NotificationType.PRIVATE_DNS_BROKEN);
4401 // If network becomes valid, the hasShownBroken should be reset for
4402 // that network so that the notification will be fired when the private
4403 // DNS is broken again.
4404 nai.networkAgentConfig.hasShownBroken = false;
4405 }
4406 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004407 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004408 } else if (portalChanged) {
4409 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
4410 == getCaptivePortalMode()) {
4411 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4412 nai.onPreventAutomaticReconnect();
4413 teardownUnneededNetwork(nai);
4414 return;
4415 } else {
4416 updateCapabilitiesForNetwork(nai);
4417 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004418 } else if (becameEvaluated) {
4419 // If valid or partial connectivity changed, updateCapabilities* has
4420 // done the rematch.
4421 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004422 }
4423 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004424
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004425 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004426 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004427 nai.onValidationStatusChanged(
4428 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4429 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004430
4431 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004432 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004433 // immediately. Re-notify partial connectivity silently if no internet
4434 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004435 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004436 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004437 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4438 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004439 }
4440
Chalard Jean254bd162022-08-25 13:04:51 +09004441 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004442 handleNetworkUnvalidated(nai);
4443 }
4444 }
4445
Calvin Ondada1452016-10-11 15:10:46 -07004446 private int getCaptivePortalMode() {
4447 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004448 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4449 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004450 }
4451
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004452 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4453 switch (msg.what) {
4454 default:
4455 return false;
4456 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4457 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4458 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4459 handleLingerComplete(nai);
4460 }
4461 break;
4462 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004463 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4464 handleNetworkAgentRegistered(msg);
4465 break;
4466 }
4467 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4468 handleNetworkAgentDisconnected(msg);
4469 break;
4470 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004471 }
4472 return true;
4473 }
4474
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004475 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004476 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004477 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004478 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004479 maybeHandleNetworkAgentMessage(msg);
4480 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004481 }
4482 }
4483
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004484 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004485 private final int mNetId;
4486 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004487
4488 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004489 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004490 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004491 }
4492
4493 @Override
4494 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4495 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004496 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004497 }
4498
4499 @Override
4500 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004501 // Legacy version of notifyNetworkTestedWithExtras.
4502 // Would only be called if the system has a NetworkStack module older than the
4503 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004504 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004505 }
4506
4507 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004508 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004509 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4510 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004511 final Message msg = mTrackerHandler.obtainMessage(
4512 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004513 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004514 new NetworkTestedResults(
4515 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004516 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004517
4518 // Invoke ConnectivityReport generation for this Network test event.
4519 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4520 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004521
Cody Kestingf1120be2020-08-03 18:01:40 -07004522 // NetworkMonitor reports the network validation result as a bitmask while
4523 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4524 // logical value for ConnectivityDiagnostics.
4525 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4526 p.result);
4527
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004528 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004529 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004530 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4531 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4532
Aaron Huang959d3642021-01-21 15:47:41 +08004533 ConnectivityReportEvent reportEvent =
4534 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4535 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004536 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004537 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004538 }
4539
4540 @Override
4541 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4542 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4543 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004544 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004545 }
4546
4547 @Override
lucasline117e2e2019-10-22 18:27:33 +08004548 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4549 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4550 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004551 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004552 }
4553
4554 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004555 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4556 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4557 EVENT_CAPPORT_DATA_CHANGED,
4558 0, mNetId, data));
4559 }
4560
4561 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004562 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004563 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004564 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004565
4566 final PendingIntent pendingIntent;
4567 // Only the system server can register notifications with package "android"
4568 final long token = Binder.clearCallingIdentity();
4569 try {
paulhu7746e4e2020-06-09 19:07:03 +08004570 pendingIntent = PendingIntent.getBroadcast(
4571 mContext,
4572 0 /* requestCode */,
4573 intent,
4574 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004575 } finally {
4576 Binder.restoreCallingIdentity(token);
4577 }
4578 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4579 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004580 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004581 }
4582
4583 @Override
4584 public void hideProvisioningNotification() {
4585 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004586 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004587 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004588
4589 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004590 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004591 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004592 }
4593
4594 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004595 public int getInterfaceVersion() {
4596 return this.VERSION;
4597 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004598
4599 @Override
4600 public String getInterfaceHash() {
4601 return this.HASH;
4602 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004603 }
4604
Cody Kestingf1120be2020-08-03 18:01:40 -07004605 /**
4606 * Converts the given NetworkMonitor-specific validation result bitmask to a
4607 * ConnectivityDiagnostics-specific validation result int.
4608 */
4609 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4610 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4611 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4612 }
4613 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4614 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4615 }
4616 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4617 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4618 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4619 }
4620
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004621 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004622 log("Data stall detected with methods: " + p.detectionMethod);
4623
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004624 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004625 int detectionMethod = 0;
4626 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4627 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4628 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4629 }
4630 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4631 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4632 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4633 p.tcpMetricsCollectionPeriodMillis);
4634 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004635 }
4636
Cody Kestingf53a0752020-04-15 12:33:28 -07004637 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004638 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004639 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004640
4641 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4642 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4643 // the cost of going through two handlers.
4644 mConnectivityDiagnosticsHandler.sendMessage(msg);
4645 }
4646
Cody Kestingb37958e2020-05-15 10:36:01 -07004647 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4648 return (p.detectionMethod & detectionMethod) != 0;
4649 }
4650
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004651 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4652 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004653 }
4654
Erik Klinea73af002018-06-26 18:53:43 +09004655 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4656 if (nai == null) return;
4657 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4658 // in order to restart a validation pass from within netd.
4659 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4660 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004661 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004662 }
4663 }
4664
Erik Kline31b4a9e2018-01-11 21:07:29 +09004665 private void handlePrivateDnsSettingsChanged() {
4666 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4667
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004668 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004669 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004670 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004671 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4672 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004673 }
4674 }
4675
Erik Kline9a62f012018-03-21 07:18:33 -07004676 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4677 // Private DNS only ever applies to networks that might provide
4678 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004679 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004680
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004681 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004682 // schedule DNS resolutions. If a DNS resolution is required the
4683 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004684 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004685
4686 // With Private DNS bypass support, we can proceed to update the
4687 // Private DNS config immediately, even if we're in strict mode
4688 // and have not yet resolved the provider name into a set of IPs.
4689 updatePrivateDns(nai, cfg);
4690 }
4691
4692 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4693 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004694 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004695 }
4696
dalyk1720e542018-03-05 12:42:22 -05004697 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4698 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4699 if (nai == null) {
4700 return;
4701 }
4702 mDnsManager.updatePrivateDnsValidation(update);
4703 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4704 }
4705
paulhu7c0a2e62021-01-08 00:51:49 +08004706 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004707 int prefixLength) {
4708 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4709 if (nai == null) return;
4710
paulhu7c0a2e62021-01-08 00:51:49 +08004711 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4712 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004713
4714 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004715 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004716 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004717 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004718 prefixLength);
4719 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004720 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004721 return;
4722 }
4723 }
4724
Lorenzo Colittid523d142020-04-01 20:16:30 +09004725 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004726 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4727 }
4728
Hai Shalome58bdc62021-01-11 18:45:34 -08004729 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004730 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004731 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004732 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4733 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4734 }
4735
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004736 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004737 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004738 * @param nai the agent info to update
4739 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004740 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004741 */
junyulai2b6f0c22021-02-03 20:15:30 +08004742 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4743 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4744 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004745 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004746 // one lingered request, set inactive.
4747 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004748 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004749 if (DBG) log("Unsetting inactive " + nai.toShortString());
4750 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004751 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004752 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004753 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004754 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4755 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004756 }
junyulai2b6f0c22021-02-03 20:15:30 +08004757 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004758 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004759 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004760 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004761 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004762 }
4763
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004764 private void handleNetworkAgentRegistered(Message msg) {
4765 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4766 if (!mNetworkAgentInfos.contains(nai)) {
4767 return;
4768 }
4769
4770 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4771 if (VDBG) log("NetworkAgent registered");
4772 } else {
4773 loge("Error connecting NetworkAgent");
4774 mNetworkAgentInfos.remove(nai);
4775 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004776 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004777 synchronized (mNetworkForNetId) {
4778 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004779 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004780 mNetIdManager.releaseNetId(nai.network.getNetId());
4781 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004782 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004783 }
4784 }
4785 }
Paul Jensend5f53392014-11-25 15:26:53 -05004786
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004787 @VisibleForTesting
4788 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09004789 // The feature of creating the networks immediately was slated for U, but race conditions
4790 // detected late required this was flagged off.
4791 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
4792 // in NetworkAgentTest.
4793 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004794 }
4795
4796 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4797 @NonNull NetworkInfo.State state) {
4798 if (nai.isCreated()) return false;
4799 if (state == NetworkInfo.State.CONNECTED) return true;
4800 if (state != NetworkInfo.State.CONNECTING) {
4801 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09004802 if (shouldCreateNetworksImmediately()) {
4803 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4804 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004805 return false;
4806 }
4807 return nai.isVPN() || shouldCreateNetworksImmediately();
4808 }
4809
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004810 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004811 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004812 }
4813
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004814 @VisibleForTesting
4815 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004816 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09004817 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004818
4819 // If the network never roamed, return false. The check below is not sufficient if time
4820 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4821 if (nai.lastRoamTime == 0) return false;
4822
he_won.hwang881307a2022-03-15 21:23:52 +09004823 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4824 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004825 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004826 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004827 final long currentTimeMs = SystemClock.elapsedRealtime();
4828 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004829 if (timeSinceLastRoam <= blockTimeOut) {
4830 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4831 return true;
4832 }
4833 }
4834 return false;
4835 }
4836
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004837 private void handleNetworkAgentDisconnected(Message msg) {
4838 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004839 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004840 }
4841
Chalard Jeand9fffc32018-05-11 20:19:20 +09004842 // Destroys a network, remove references to it from the internal state managed by
4843 // ConnectivityService, free its interfaces and clean up.
4844 // Must be called on the Handler thread.
4845 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004846 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004847
4848 if (!mNetworkAgentInfos.contains(nai)) return;
4849
Chalard Jeand9fffc32018-05-11 20:19:20 +09004850 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004851 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004852 }
lucaslinb25c9a62019-02-12 15:30:13 +08004853 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004854 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004855 // A network agent has disconnected.
4856 // TODO - if we move the logic to the network agent (have them disconnect
4857 // because they lost all their requests or because their score isn't good)
4858 // then they would disconnect organically, report their new state and then
4859 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08004860 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004861 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4862 null, null);
4863 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004864 final boolean wasDefault = isDefaultNetwork(nai);
4865 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004866 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004867 }
4868 notifyIfacesChangedForNetworkStats();
4869 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4870 // by other networks that are already connected. Perhaps that can be done by
4871 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4872 // of rematchAllNetworksAndRequests
4873 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004874 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004875
4876 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004877 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4878 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08004879 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004880 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004881 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004882 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004883 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004884 synchronized (mNetworkForNetId) {
4885 // Remove the NetworkAgent, but don't mark the netId as
4886 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004887 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004888 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004889 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08004890 // Update allowed network lists in netd. This should be called after removing nai
4891 // from mNetworkAgentInfos.
4892 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004893 // Remove all previously satisfied requests.
4894 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004895 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004896 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004897 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004898 if (currentNetwork != null
4899 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004900 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004901 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4902 // rematch not to keep disconnected agents instead of setting it here ; this
4903 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004904 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004905 for (final NetworkOfferInfo noi : mNetworkOffers) {
4906 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004907 }
James Mattise3ef1912020-12-20 11:09:58 -08004908
Chalard Jean5b409c72021-02-04 13:12:59 +09004909 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004910 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004911 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004912 // network, because while incorrect this is the closest to the old (also
4913 // incorrect) behavior.
4914 mNetworkActivityTracker.updateDataActivityTracking(
4915 null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004916 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004917 ensureNetworkTransitionWakelock(nai.toShortString());
4918 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004919 }
4920 }
junyulai2b6f0c22021-02-03 20:15:30 +08004921 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004922 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004923 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004924 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004925 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004926 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004927 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004928
Aaron Huang9fe47be2021-06-08 13:11:45 +08004929 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
4930 // The obvious place to do this would be in makeDefault(), however makeDefault() is
4931 // not called by the rematch in this case. This is because the code above unset
4932 // this network from the default request's satisfier, and that is what the rematch
4933 // is using as its source data to know what the old satisfier was. So as far as the
4934 // rematch above is concerned, the old default network was null.
4935 // Therefore if there is no new default, the default network was null and is still
4936 // null, thus there was no change so makeDefault() is not called. So if the old
4937 // network had a proxy and there is no new default, the proxy tracker should be told
4938 // that there is no longer a default proxy.
4939 // Strictly speaking this is not essential because having a proxy setting when
4940 // there is no network is harmless, but it's still counter-intuitive so reset to null.
4941 mProxyTracker.setDefaultProxy(null);
4942 }
4943
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004944 // Immediate teardown.
4945 if (nai.teardownDelayMs == 0) {
4946 destroyNetwork(nai);
4947 return;
4948 }
4949
4950 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004951 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304952 try {
4953 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4954 } catch (RemoteException e) {
4955 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4956 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004957 }
4958 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4959 }
4960
4961 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004962 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004963 // Tell netd to clean up the configuration for this network
4964 // (routing rules, DNS, etc).
4965 // This may be slow as it requires a lot of netd shelling out to ip and
4966 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004967 // after we've rematched networks with requests (which might change the default
4968 // network or service a new request from an app), so network traffic isn't interrupted
4969 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004970 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004971 }
Chalard Jeandf29a852023-05-29 17:02:43 +09004972 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004973 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4974 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4975 // false if the network was never created.
4976 // TODO: delete when S is no longer supported.
4977 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004978 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004979 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004980 }
4981
Ken Chen6df7a902021-04-09 15:08:42 +08004982 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004983 try {
4984 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004985 final NativeNetworkConfig config;
4986 if (nai.isVPN()) {
4987 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004988 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004989 return false;
4990 }
4991 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4992 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004993 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08004994 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004995 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004996 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004997 getNetworkPermission(nai.networkCapabilities),
4998 false /* secure */,
4999 VpnManager.TYPE_VPN_NONE,
5000 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005001 }
Ken Chen6df7a902021-04-09 15:08:42 +08005002 mNetd.networkCreate(config);
5003 mDnsResolver.createNetworkCache(nai.network.getNetId());
5004 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
5005 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08005006 return true;
5007 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005008 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005009 return false;
5010 }
5011 }
5012
Ken Chen6df7a902021-04-09 15:08:42 +08005013 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005014 if (mDscpPolicyTracker != null) {
5015 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5016 }
Luke Huangfdd11f82019-04-09 18:41:49 +08005017 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005018 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005019 } catch (RemoteException | ServiceSpecificException e) {
5020 loge("Exception destroying network(networkDestroy): " + e);
5021 }
5022 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005023 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005024 } catch (RemoteException | ServiceSpecificException e) {
5025 loge("Exception destroying network: " + e);
5026 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005027 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5028 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5029 // gets created, could add data to DnsManager data structures that will never get deleted.
5030 mDnsManager.removeNetwork(nai.network);
5031
5032 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005033 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005034 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5035 }
5036
Chalard Jean254bd162022-08-25 13:04:51 +09005037 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005038 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005039 }
5040
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005041 // If this method proves to be too slow then we can maintain a separate
5042 // pendingIntent => NetworkRequestInfo map.
5043 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5044 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005045 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5046 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5047 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005048 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005049 return entry.getValue();
5050 }
5051 }
5052 return null;
5053 }
5054
Chalard Jean524f0b12021-10-25 21:11:56 +09005055 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005056 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005057 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5058 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5059 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5060 // bug is fixed.
5061 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005062 throw new IllegalStateException("This NRI is already registered. New : " + nri
5063 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005064 }
5065 }
5066 }
5067 }
5068
Chalard Jeanac9ace02022-01-26 16:54:05 +09005069 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5070 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005071 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09005072 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
5073 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005074 }
5075 return false;
5076 }
5077
James Mattisf7027322020-12-13 16:28:14 -08005078 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005079 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005080 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5081 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5082 final NetworkRequestInfo existingRequest =
5083 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005084 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005085 if (DBG) {
5086 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5087 + nri.mRequests.get(0) + " because their intents matched.");
5088 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005089 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005090 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005091 }
Erik Kline05f2b402015-04-30 12:58:40 +09005092 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005093 }
5094
James Mattisf7027322020-12-13 16:28:14 -08005095 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005096 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005097 }
5098
James Mattis3ce3d3c2021-02-09 18:18:28 -08005099 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005100 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005101 for (final NetworkRequestInfo nri : nris) {
5102 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005103 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005104 for (final NetworkRequest req : nri.mRequests) {
5105 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005106 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005107 if (req.isListen()) {
5108 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5109 if (req.networkCapabilities.hasSignalStrength()
5110 && network.satisfiesImmutableCapabilitiesOf(req)) {
5111 updateSignalStrengthThresholds(network, "REGISTER", req);
5112 }
James Mattisf7027322020-12-13 16:28:14 -08005113 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005114 }
5115 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005116
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005117 // If this NRI has a satisfier already, it is replacing an older request that
5118 // has been removed. Track it.
5119 final NetworkRequest activeRequest = nri.getActiveRequest();
5120 if (null != activeRequest) {
5121 // If there is an active request, then for sure there is a satisfier.
5122 nri.getSatisfier().addRequest(activeRequest);
5123 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005124 }
James Mattisf7027322020-12-13 16:28:14 -08005125
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005126 if (mFlags.noRematchAllRequestsOnRegister()) {
5127 rematchNetworksAndRequests(nris);
5128 } else {
5129 rematchAllNetworksAndRequests();
5130 }
James Mattis45d81842021-01-10 14:24:24 -08005131
Chalard Jean0354d8c2021-01-12 10:58:56 +09005132 // Requests that have not been matched to a network will not have been sent to the
5133 // providers, because the old satisfier and the new satisfier are the same (null in this
5134 // case). Send these requests to the providers.
5135 for (final NetworkRequestInfo nri : nris) {
5136 for (final NetworkOfferInfo noi : mNetworkOffers) {
5137 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005138 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005139 }
5140 }
5141
James Mattisf7027322020-12-13 16:28:14 -08005142 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5143 final int callingUid) {
5144 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005145 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005146 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5147 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5148 handleReleaseNetworkRequest(
5149 nri.mRequests.get(0),
5150 callingUid,
5151 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005152 }
5153 }
5154
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005155 // Determines whether the network is the best (or could become the best, if it validated), for
5156 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5157 // on the value of reason:
5158 //
5159 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5160 // then it should be torn down.
5161 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5162 // then it should be lingered.
5163 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005164 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005165
Chalard Jean254bd162022-08-25 13:04:51 +09005166 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005167 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5168 return false;
5169 }
5170
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005171 final int numRequests;
5172 switch (reason) {
5173 case TEARDOWN:
5174 numRequests = nai.numRequestNetworkRequests();
5175 break;
5176 case LINGER:
5177 numRequests = nai.numForegroundNetworkRequests();
5178 break;
5179 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005180 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005181 return true;
5182 }
5183
Chalard Jean947acd42021-03-08 22:29:27 +09005184 if (numRequests > 0) return false;
5185
Paul Jensende49eb12015-06-25 15:30:08 -04005186 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005187 if (reason == UnneededFor.LINGER
5188 && !nri.isMultilayerRequest()
5189 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005190 // Background requests don't affect lingering.
5191 continue;
5192 }
5193
James Mattis3d229892020-11-16 16:46:28 -08005194 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005195 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005196 }
5197 }
Paul Jensende49eb12015-06-25 15:30:08 -04005198 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005199 }
5200
James Mattis3d229892020-11-16 16:46:28 -08005201 private boolean isNetworkPotentialSatisfier(
5202 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
5203 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005204 // request, return immediately. For multilayer requests, check to see if any of the
5205 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005206 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5207 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005208 return false;
5209 }
5210 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005211 // This multilayer listen request is satisfied therefore no further requests need to be
5212 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005213 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005214 return false;
5215 }
James Mattis3d229892020-11-16 16:46:28 -08005216 // As non-multilayer listen requests have already returned, the below would only happen
5217 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005218 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005219 continue;
5220 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09005221 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08005222 // there is hope for it to become one if it validated, then it is needed.
5223 if (candidate.satisfies(req)) {
5224 // As soon as a network is found that satisfies a request, return. Specifically for
5225 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5226 // is important so as to not evaluate lower priority requests further in
5227 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005228 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5229 ? nri.getSatisfier() : null;
5230 // Note that this catches two important cases:
5231 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5232 // is currently satisfying the request. This is desirable when
5233 // cellular ends up validating but WiFi does not.
5234 // 2. Unvalidated WiFi will not be reaped when validated cellular
5235 // is currently satisfying the request. This is desirable when
5236 // WiFi ends up validating and out scoring cellular.
5237 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005238 }
5239 }
5240
5241 return false;
5242 }
5243
Erik Kline0c04b742016-07-07 16:50:58 +09005244 private NetworkRequestInfo getNriForAppRequest(
5245 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005246 // Looking up the app passed param request in mRequests isn't possible since it may return
5247 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5248 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005249 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5250 // to avoid potential race conditions when validating a package->uid mapping when sending
5251 // the callback on the very low-chance that an application shuts down prior to the callback
5252 // being sent.
5253 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5254 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005255
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005256 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005257 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005258 log(String.format("UID %d attempted to %s for unowned request %s",
5259 callingUid, requestedOperation, nri));
5260 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005261 }
Erik Kline0c04b742016-07-07 16:50:58 +09005262 }
5263
5264 return nri;
5265 }
5266
James Mattisf7027322020-12-13 16:28:14 -08005267 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5268 final String callingMethod) {
5269 if (nri.isMultilayerRequest()) {
5270 throw new IllegalStateException(
5271 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005272 }
5273 }
5274
James Mattisf7027322020-12-13 16:28:14 -08005275 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005276 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005277 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5278 // single NetworkRequest and thus does not apply to multilayer requests.
5279 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5280 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005281 return;
5282 }
James Mattis2516da32021-01-31 17:06:19 -08005283 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005284 return;
5285 }
James Mattisf7027322020-12-13 16:28:14 -08005286 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5287 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005288 }
5289 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005290 callCallbackForRequest(
5291 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005292 }
5293
James Mattisf7027322020-12-13 16:28:14 -08005294 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5295 final int callingUid,
5296 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005297 final NetworkRequestInfo nri =
5298 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5299 if (nri == null) {
5300 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005301 }
James Mattisf7027322020-12-13 16:28:14 -08005302 if (VDBG || (DBG && request.isRequest())) {
5303 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005304 }
5305 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005306 if (callOnUnavailable) {
5307 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5308 }
Erik Kline155a59a2015-11-25 12:49:38 +09005309 }
Erik Kline0c04b742016-07-07 16:50:58 +09005310
James Mattisa076c532020-12-02 14:12:41 -08005311 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005312 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005313 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005314 if (null == mNetworkRequests.remove(req)) {
5315 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5316 continue;
5317 }
James Mattisa076c532020-12-02 14:12:41 -08005318 if (req.isListen()) {
5319 removeListenRequestFromNetworks(req);
5320 }
5321 }
James Mattis8f036802021-06-20 16:26:01 -07005322 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005323 if (mDefaultNetworkRequests.remove(nri)) {
5324 // If this request was one of the defaults, then the UID rules need to be updated
5325 // WARNING : if the app(s) for which this network request is the default are doing
5326 // traffic, this will kill their connected sockets, even if an equivalent request
5327 // is going to be reinstated right away ; unconnected traffic will go on the default
5328 // until the new default is set, which will happen very soon.
5329 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5330 // remove ranges for those requests that won't have a replacement
5331 final NetworkAgentInfo satisfier = nri.getSatisfier();
5332 if (null != satisfier) {
5333 try {
paulhu0e79d952021-06-09 16:11:35 +08005334 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5335 satisfier.network.getNetId(),
5336 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005337 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005338 } catch (RemoteException e) {
5339 loge("Exception setting network preference default network", e);
5340 }
5341 }
5342 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005343
Junyu Lai00d92df2022-07-05 11:01:52 +08005344 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005345 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005346 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005347
5348 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005349 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005350 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005351 }
5352 }
5353
Chalard Jean0354d8c2021-01-12 10:58:56 +09005354 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5355 // needed for this offer.
5356 for (final NetworkOfferInfo noi : mNetworkOffers) {
5357 for (final NetworkRequest req : nri.mRequests) {
5358 if (req.isRequest() && noi.offer.neededFor(req)) {
5359 noi.offer.onNetworkUnneeded(req);
5360 }
5361 }
5362 }
James Mattisa076c532020-12-02 14:12:41 -08005363 }
5364
James Mattis3ce3d3c2021-02-09 18:18:28 -08005365 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5366 for (final NetworkRequestInfo nri : nris) {
5367 if (mDefaultRequest == nri) {
5368 // Make sure we never remove the default request.
5369 continue;
5370 }
5371 handleRemoveNetworkRequest(nri);
5372 }
5373 }
5374
James Mattisa076c532020-12-02 14:12:41 -08005375 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5376 // listens don't have a singular affected Network. Check all networks to see
5377 // if this listen request applies and remove it.
5378 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5379 nai.removeRequest(req.requestId);
5380 if (req.networkCapabilities.hasSignalStrength()
5381 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5382 updateSignalStrengthThresholds(nai, "RELEASE", req);
5383 }
5384 }
5385 }
5386
5387 /**
5388 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5389 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5390 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5391 */
5392 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5393 boolean wasKept = false;
5394 final NetworkAgentInfo nai = nri.getSatisfier();
5395 if (nai != null) {
5396 final int requestLegacyType = nri.getActiveRequest().legacyType;
5397 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5398 nai.removeRequest(nri.getActiveRequest().requestId);
5399 if (VDBG || DDBG) {
5400 log(" Removing from current network " + nai.toShortString()
5401 + ", leaving " + nai.numNetworkRequests() + " requests.");
5402 }
5403 // If there are still lingered requests on this network, don't tear it down,
5404 // but resume lingering instead.
5405 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005406 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005407 notifyNetworkLosing(nai, now);
5408 }
5409 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5410 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5411 teardownUnneededNetwork(nai);
5412 } else {
5413 wasKept = true;
5414 }
James Mattisa076c532020-12-02 14:12:41 -08005415 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5416 // Went from foreground to background.
5417 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005418 }
5419
Erik Kline0c04b742016-07-07 16:50:58 +09005420 // Maintain the illusion. When this request arrived, we might have pretended
5421 // that a network connected to serve it, even though the network was already
5422 // connected. Now that this request has gone away, we might have to pretend
5423 // that the network disconnected. LegacyTypeTracker will generate that
5424 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005425 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005426 boolean doRemove = true;
5427 if (wasKept) {
5428 // check if any of the remaining requests for this network are for the
5429 // same legacy type - if so, don't remove the nai
5430 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5431 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005432 if (otherRequest.legacyType == requestLegacyType
5433 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005434 if (DBG) log(" still have other legacy request - leaving");
5435 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005436 }
5437 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005438 }
5439
Erik Kline0c04b742016-07-07 16:50:58 +09005440 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005441 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005442 }
5443 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005444 }
5445 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005446
Junyu Lai00d92df2022-07-05 11:01:52 +08005447 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005448 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005449 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5450 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5451 }
5452
Lorenzo Colittid6459092016-07-04 12:55:44 +09005453 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005454 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005455 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005456 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005457 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005458 }
5459
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005460 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005461 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5462 enforceNetworkStackSettingsOrSetup();
5463 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5464 encodeBool(accept), encodeBool(always), network));
5465 }
5466
5467 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005468 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005469 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005470 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5471 }
5472
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005473 @Override
5474 public void setTestAllowBadWifiUntil(long timeMs) {
5475 enforceSettingsPermission();
5476 if (!Build.isDebuggable()) {
5477 throw new IllegalStateException("Does not support in non-debuggable build");
5478 }
5479
5480 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5481 throw new IllegalArgumentException("It should not exceed "
5482 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5483 }
5484
5485 mHandler.sendMessage(
5486 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5487 }
5488
chiachangwange0192a72023-02-06 13:25:01 +00005489 @Override
5490 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5491 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005492
5493 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5494 throw new IllegalArgumentException("Argument should not exceed "
5495 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5496 }
5497
5498 mHandler.sendMessage(
5499 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5500 }
5501
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005502 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5503 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5504 " accept=" + accept + " always=" + always);
5505
5506 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5507 if (nai == null) {
5508 // Nothing to do.
5509 return;
5510 }
5511
Chalard Jean254bd162022-08-25 13:04:51 +09005512 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005513 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005514 return;
5515 }
5516
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005517 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005518 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005519 }
5520
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005521 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5522 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005523 // If network becomes partial connectivity and user already accepted to use this
5524 // network, we should respect the user's option and don't need to popup the
5525 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005526 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005527 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005528 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005529 }
5530
5531 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005532 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005533 }
5534
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005535 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005536 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005537 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005538 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005539 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005540 }
5541
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005542 }
5543
lucaslin2240ef62019-03-12 13:08:03 +08005544 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5545 boolean always) {
5546 if (DBG) {
5547 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5548 + " always=" + always);
5549 }
5550
5551 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5552 if (nai == null) {
5553 // Nothing to do.
5554 return;
5555 }
5556
Chalard Jean254bd162022-08-25 13:04:51 +09005557 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005558 // The network validated while the dialog box was up. Take no action.
5559 return;
5560 }
5561
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005562 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5563 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005564 }
5565
5566 // TODO: Use the current design or save the user choice into IpMemoryStore.
5567 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005568 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005569 }
5570
5571 if (!accept) {
5572 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005573 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005574 // Tear down the network.
5575 teardownUnneededNetwork(nai);
5576 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005577 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5578 // result in a partial connectivity result which will be processed by
5579 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005580 //
5581 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5582 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005583 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005584 }
5585 }
5586
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005587 private void handleSetAvoidUnvalidated(Network network) {
5588 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005589 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005590 // Nothing to do. The network either disconnected or revalidated.
5591 return;
5592 }
Chalard Jean254bd162022-08-25 13:04:51 +09005593 if (0L == nai.getAvoidUnvalidated()) {
5594 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005595 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005596 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005597 }
5598 }
5599
Chalard Jean5fb43c72022-09-08 19:03:14 +09005600 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005601 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005602 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005603 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005604 }
5605
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005606 @Override
5607 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005608 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005609 mHandler.post(() -> {
5610 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5611 if (nai == null) return;
5612 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005613 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005614 });
5615 }
5616
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005617 /**
5618 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5619 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005620 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005621 * @param appExtras Bundle to use as intent extras for the captive portal application.
5622 * Must be treated as opaque to avoid preventing the captive portal app to
5623 * update its arguments.
5624 */
5625 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005626 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005627 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5628 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005629
5630 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5631 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005632 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5633 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005634 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5635
lucaslin75ff7022020-12-17 04:14:35 +08005636 final long token = Binder.clearCallingIdentity();
5637 try {
5638 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5639 } finally {
5640 Binder.restoreCallingIdentity(token);
5641 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005642 }
5643
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005644 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5645 private final Network mNetwork;
5646
5647 private CaptivePortalImpl(Network network) {
5648 mNetwork = network;
5649 }
5650
5651 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005652 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005653 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5654 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005655 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5656 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5657 // Since the network will be disconnected, skip notifying NetworkMonitor
5658 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005659 }
5660
Chiachang Wang938bfba2020-01-09 13:50:55 +08005661 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005662 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005663 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005664 }
5665
5666 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005667 public void appRequest(final int request) {
5668 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5669 if (nm == null) return;
5670
5671 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005672 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005673 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005674 }
5675 }
5676
5677 @Nullable
5678 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5679 // getNetworkAgentInfoForNetwork is thread-safe
5680 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5681 if (nai == null) return null;
5682
5683 // nai.networkMonitor() is thread-safe
5684 return nai.networkMonitor();
5685 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005686 }
5687
Hugo Benichic9048bc2016-09-14 23:23:08 +00005688 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005689 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005690 }
5691
Chalard Jean020b93a2022-09-01 13:20:14 +09005692 private boolean activelyPreferBadWifi() {
5693 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5694 }
5695
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005696 /**
5697 * Return whether the device should maintain continuous, working connectivity by switching away
5698 * from WiFi networks having no connectivity.
5699 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5700 */
5701 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005702 if (!checkNetworkStackPermission()) {
5703 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5704 }
5705 return avoidBadWifi();
5706 }
5707
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005708 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005709 ensureRunningOnConnectivityServiceThread();
5710 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005711 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005712 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005713 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005714 if (avoidBadWifi) {
5715 // If the device is now avoiding bad wifi, remove notifications that might have
5716 // been put up when the device didn't.
5717 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5718 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005719 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005720 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5721 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5722 for (final NetworkOfferInfo noi : offersToUpdate) {
5723 updateOfferScore(noi.offer);
5724 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005725 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005726 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005727 }
5728
Erik Kline95ecfee2016-10-02 18:02:14 +09005729 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005730 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005731 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005732 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005733 if (!configRestrict) {
5734 pw.println("Bad Wi-Fi avoidance: unrestricted");
5735 return;
5736 }
5737
5738 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5739 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005740 pw.println("Config restrict: " + configRestrict);
5741 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005742
Chalard Jeane0fdea32022-09-14 21:44:22 +09005743 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005744 String description;
5745 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005746 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005747 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005748 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005749 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005750 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005751 description = "avoid";
5752 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005753 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005754 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005755 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005756
5757 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5758 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005759 if (null == configValue) {
5760 description = "unset";
5761 } else if (configValue) {
5762 description = "force true";
5763 } else {
5764 description = "force false";
5765 }
5766 pw.println("Actively prefer bad wifi conf: " + description);
5767 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005768 pw.println("Network overrides:");
5769 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005770 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005771 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005772 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005773 }
5774 }
5775 pw.decreaseIndent();
5776 pw.decreaseIndent();
5777 }
5778
paulhu7746e4e2020-06-09 19:07:03 +08005779 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5780 // unify the method.
5781 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5782 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5783 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5784 return settingsComponent != null
5785 ? settingsComponent.getPackageName() : "com.android.settings";
5786 }
5787
lucaslinb1e8e382019-01-24 15:55:30 +08005788 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005789 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005790 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005791 switch (type) {
5792 case NO_INTERNET:
5793 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005794 // High priority because it is only displayed for explicitly selected networks.
5795 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005796 break;
lucasline117e2e2019-10-22 18:27:33 +08005797 case PRIVATE_DNS_BROKEN:
5798 action = Settings.ACTION_WIRELESS_SETTINGS;
5799 // High priority because we should let user know why there is no internet.
5800 highPriority = true;
5801 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005802 case LOST_INTERNET:
5803 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005804 // High priority because it could help the user avoid unexpected data usage.
5805 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005806 break;
lucaslin2240ef62019-03-12 13:08:03 +08005807 case PARTIAL_CONNECTIVITY:
5808 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005809 // Don't bother the user with a high-priority notification if the network was not
5810 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005811 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005812 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005813 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005814 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005815 return;
5816 }
5817
5818 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005819 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005820 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005821 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005822 // Some OEMs have their own Settings package. Thus, need to get the current using
5823 // Settings package name instead of just use default name "com.android.settings".
5824 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5825 intent.setClassName(settingsPkgName,
5826 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005827 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005828
paulhu2af50222020-10-11 22:52:27 +08005829 PendingIntent pendingIntent = PendingIntent.getActivity(
5830 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005831 0 /* requestCode */,
5832 intent,
paulhu2af50222020-10-11 22:52:27 +08005833 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005834
Serik Beketayevec8ad212020-12-07 22:43:07 -08005835 mNotifier.showNotification(
5836 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005837 }
5838
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005839 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5840 // Don't prompt if the network is validated, and don't prompt on captive portals
5841 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005842 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005843 return false;
5844 }
5845
5846 // If a network has partial connectivity, always prompt unless the user has already accepted
5847 // partial connectivity and selected don't ask again. This ensures that if the device
5848 // automatically connects to a network that has partial Internet access, the user will
5849 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005850 // because we have prompted them.
5851 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005852 return true;
5853 }
5854
5855 // If a network has no Internet access, only prompt if the network was explicitly selected
5856 // and if the user has not already told us to use the network regardless of whether it
5857 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005858 if (nai.networkAgentConfig.explicitlySelected
5859 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005860 return true;
5861 }
5862
5863 return false;
5864 }
5865
Chalard Jean5fb43c72022-09-08 19:03:14 +09005866 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5867 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005868
Chalard Jean5fb43c72022-09-08 19:03:14 +09005869 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5870 if (null == nai) return;
5871
5872 if (nai.setEvaluated()) {
5873 // If setEvaluated() returned true, the network never had any form of connectivity.
5874 // This may have an impact on request matching if bad WiFi avoidance is off and the
5875 // network was found not to have Internet access.
5876 nai.updateScoreForNetworkAgentUpdate();
5877 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005878
5879 // Also, if this is WiFi and it should be preferred actively, now is the time to
5880 // prompt the user that they walked past and connected to a bad WiFi.
5881 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5882 && !avoidBadWifi()
5883 && activelyPreferBadWifi()) {
5884 // The notification will be removed if the network validates or disconnects.
5885 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5886 return;
5887 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005888 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005889
Chalard Jean5fb43c72022-09-08 19:03:14 +09005890 if (!shouldPromptUnvalidated(nai)) return;
5891
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005892 // Stop automatically reconnecting to this network in the future. Automatically connecting
5893 // to a network that provides no or limited connectivity is not useful, because the user
5894 // cannot use that network except through the notification shown by this method, and the
5895 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005896 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005897
Chalard Jean254bd162022-08-25 13:04:51 +09005898 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005899 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005900 } else {
5901 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5902 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005903 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005904
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005905 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5906 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005907 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005908
lucaslin2240ef62019-03-12 13:08:03 +08005909 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5910 return;
5911 }
5912
5913 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005914 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005915 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005916 }
5917
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005918 @Override
5919 public int getMultipathPreference(Network network) {
5920 enforceAccessPermission();
5921
5922 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005923 if (nai != null && nai.networkCapabilities
5924 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005925 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5926 }
5927
Aaron Huang9a57acf2020-12-08 10:03:29 +08005928 final NetworkPolicyManager netPolicyManager =
5929 mContext.getSystemService(NetworkPolicyManager.class);
5930
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005931 final long token = Binder.clearCallingIdentity();
5932 final int networkPreference;
5933 try {
5934 networkPreference = netPolicyManager.getMultipathPreference(network);
5935 } finally {
5936 Binder.restoreCallingIdentity(token);
5937 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005938 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005939 return networkPreference;
5940 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005941 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5942 }
5943
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005944 @Override
5945 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005946 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005947 }
5948
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005949 private class InternalHandler extends Handler {
5950 public InternalHandler(Looper looper) {
5951 super(looper);
5952 }
5953
5954 @Override
5955 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005956 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005957 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005958 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005959 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005960 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005961 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005962 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005963 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005964 break;
5965 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08005966 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005967 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08005968 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005969 break;
5970 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005971 case EVENT_REGISTER_NETWORK_PROVIDER: {
5972 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005973 break;
5974 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005975 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5976 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005977 break;
5978 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005979 case EVENT_REGISTER_NETWORK_OFFER: {
5980 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5981 break;
5982 }
5983 case EVENT_UNREGISTER_NETWORK_OFFER: {
5984 final NetworkOfferInfo offer =
5985 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5986 if (null != offer) {
5987 handleUnregisterNetworkOffer(offer);
5988 }
5989 break;
5990 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005991 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005992 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5993 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5994 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005995 break;
5996 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005997 case EVENT_REGISTER_NETWORK_REQUEST:
5998 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005999 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006000 break;
6001 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006002 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6003 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006004 handleRegisterNetworkRequestWithIntent(msg);
6005 break;
6006 }
Erik Kline155a59a2015-11-25 12:49:38 +09006007 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6008 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6009 handleTimedOutNetworkRequest(nri);
6010 break;
6011 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006012 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6013 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6014 break;
6015 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006016 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006017 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6018 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006019 break;
6020 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006021 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006022 Network network = (Network) msg.obj;
6023 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006024 break;
6025 }
lucaslin2240ef62019-03-12 13:08:03 +08006026 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6027 Network network = (Network) msg.obj;
6028 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6029 toBool(msg.arg2));
6030 break;
6031 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006032 case EVENT_SET_AVOID_UNVALIDATED: {
6033 handleSetAvoidUnvalidated((Network) msg.obj);
6034 break;
6035 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006036 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6037 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006038 break;
6039 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006040 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6041 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006042 break;
6043 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006044 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6045 // handler thread.
6046 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006047 mKeepaliveTracker.handleStartKeepalive(msg);
6048 break;
6049 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006050 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006051 final AutomaticOnOffKeepalive ki =
6052 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6053 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006054
chiachangwang676c84e2023-02-14 09:22:05 +00006055 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006056 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006057 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006058 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006059 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6060 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006061 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6062 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006063 }
6064 }
6065
6066 // If the network no longer exists, then the keepalive should have been
6067 // cleaned up already. There is no point trying to resume keepalives.
6068 if (!networkFound) return;
6069
chiachangwang676c84e2023-02-14 09:22:05 +00006070 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006071 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang676c84e2023-02-14 09:22:05 +00006072 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006073 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006074 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006075 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006076 }
6077 break;
6078 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006079 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006080 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006081 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6082 (IBinder) msg.obj);
6083 if (ki == null) {
6084 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006085 return;
6086 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006087 final int reason = msg.arg2;
6088 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006089 break;
6090 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006091 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6092 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6093 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006094 break;
6095 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006096 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6097 handlePrivateDnsSettingsChanged();
6098 break;
dalyk1720e542018-03-05 12:42:22 -05006099 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6100 handlePrivateDnsValidationUpdate(
6101 (PrivateDnsValidationUpdate) msg.obj);
6102 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006103 case EVENT_UID_BLOCKED_REASON_CHANGED:
6104 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006105 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006106 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6107 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6108 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006109 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006110 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6111 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006112 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006113 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006114 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006115 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006116 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6117 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006118 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006119 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006120 }
lucaslin1193a5d2021-01-21 02:04:15 +08006121 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006122 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006123 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006124 break;
paulhu51f77dc2021-06-07 02:34:20 +00006125 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6126 handleMobileDataPreferredUidsChanged();
6127 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006128 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6129 final long timeMs = ((Long) msg.obj).longValue();
6130 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6131 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006132 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6133 handleIngressRateLimitChanged();
6134 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006135 case EVENT_USER_DOES_NOT_WANT:
6136 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6137 if (nai == null) break;
6138 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006139 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006140 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006141 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6142 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6143 break;
chiachangwange0192a72023-02-06 13:25:01 +00006144 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6145 final long time = ((Long) msg.obj).longValue();
6146 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6147 break;
6148 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006149 case EVENT_UID_FROZEN_STATE_CHANGED:
6150 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6151 handleFrozenUids(args.mUids, args.mFrozenStates);
6152 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006153 }
6154 }
6155 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006156
Lorenzo Colittid6459092016-07-04 12:55:44 +09006157 @Override
markchien5776f962019-12-16 20:15:20 +08006158 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006159 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006160 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006161 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6162 Context.TETHERING_SERVICE);
6163 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006164 }
6165
Lorenzo Colittid6459092016-07-04 12:55:44 +09006166 @Override
markchien5776f962019-12-16 20:15:20 +08006167 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006168 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006169 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006170 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6171 Context.TETHERING_SERVICE);
6172 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006173 }
6174
Lorenzo Colittid6459092016-07-04 12:55:44 +09006175 @Override
markchien5776f962019-12-16 20:15:20 +08006176 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006177 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006178 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006179 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6180 Context.TETHERING_SERVICE);
6181 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006182 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006183
markchien5776f962019-12-16 20:15:20 +08006184
Lorenzo Colittid6459092016-07-04 12:55:44 +09006185 @Override
markchien5776f962019-12-16 20:15:20 +08006186 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006187 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006188 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006189 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6190 Context.TETHERING_SERVICE);
6191
6192 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006193 }
6194
Lorenzo Colittid6459092016-07-04 12:55:44 +09006195 @Override
markchien5776f962019-12-16 20:15:20 +08006196 @Deprecated
6197 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006198 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006199 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6200 Context.TETHERING_SERVICE);
6201
6202 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006203 }
6204
Udam Saini8f7d6a72017-06-07 12:06:28 -07006205 @Override
markchien5776f962019-12-16 20:15:20 +08006206 @Deprecated
6207 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006208 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006209 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6210 Context.TETHERING_SERVICE);
6211 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006212 }
6213
Robert Greenwalte0b00512014-07-02 09:59:16 -07006214 // Called when we lose the default network and have no replacement yet.
6215 // This will automatically be cleared after X seconds or a new default network
6216 // becomes CONNECTED, whichever happens first. The timer is started by the
6217 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006218 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006219 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006220 if (mNetTransitionWakeLock.isHeld()) {
6221 return;
6222 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006223 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006224 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6225 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006226 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006227 mWakelockLogs.log("ACQUIRE for " + forWhom);
6228 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006229 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006230 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006231 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006232 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006233
Hugo Benichi471b62a2017-03-30 23:18:10 +09006234 // Called when we gain a new default network to release the network transition wakelock in a
6235 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6236 // message is cancelled.
6237 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006238 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006239 if (!mNetTransitionWakeLock.isHeld()) {
6240 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006241 }
6242 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006243 // Cancel self timeout on wakelock hold.
6244 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6245 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6246 mHandler.sendMessageDelayed(msg, 1000);
6247 }
6248
6249 // Called when either message of ensureNetworkTransitionWakelock or
6250 // scheduleReleaseNetworkTransitionWakelock is processed.
6251 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6252 String event = eventName(eventId);
6253 synchronized (this) {
6254 if (!mNetTransitionWakeLock.isHeld()) {
6255 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006256 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006257 return;
6258 }
6259 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006260 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6261 mTotalWakelockDurationMs += lockDuration;
6262 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6263 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006264 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006265 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006266 }
6267
Robert Greenwalt986c7412010-09-08 15:24:47 -07006268 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006269 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006270 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006271 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006272 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006273 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006274 }
6275
Lorenzo Colittid6459092016-07-04 12:55:44 +09006276 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006277 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006278 enforceAccessPermission();
6279 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006280 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006281 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006282
6283 final NetworkAgentInfo nai;
6284 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006285 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006286 } else {
6287 nai = getNetworkAgentInfoForNetwork(network);
6288 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006289
6290 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006291 mHandler.obtainMessage(
6292 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006293 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006294
Hugo Benichid6b510a2017-04-06 17:22:18 +09006295 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006296 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006297 if (nai == null
6298 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006299 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006300 return;
6301 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006302 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006303 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006304 mConnectivityDiagnosticsHandler.sendMessage(
6305 mConnectivityDiagnosticsHandler.obtainMessage(
6306 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6307 new ReportedNetworkConnectivityInfo(
6308 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006309 return;
6310 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006311 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006312 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006313 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006314 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006315 // Validating a network that has not yet connected could result in a call to
6316 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006317 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006318 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006319 }
paulhu7aeba372020-12-30 00:42:19 +08006320 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6321 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006322 return;
6323 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006324
6325 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6326 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6327 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6328 // completed.
6329 mConnectivityDiagnosticsHandler.sendMessage(
6330 mConnectivityDiagnosticsHandler.obtainMessage(
6331 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6332 new ReportedNetworkConnectivityInfo(
6333 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006334 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006335 }
6336
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006337 // TODO: call into netd.
6338 private boolean queryUserAccess(int uid, Network network) {
6339 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6340 if (nai == null) return false;
6341
6342 // Any UID can use its default network.
6343 if (nai == getDefaultNetworkForUid(uid)) return true;
6344
6345 // Privileged apps can use any network.
6346 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6347 return true;
6348 }
6349
6350 // An unprivileged UID can use a VPN iff the VPN applies to it.
6351 if (nai.isVPN()) {
6352 return nai.networkCapabilities.appliesToUid(uid);
6353 }
6354
6355 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6356 // sockets, i.e., if it is the owner.
6357 final NetworkAgentInfo vpn = getVpnForUid(uid);
6358 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6359 && uid != vpn.networkCapabilities.getOwnerUid()) {
6360 return false;
6361 }
6362
6363 // The UID's permission must be at least sufficient for the network. Since the restricted
6364 // permission was already checked above, that just leaves background networks.
6365 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6366 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6367 }
6368
6369 // Unrestricted network. Anyone gets to use it.
6370 return true;
6371 }
6372
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006373 /**
6374 * Returns information about the proxy a certain network is using. If given a null network, it
6375 * it will return the proxy for the bound network for the caller app or the default proxy if
6376 * none.
6377 *
6378 * @param network the network we want to get the proxy information for.
6379 * @return Proxy information if a network has a proxy configured, or otherwise null.
6380 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006381 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006382 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006383 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006384 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006385 if (network == null) {
6386 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006387 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006388 true);
6389 if (activeNetwork == null) {
6390 return null;
6391 }
6392 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006393 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006394 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6395 // caller may not have.
6396 return getLinkPropertiesProxyInfo(network);
6397 }
6398 // No proxy info available if the calling UID does not have network access.
6399 return null;
6400 }
6401
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006402
6403 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006404 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6405 if (nai == null) return null;
6406 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006407 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6408 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006409 }
6410 }
6411
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006412 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006413 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006414 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006415 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006416 }
6417
Chalard Jean777e2e52018-06-07 18:02:37 +09006418 @Override
6419 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006420 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006421 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006422 }
6423
Aaron Huang9fe47be2021-06-08 13:11:45 +08006424 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006425 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006426 final NetworkAgentInfo nai = getDefaultNetwork();
6427 // TODO : this method should check that net == nai.network, unfortunately at this point
6428 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6429 // is only ever installed on the default network so in practice this is okay.
6430 if (null == nai) return;
6431 // PAC proxies only work on the default network. Therefore, only the default network
6432 // should have its link properties fixed up for PAC proxies.
6433 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6434 if (nai.everConnected()) {
6435 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6436 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006437 }
6438
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006439 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6440 // when any network changes proxy.
6441 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6442 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006443 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6444 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006445 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6446
Chalard Jean7d97afc2018-06-07 17:41:29 +09006447 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006448 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006449 }
6450 }
6451
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006452 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006453 final private HashMap<Uri, Integer> mUriEventMap;
6454 final private Context mContext;
6455 final private Handler mHandler;
6456
6457 SettingsObserver(Context context, Handler handler) {
6458 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006459 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006460 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006461 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006462 }
6463
Erik Kline05f2b402015-04-30 12:58:40 +09006464 void observe(Uri uri, int what) {
6465 mUriEventMap.put(uri, what);
6466 final ContentResolver resolver = mContext.getContentResolver();
6467 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006468 }
6469
6470 @Override
6471 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006472 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006473 }
6474
6475 @Override
6476 public void onChange(boolean selfChange, Uri uri) {
6477 final Integer what = mUriEventMap.get(uri);
6478 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006479 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006480 } else {
6481 loge("No matching event to send for URI=" + uri);
6482 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006483 }
6484 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006485
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006486 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006487 Log.d(TAG, s);
6488 }
6489
6490 private static void logw(String s) {
6491 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006492 }
6493
Daniel Brightf9e945b2020-06-15 16:10:01 -07006494 private static void logwtf(String s) {
6495 Log.wtf(TAG, s);
6496 }
6497
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006498 private static void logwtf(String s, Throwable t) {
6499 Log.wtf(TAG, s, t);
6500 }
6501
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006502 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006503 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006504 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006505
Hugo Benichi39621362017-02-11 17:04:43 +09006506 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006507 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006508 }
6509
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006510 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006511 * Return the information of all ongoing VPNs.
6512 *
6513 * <p>This method is used to update NetworkStatsService.
6514 *
6515 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006516 */
junyulai2050bed2021-01-23 09:46:34 +08006517 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006518 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006519 if (mLockdownEnabled) {
6520 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006521 }
junyulai2050bed2021-01-23 09:46:34 +08006522 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006523 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006524 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006525 if (info != null) {
6526 infoList.add(info);
6527 }
6528 }
junyulai2050bed2021-01-23 09:46:34 +08006529 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006530 }
6531
6532 /**
6533 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006534 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006535 */
junyulai2050bed2021-01-23 09:46:34 +08006536 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006537 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006538 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6539 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006540 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6541 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6542 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006543 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6544 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006545 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006546 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006547 }
6548 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006549
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006550 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006551
6552 List<String> interfaces = new ArrayList<>();
6553 for (Network network : underlyingNetworks) {
6554 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6555 if (underlyingNai == null) continue;
6556 LinkProperties lp = underlyingNai.linkProperties;
6557 for (String iface : lp.getAllInterfaceNames()) {
6558 if (!TextUtils.isEmpty(iface)) {
6559 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006560 }
6561 }
Benedict Wong34857f82019-06-12 17:46:15 +00006562 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006563
6564 if (interfaces.isEmpty()) return null;
6565
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006566 // Must be non-null or NetworkStatsService will crash.
6567 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6568 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006569 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006570 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006571
junyulai2050bed2021-01-23 09:46:34 +08006572 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6573 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006574 }
6575
James Mattisd31bdfa2020-12-23 16:37:26 -08006576 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006577 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6578 Network[] underlyingNetworks) {
6579 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006580 if (underlyingNetworks == null && defaultNetwork != null) {
6581 // null underlying networks means to track the default.
6582 underlyingNetworks = new Network[] { defaultNetwork };
6583 }
6584 return underlyingNetworks;
6585 }
6586
6587 // Returns true iff |network| is an underlying network of |nai|.
6588 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6589 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6590 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006591 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006592 final Network[] underlying = underlyingNetworksOrDefault(
6593 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006594 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006595 }
6596
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006597 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006598 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006599 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006600 * When underlying networks change, such networks may have to update capabilities to reflect
6601 * things like the metered bit, their transports, and so on. The capabilities are calculated
6602 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006603 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006604 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006605 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006606 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006607 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006608 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006609 }
6610 }
6611 }
6612
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006613 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6614 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6615 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6616 // a VPN is not up.
6617 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6618 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6619 for (UidRange range : blockedUidRanges) {
6620 if (range.contains(uid)) return true;
6621 }
6622 return false;
6623 }
6624
6625 @Override
6626 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006627 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006628 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6629 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6630 }
6631
6632 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6633 if (DBG) {
6634 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6635 + Arrays.toString(ranges));
6636 }
6637 // Cannot use a Set since the list of UID ranges might contain duplicates.
6638 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6639 for (int i = 0; i < ranges.length; i++) {
6640 if (requireVpn) {
6641 newVpnBlockedUidRanges.add(ranges[i]);
6642 } else {
6643 newVpnBlockedUidRanges.remove(ranges[i]);
6644 }
6645 }
6646
6647 try {
6648 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6649 } catch (RemoteException | ServiceSpecificException e) {
6650 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6651 + Arrays.toString(ranges) + "): netd command failed: " + e);
6652 }
6653
Chalard Jeandf29a852023-05-29 17:02:43 +09006654 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006655 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6656 }
6657
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006658 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6659 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006660 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6661 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006662 }
6663
6664 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6665 }
6666
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006667 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006668 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006669 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006670 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006671 }
6672
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006673 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6674 return mLockdownEnabled
6675 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6676 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006677 }
6678
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006679 private NetworkAgentInfo getLegacyLockdownNai() {
6680 if (!mLockdownEnabled) {
6681 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006682 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006683 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006684 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6685 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006686
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006687 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006688 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6689 // a local variable. There is no need to make a copy because its contents cannot change.
6690 final Network[] underlying = nai.declaredUnderlyingNetworks;
6691 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006692 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006693 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006694
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006695 // The legacy lockdown VPN always uses the default network.
6696 // If the VPN's underlying network is no longer the current default network, it means that
6697 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006698 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6699 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006700 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006701 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006702 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006703 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006704
6705 return nai;
6706 };
6707
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006708 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6709 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6710 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006711 private DetailedState getLegacyLockdownState(DetailedState origState) {
6712 if (origState != DetailedState.CONNECTED) {
6713 return origState;
6714 }
6715 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6716 ? DetailedState.CONNECTING
6717 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006718 }
6719
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006720 private void filterForLegacyLockdown(NetworkInfo ni) {
6721 if (!mLockdownEnabled || !ni.isConnected()) return;
6722 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6723 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6724 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6725 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6726 // network, this time with a state of CONNECTED.
6727 //
6728 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6729 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6730 // is not too far off the truth, since an always-on VPN, when not connected, is always
6731 // trying to reconnect.
6732 if (getLegacyLockdownNai() == null) {
6733 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6734 }
6735 }
6736
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006737 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006738 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006739 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006740 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006741 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6742 return;
6743 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006744 final long ident = Binder.clearCallingIdentity();
6745 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006746 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006747 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006748 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006749 } finally {
6750 Binder.restoreCallingIdentity(ident);
6751 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006752 }
Wink Savillecb117d32013-08-29 14:57:08 -07006753
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006754 @Override
6755 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006756 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006757 final long ident = Binder.clearCallingIdentity();
6758 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006759 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006760 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006761 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6762 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006763 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006764 } finally {
6765 Binder.restoreCallingIdentity(ident);
6766 }
6767 }
6768
James Mattis02220e22021-03-13 19:27:21 -08006769 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006770 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6771 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6772 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006773 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006774 }
6775
James Mattis02220e22021-03-13 19:27:21 -08006776 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006777 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006778 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006779 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6780 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006781 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006782 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6783 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6784 }
junyulaid91e7052020-08-28 13:44:33 +08006785 }
6786
James Mattis02220e22021-03-13 19:27:21 -08006787 private void onPackageChanged(@NonNull final String packageName) {
6788 // This is necessary in case a package is added or removed, but also when it's replaced to
6789 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6790 // as one in the preferences, then it should follow the same routing as that other package,
6791 // which means updating the rules is never to be needed in this case (whether it joins or
6792 // leaves a UID with a preference).
6793 if (isMappedInOemNetworkPreference(packageName)) {
6794 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6795 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006796
6797 // Invalidates cache entry when the package is updated.
6798 synchronized (mSelfCertifiedCapabilityCache) {
6799 mSelfCertifiedCapabilityCache.remove(packageName);
6800 }
James Mattis02220e22021-03-13 19:27:21 -08006801 }
6802
6803 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006804 @Override
6805 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006806 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006807 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006808 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006809
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006810 // User should be filled for below intents, check the existence.
6811 if (user == null) {
6812 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6813 return;
6814 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006815
Lorenzo Colitticd675292021-02-04 17:32:07 +09006816 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006817 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006818 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006819 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006820 } else {
junyulaid91e7052020-08-28 13:44:33 +08006821 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006822 }
6823 }
6824 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006825
James Mattis02220e22021-03-13 19:27:21 -08006826 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6827 @Override
6828 public void onReceive(Context context, Intent intent) {
6829 ensureRunningOnConnectivityServiceThread();
6830 switch (intent.getAction()) {
6831 case Intent.ACTION_PACKAGE_ADDED:
6832 case Intent.ACTION_PACKAGE_REMOVED:
6833 case Intent.ACTION_PACKAGE_REPLACED:
6834 onPackageChanged(intent.getData().getSchemeSpecificPart());
6835 break;
6836 default:
6837 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6838 }
6839 }
6840 };
6841
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006842 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006843 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006844
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006845 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006846 public final String name;
6847 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006848 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006849 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006850
lifraf3a3492021-03-10 13:58:14 +08006851 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6852 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006853 this.name = name;
6854 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006855 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006856 mDeathRecipient = deathRecipient;
6857
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006858 if (mDeathRecipient == null) {
6859 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006860 }
6861 }
6862
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006863 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006864 try {
6865 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6866 } catch (RemoteException e) {
6867 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006868 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006869 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006870 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006871
James Mattis4fce5d12020-11-12 15:53:42 -08006872 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6873 for (int i = 0; i < requests.size(); i++) {
6874 ensureNetworkRequestHasType(requests.get(i));
6875 }
6876 }
6877
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006878 private void ensureNetworkRequestHasType(NetworkRequest request) {
6879 if (request.type == NetworkRequest.Type.NONE) {
6880 throw new IllegalArgumentException(
6881 "All NetworkRequests in ConnectivityService must have a type");
6882 }
6883 }
6884
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006885 /**
6886 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006887 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006888 */
James Mattis258ea3c2020-11-15 15:04:40 -08006889 @VisibleForTesting
6890 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006891 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6892 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006893 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006894
James Mattisa076c532020-12-02 14:12:41 -08006895 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6896 void setSatisfier(
6897 @Nullable final NetworkAgentInfo satisfier,
6898 @Nullable final NetworkRequest activeRequest) {
6899 mSatisfier = satisfier;
6900 mActiveRequest = activeRequest;
6901 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006902
James Mattisd31bdfa2020-12-23 16:37:26 -08006903 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006904 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006905 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006906 private NetworkAgentInfo mSatisfier;
6907 NetworkAgentInfo getSatisfier() {
6908 return mSatisfier;
6909 }
6910
6911 // The request in mRequests assigned to a network agent. This is null if none of the
6912 // requests in mRequests can be satisfied. This member has the constraint of only being
6913 // accessible on the handler thread.
6914 @Nullable
6915 private NetworkRequest mActiveRequest;
6916 NetworkRequest getActiveRequest() {
6917 return mActiveRequest;
6918 }
6919
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006920 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006921 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006922 @Nullable
6923 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006924
6925 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006926 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006927 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006928 final int mPid;
6929 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006930 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006931 @Nullable
6932 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006933
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006934 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006935 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006936
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006937 // Effective UID of this request. This is different from mUid when a privileged process
6938 // files a request on behalf of another UID. This UID is used to determine blocked status,
6939 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6940 // maximum limit of registered callbacks per UID.
6941 final int mAsUid;
6942
paulhu48291862021-07-14 14:53:57 +08006943 // Preference order of this request.
6944 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006945
James Mattis3ce3d3c2021-02-09 18:18:28 -08006946 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6947 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6948 // maintained for keying off of. This is only a concern when the original nri
6949 // mNetworkRequests changes which happens currently for apps that register callbacks to
6950 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6951 // that match the per-app default nri that currently tracks the calling app's uid so that
6952 // callbacks are fired at the appropriate time. When the callbacks fire,
6953 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6954 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6955 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6956 @NonNull
6957 private final NetworkRequest mNetworkRequestForCallback;
6958 NetworkRequest getNetworkRequestForCallback() {
6959 return mNetworkRequestForCallback;
6960 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006961
James Mattisd31bdfa2020-12-23 16:37:26 -08006962 /**
6963 * Get the list of UIDs this nri applies to.
6964 */
6965 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006966 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006967 // networkCapabilities.getUids() returns a defensive copy.
6968 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006969 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6970 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006971 }
6972
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006973 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6974 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006975 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006976 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006977 }
6978
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006979 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006980 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006981 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006982 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006983 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006984 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006985 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006986 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006987 mBinder = null;
6988 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006989 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006990 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006991 mPerUidCounter = getRequestCounter(this);
6992 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006993 /**
6994 * Location sensitive data not included in pending intent. Only included in
6995 * {@link NetworkCallback}.
6996 */
6997 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006998 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006999 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007000 }
7001
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007002 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007003 @Nullable final IBinder binder,
7004 @NetworkCallback.Flag int callbackFlags,
7005 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007006 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7007 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007008 }
7009
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007010 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007011 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007012 @Nullable final IBinder binder,
7013 @NetworkCallback.Flag int callbackFlags,
7014 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007015 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007016 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007017 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007018 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007019 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007020 mBinder = binder;
7021 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007022 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007023 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007024 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007025 mPerUidCounter = getRequestCounter(this);
7026 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007027 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007028 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007029 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007030 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007031 }
7032
James Mattis3ce3d3c2021-02-09 18:18:28 -08007033 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7034 @NonNull final List<NetworkRequest> r) {
7035 super();
7036 ensureAllNetworkRequestsHaveType(r);
7037 mRequests = initializeRequests(r);
7038 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007039 final NetworkAgentInfo satisfier = nri.getSatisfier();
7040 if (null != satisfier) {
7041 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7042 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007043 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007044 // As this code creates a new NRI with a new set of requests, figure out which of
7045 // the list of requests should be the active request. It is always the first
7046 // request of the list that can be satisfied by the satisfier since the order of
7047 // requests is a priority order.
7048 // Note even in the presence of a satisfier there may not be an active request,
7049 // when the satisfier is the no-service network.
7050 NetworkRequest activeRequest = null;
7051 for (final NetworkRequest candidate : r) {
7052 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7053 activeRequest = candidate;
7054 break;
7055 }
7056 }
7057 setSatisfier(satisfier, activeRequest);
7058 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007059 mMessenger = nri.mMessenger;
7060 mBinder = nri.mBinder;
7061 mPid = nri.mPid;
7062 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007063 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007064 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007065 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007066 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007067 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007068 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007069 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007070 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007071 }
7072
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007073 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007074 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007075 }
7076
paulhue9913722021-05-26 15:19:20 +08007077 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007078 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007079 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007080 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007081 }
7082
James Mattis2516da32021-01-31 17:06:19 -08007083 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7084 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7085 // false.
7086 boolean isBeingSatisfied() {
7087 return (null != mSatisfier && null != mActiveRequest);
7088 }
7089
James Mattis3d229892020-11-16 16:46:28 -08007090 boolean isMultilayerRequest() {
7091 return mRequests.size() > 1;
7092 }
7093
James Mattis45d81842021-01-10 14:24:24 -08007094 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7095 // Creating a defensive copy to prevent the sender from modifying the list being
7096 // reflected in the return value of this method.
7097 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007098 return Collections.unmodifiableList(tempRequests);
7099 }
7100
James Mattisb1392002021-03-31 13:57:52 -07007101 void linkDeathRecipient() {
7102 if (null != mBinder) {
7103 try {
7104 mBinder.linkToDeath(this, 0);
7105 } catch (RemoteException e) {
7106 binderDied();
7107 }
7108 }
7109 }
7110
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007111 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007112 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007113 try {
7114 mBinder.unlinkToDeath(this, 0);
7115 } catch (NoSuchElementException e) {
7116 // Temporary workaround for b/194394697 pending analysis of additional logs
7117 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7118 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007119 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007120 }
7121
paulhu48291862021-07-14 14:53:57 +08007122 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7123 // Compare two preference orders.
7124 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007125 }
7126
paulhu48291862021-07-14 14:53:57 +08007127 int getPreferenceOrderForNetd() {
7128 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7129 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7130 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007131 }
paulhu48291862021-07-14 14:53:57 +08007132 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007133 }
7134
James Mattis4fce5d12020-11-12 15:53:42 -08007135 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007136 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007137 // As an immutable collection, mRequests cannot change by the time the
7138 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7139 // is acceptable. Use handleReleaseNetworkRequest and not directly
7140 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7141 // the app already unregistered the request.
7142 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7143 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007144 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007145
James Mattis4fce5d12020-11-12 15:53:42 -08007146 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007147 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007148 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7149 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007150 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007151 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007152 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007153 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007154 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007155 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007156 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007157 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007158 }
7159
Junyu Lai00d92df2022-07-05 11:01:52 +08007160 // Keep backward compatibility since the ServiceSpecificException is used by
7161 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7162 public static class RequestInfoPerUidCounter extends PerUidCounter {
7163 RequestInfoPerUidCounter(int maxCountPerUid) {
7164 super(maxCountPerUid);
7165 }
7166
7167 @Override
7168 public synchronized void incrementCountOrThrow(int uid) {
7169 try {
7170 super.incrementCountOrThrow(uid);
7171 } catch (IllegalStateException e) {
7172 throw new ServiceSpecificException(
7173 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7174 "Uid " + uid + " exceeded its allotted requests limit");
7175 }
7176 }
7177
7178 @Override
7179 public synchronized void decrementCountOrThrow(int uid) {
7180 throw new UnsupportedOperationException("Use decrementCount instead.");
7181 }
7182
7183 public synchronized void decrementCount(int uid) {
7184 try {
7185 super.decrementCountOrThrow(uid);
7186 } catch (IllegalStateException e) {
7187 logwtf("Exception when decrement per uid request count: ", e);
7188 }
7189 }
7190 }
7191
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007192 // This checks that the passed capabilities either do not request a
7193 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007194 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007195 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007196 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007197 throw new SecurityException("Insufficient permissions to request a specific SSID");
7198 }
paulhu1a407652019-03-22 16:35:06 +08007199
7200 if (nc.hasSignalStrength()
7201 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7202 throw new SecurityException(
7203 "Insufficient permissions to request a specific signal strength");
7204 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007205 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007206
junyulai2217bec2021-04-14 23:33:31 +08007207 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007208 enforceNetworkFactoryPermission();
7209 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007210 }
7211
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007212 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007213 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007214 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007215 // mNetworkRequests may contain the same value multiple times in case of
7216 // multilayer requests. It won't matter in this case because the thresholds
7217 // will then be the same and be deduplicated as they enter the `thresholds` set.
7218 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007219 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7220 for (final NetworkRequest req : nri.mRequests) {
7221 if (req.networkCapabilities.hasSignalStrength()
7222 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7223 thresholds.add(req.networkCapabilities.getSignalStrength());
7224 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007225 }
7226 }
7227 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007228 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007229 }
7230
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007231 private void updateSignalStrengthThresholds(
7232 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007233 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007234
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007235 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007236 String detail;
7237 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7238 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7239 } else {
7240 detail = reason;
7241 }
7242 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007243 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007244 }
7245
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007246 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007247 }
7248
Chalard Jeandd421992021-12-16 23:16:02 +09007249 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007250 if (nc == null) {
7251 return;
7252 }
7253 NetworkSpecifier ns = nc.getNetworkSpecifier();
7254 if (ns == null) {
7255 return;
7256 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007257 if (ns instanceof MatchAllNetworkSpecifier) {
7258 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7259 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007260 }
7261
Chalard Jeandd421992021-12-16 23:16:02 +09007262 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007263 ensureValidNetworkSpecifier(nc);
7264 if (nc.isPrivateDnsBroken()) {
7265 throw new IllegalArgumentException("Can't request broken private DNS");
7266 }
Chalard Jeande665262022-02-25 16:12:12 +09007267 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007268 throw new IllegalArgumentException("Can't request access UIDs");
7269 }
lucasline117e2e2019-10-22 18:27:33 +08007270 }
7271
Chalard Jeandd421992021-12-16 23:16:02 +09007272 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7273 ensureListenableCapabilities(nc);
7274 final String badCapability = nc.describeFirstNonRequestableCapability();
7275 if (badCapability != null) {
7276 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7277 }
7278 }
7279
Chiachang Wang3bc52762021-11-25 14:17:57 +08007280 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7281 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007282 private boolean isTargetSdkAtleast(int version, int callingUid,
7283 @NonNull String callingPackageName) {
7284 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007285 final PackageManager pm =
7286 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007287 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007288 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007289 if (callingVersion < version) return false;
7290 } catch (PackageManager.NameNotFoundException e) { }
7291 return true;
7292 }
7293
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007294 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007295 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007296 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007297 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007298 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007299 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007300 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7301 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007302 throw new SecurityException("Insufficient permissions to specify legacy type");
7303 }
markchienfac84a22020-03-18 21:16:15 +08007304 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007305 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007306 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007307 // Privileged callers can track the default network of another UID by passing in a UID.
7308 if (asUid != Process.INVALID_UID) {
7309 enforceSettingsPermission();
7310 } else {
7311 asUid = callingUid;
7312 }
junyulaiad010792021-01-11 16:53:38 +08007313 final NetworkRequest.Type reqType;
7314 try {
7315 reqType = NetworkRequest.Type.values()[reqTypeInt];
7316 } catch (ArrayIndexOutOfBoundsException e) {
7317 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7318 }
7319 switch (reqType) {
7320 case TRACK_DEFAULT:
7321 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007322 // is unused and will be replaced by ones appropriate for the UID (usually, the
7323 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007324 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007325 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007326 enforceAccessPermission();
7327 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007328 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007329 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007330 networkCapabilities = new NetworkCapabilities(defaultNc);
7331 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007332 case BACKGROUND_REQUEST:
7333 enforceNetworkStackOrSettingsPermission();
7334 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007335 case REQUEST:
7336 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7337 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007338 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007339 // TODO: this is incorrect. We mark the request as metered or not depending on
7340 // the state of the app when the request is filed, but we never change the
7341 // request if the app changes network state. http://b/29964605
7342 enforceMeteredApnPolicy(networkCapabilities);
7343 break;
junyulai1b1c8742021-03-12 20:05:08 +08007344 case LISTEN_FOR_BEST:
7345 enforceAccessPermission();
7346 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7347 break;
junyulaiad010792021-01-11 16:53:38 +08007348 default:
7349 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007350 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007351 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007352 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007353 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007354
junyulai1b1c8742021-03-12 20:05:08 +08007355 // Enforce FOREGROUND if the caller does not have permission to use background network.
7356 if (reqType == LISTEN_FOR_BEST) {
7357 restrictBackgroundRequestForCaller(networkCapabilities);
7358 }
7359
7360 // Set the UID range for this request to the single UID of the requester, unless the
7361 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007362 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7363 // are no visible methods to set the UIDs, an app could use reflection to try and get
7364 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007365 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007366 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7367 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007368
Etan Cohen85000162017-02-05 10:42:27 -08007369 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007370 throw new IllegalArgumentException("Bad timeout specified");
7371 }
Etan Cohen9786d922015-11-18 10:56:15 -08007372
James Mattis3ce3d3c2021-02-09 18:18:28 -08007373 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007374 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007375 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007376 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007377 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007378 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007379
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007380 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7381 // copied from the default request above. (This is necessary to ensure, for example, that
7382 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7383 // changes don't alter request matching.
7384 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7385 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007386 throw new IllegalStateException(
7387 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007388 + networkCapabilities + " vs. " + defaultNc);
7389 }
7390
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007391 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007392 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007393 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007394 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007395 }
7396 return networkRequest;
7397 }
7398
James Mattis3ce3d3c2021-02-09 18:18:28 -08007399 /**
7400 * Return the nri to be used when registering a network request. Specifically, this is used with
7401 * requests registered to track the default request. If there is currently a per-app default
7402 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7403 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007404 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7405 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007406 * @param nr the network request for the nri.
7407 * @param msgr the messenger for the nri.
7408 * @param binder the binder for the nri.
7409 * @param callingAttributionTag the calling attribution tag for the nri.
7410 * @return the nri to register.
7411 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007412 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007413 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007414 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007415 @Nullable String callingAttributionTag) {
7416 final List<NetworkRequest> requests;
7417 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7418 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007419 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007420 } else {
7421 requests = Collections.singletonList(nr);
7422 }
Roshan Pius951c0032020-12-22 15:10:42 -08007423 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007424 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007425 }
7426
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007427 private boolean shouldCheckCapabilitiesDeclaration(
7428 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7429 @NonNull final String callingPackageName) {
7430 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7431 // Only run the check if the change is enabled.
7432 if (!mDeps.isChangeEnabled(
7433 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7434 callingPackageName, user)) {
7435 return false;
7436 }
7437
7438 return networkCapabilities.hasCapability(
7439 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7440 || networkCapabilities.hasCapability(
7441 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7442 }
7443
7444 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
7445 @NonNull final NetworkCapabilities networkCapabilities) {
7446 // This check is added to fix the linter error for "current min is 30", which is not going
7447 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007448 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007449 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7450 return;
7451 }
7452 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007453 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007454 try {
7455 synchronized (mSelfCertifiedCapabilityCache) {
7456 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7457 callerPackageName);
7458 if (applicationNetworkCapabilities == null) {
7459 final PackageManager packageManager = mContext.getPackageManager();
7460 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7461 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7462 callerPackageName
7463 );
7464 final XmlResourceParser parser = packageManager
7465 .getResourcesForApplication(callerPackageName)
7466 .getXml(networkSliceProperty.getResourceId());
7467 applicationNetworkCapabilities =
7468 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7469 mSelfCertifiedCapabilityCache.put(callerPackageName,
7470 applicationNetworkCapabilities);
7471 }
7472
7473 }
7474 } catch (PackageManager.NameNotFoundException ne) {
7475 throw new SecurityException(
7476 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7477 + " property");
7478 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7479 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007480 } finally {
7481 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007482 }
7483
7484 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7485 networkCapabilities);
7486 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007487 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007488 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007489 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7490 callingPackageName)) {
7491 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7492 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007493 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007494 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7495 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7496 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7497 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007498 }
junyulai96bd9fe2022-03-08 17:36:42 +08007499 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007500 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007501 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007502 }
7503 }
7504
fenglu3f357402015-03-20 11:29:56 -07007505 @Override
fenglub00f4882015-04-21 17:12:05 -07007506 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007507 enforceAccessPermission();
7508 NetworkAgentInfo nai = null;
7509 if (network == null) {
7510 return false;
7511 }
7512 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007513 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007514 }
7515 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007516 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007517 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007518 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007519 Integer uidReqs = mBandwidthRequests.get(uid);
7520 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007521 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007522 }
7523 mBandwidthRequests.put(uid, ++uidReqs);
7524 }
fenglu3f357402015-03-20 11:29:56 -07007525 return true;
7526 }
7527 return false;
7528 }
7529
Felipe Leme0a5ae422016-06-20 16:36:29 -07007530 private boolean isSystem(int uid) {
7531 return uid < Process.FIRST_APPLICATION_UID;
7532 }
fenglu3f357402015-03-20 11:29:56 -07007533
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007534 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007535 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007536 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007537 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007538 return;
7539 }
Hugo Benichi39621362017-02-11 17:04:43 +09007540 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7541 // Policy already enforced.
7542 return;
7543 }
paulhuaf50d7d2020-12-24 19:47:34 +08007544 final long ident = Binder.clearCallingIdentity();
7545 try {
7546 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7547 // If UID is restricted, don't allow them to bring up metered APNs.
7548 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7549 }
7550 } finally {
7551 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007552 }
7553 }
7554
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007555 @Override
7556 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007557 PendingIntent operation, @NonNull String callingPackageName,
7558 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007559 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007560 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007561 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007562 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007563 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007564 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007565 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007566 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007567 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007568 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7569 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007570
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007571 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007572 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007573 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7574 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007575 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007576 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7577 nri));
7578 return networkRequest;
7579 }
7580
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007581 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7582 mHandler.sendMessageDelayed(
7583 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007584 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007585 }
7586
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007587 @Override
7588 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007589 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007590 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007591 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007592 }
7593
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007594 // In order to implement the compatibility measure for pre-M apps that call
7595 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7596 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7597 // This ensures it has permission to do so.
7598 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7599 if (nc == null) {
7600 return false;
7601 }
7602 int[] transportTypes = nc.getTransportTypes();
7603 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7604 return false;
7605 }
7606 try {
7607 mContext.enforceCallingOrSelfPermission(
7608 android.Manifest.permission.ACCESS_WIFI_STATE,
7609 "ConnectivityService");
7610 } catch (SecurityException e) {
7611 return false;
7612 }
7613 return true;
7614 }
7615
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007616 @Override
7617 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007618 Messenger messenger, IBinder binder,
7619 @NetworkCallback.Flag int callbackFlags,
7620 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007621 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007622 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7623 enforceAccessPermission();
7624 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007625
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007626 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007627 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007628 Binder.getCallingPid(), callingUid, callingPackageName);
7629 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007630 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7631 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7632 // onLost and onAvailable callbacks when networks move in and out of the background.
7633 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7634 // can't request networks.
7635 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007636 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007637
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007638 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007639 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007640 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007641 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007642 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007643 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007644
7645 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7646 return networkRequest;
7647 }
7648
7649 @Override
7650 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007651 PendingIntent operation, @NonNull String callingPackageName,
7652 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007653 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007654 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007655 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7656 enforceAccessPermission();
7657 }
Chalard Jeandd421992021-12-16 23:16:02 +09007658 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007659 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007660 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007661 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007662 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007663
7664 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007665 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007666 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7667 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007668 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007669
WeiZhang1cc3f172021-06-03 19:02:04 -05007670 mHandler.sendMessage(mHandler.obtainMessage(
7671 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007672 }
7673
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007674 /** Returns the next Network provider ID. */
7675 public final int nextNetworkProviderId() {
7676 return mNextNetworkProviderId.getAndIncrement();
7677 }
7678
Erik Kline0c04b742016-07-07 16:50:58 +09007679 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007680 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007681 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007682 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007683 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007684 }
7685
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007686 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7687 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007688 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7689 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7690 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007691 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007692 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007693 return;
7694 }
7695
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007696 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7697 mNetworkProviderInfos.put(npi.messenger, npi);
7698 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007699 }
7700
7701 @Override
7702 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007703 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007704 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007705 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007706 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007707 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7708 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007709 }
7710
7711 @Override
7712 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007713 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007714 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007715 }
7716
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007717 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007718 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007719 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7720 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007721 Objects.requireNonNull(score);
7722 Objects.requireNonNull(caps);
7723 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007724 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007725 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007726 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7727 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007728 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7729 }
7730
Chalard Jeanbb902a52021-08-18 01:35:19 +09007731 private void updateOfferScore(final NetworkOffer offer) {
7732 final boolean yieldToBadWiFi =
7733 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7734 final NetworkOffer newOffer = new NetworkOffer(
7735 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7736 offer.caps, offer.callback, offer.providerId);
7737 if (offer.equals(newOffer)) return;
7738 handleRegisterNetworkOffer(newOffer);
7739 }
7740
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007741 @Override
7742 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007743 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007744 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7745 }
7746
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007747 private void handleUnregisterNetworkProvider(Messenger messenger) {
7748 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7749 if (npi == null) {
7750 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007751 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007752 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007753 // Unregister all the offers from this provider
7754 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7755 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007756 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007757 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7758 toRemove.add(noi);
7759 }
7760 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007761 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007762 handleUnregisterNetworkOffer(noi);
7763 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007764 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007765 }
7766
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007767 @Override
James Mattisf7027322020-12-13 16:28:14 -08007768 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007769 if (request.hasTransport(TRANSPORT_TEST)) {
7770 enforceNetworkFactoryOrTestNetworksPermission();
7771 } else {
7772 enforceNetworkFactoryPermission();
7773 }
James Mattisf7027322020-12-13 16:28:14 -08007774 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7775 if (nri != null) {
7776 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7777 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7778 mHandler.post(() -> handleReleaseNetworkRequest(
7779 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7780 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007781 }
7782
Paul Jensen1f567382015-02-13 14:18:39 -05007783 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7784 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007785 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007786 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007787 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007788 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007789 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007790
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007791 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007792 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007793 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007794
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007795 // UID ranges for users that are currently blocked by VPNs.
7796 // This array is accessed and iterated on multiple threads without holding locks, so its
7797 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7798 // (on the handler thread).
7799 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7800
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007801 // Must only be accessed on the handler thread
7802 @NonNull
7803 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7804
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007805 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007806 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007807
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007808 // Current OEM network preferences. This object must only be written to on the handler thread.
7809 // Since it is immutable and always non-null, other threads may read it if they only care
7810 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007811 @NonNull
7812 private OemNetworkPreferences mOemNetworkPreferences =
7813 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007814 // Current per-profile network preferences. This object follows the same threading rules as
7815 // the OEM network preferences above.
7816 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007817 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7818 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007819
lucaslin3ba7cc22022-12-19 02:35:33 +00007820 // Current VPN network preferences. This object follows the same threading rules as the OEM
7821 // network preferences above.
7822 @NonNull
7823 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7824 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7825
paulhu51f77dc2021-06-07 02:34:20 +00007826 // A set of UIDs that should use mobile data preferentially if available. This object follows
7827 // the same threading rules as the OEM network preferences above.
7828 @NonNull
7829 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7830
James Mattiscb1e0362021-04-06 17:07:42 -07007831 // OemNetworkPreferences activity String log entries.
7832 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7833 @NonNull
7834 private final LocalLog mOemNetworkPreferencesLogs =
7835 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7836
James Mattis02220e22021-03-13 19:27:21 -08007837 /**
7838 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7839 * @param packageName the package name to check existence of a mapping for.
7840 * @return true if a mapping exists, false otherwise
7841 */
7842 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7843 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7844 }
7845
James Mattise3ef1912020-12-20 11:09:58 -08007846 // The always-on request for an Internet-capable network that apps without a specific default
7847 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007848 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007849 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007850 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007851 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007852 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007853 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007854 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007855
James Mattisd31bdfa2020-12-23 16:37:26 -08007856 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7857 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7858 }
7859
7860 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007861 * Return the default network request currently tracking the given uid.
7862 * @param uid the uid to check.
7863 * @return the NetworkRequestInfo tracking the given uid.
7864 */
7865 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007866 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007867 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007868 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007869 // Checking the first request is sufficient as only multilayer requests will have more
7870 // than one request and for multilayer, all requests will track the same uids.
7871 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007872 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007873 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007874 highestPriorityNri = nri;
7875 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007876 }
7877 }
paulhuaa0743d2021-05-26 21:56:03 +08007878 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007879 }
7880
7881 /**
7882 * Get a copy of the network requests of the default request that is currently tracking the
7883 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007884 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7885 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007886 * @param requestorUid the uid to check the default for.
7887 * @param requestorPackageName the requestor's package name.
7888 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7889 */
7890 @NonNull
7891 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007892 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007893 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007894 getDefaultRequestTrackingUid(asUid).mRequests,
7895 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007896 }
7897
7898 /**
7899 * Copy the given nri's NetworkRequest collection.
7900 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007901 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7902 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007903 * @param requestorUid the uid to set on the copied collection.
7904 * @param requestorPackageName the package name to set on the copied collection.
7905 * @return the copied NetworkRequest collection.
7906 */
7907 @NonNull
7908 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007909 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7910 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007911 final List<NetworkRequest> requests = new ArrayList<>();
7912 for (final NetworkRequest nr : requestsToCopy) {
7913 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007914 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007915 nr.legacyType, nextNetworkRequestId(), nr.type));
7916 }
7917 return requests;
7918 }
7919
7920 @NonNull
7921 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007922 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7923 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007924 // These capabilities are for a TRACK_DEFAULT callback, so:
7925 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7926 // mDefaultRequest and a per-UID default request.
7927 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007928 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007929 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007930 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7931 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007932 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007933 restrictRequestUidsForCallerAndSetRequestorInfo(
7934 netCap, requestorUid, requestorPackageName);
7935 return netCap;
7936 }
7937
7938 /**
7939 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7940 * @param nr the network request to check for equality against.
7941 * @return the nri if one exists, null otherwise.
7942 */
7943 @Nullable
7944 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7945 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7946 if (nri.getNetworkRequestForCallback().equals(nr)) {
7947 return nri;
7948 }
7949 }
7950 return null;
7951 }
7952
7953 /**
7954 * Check if an nri is currently being managed by per-app default networking.
7955 * @param nri the nri to check.
7956 * @return true if this nri is currently being managed by per-app default networking.
7957 */
7958 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7959 // nri.mRequests.get(0) is only different from the original request filed in
7960 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7961 // functionality therefore if these two don't match, it means this particular nri is
7962 // currently being managed by a per-app default.
7963 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7964 }
7965
7966 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007967 * Determine if an nri is a managed default request that disallows default networking.
7968 * @param nri the request to evaluate
7969 * @return true if device-default networking is disallowed
7970 */
7971 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7972 // Check if this nri is a managed default that supports the default network at its
7973 // lowest priority request.
7974 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7975 final NetworkCapabilities lowestPriorityNetCap =
7976 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7977 return isPerAppDefaultRequest(nri)
7978 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7979 lowestPriorityNetCap));
7980 }
7981
Erik Kline05f2b402015-04-30 12:58:40 +09007982 // Request used to optionally keep mobile data active even when higher
7983 // priority networks like Wi-Fi are active.
7984 private final NetworkRequest mDefaultMobileDataRequest;
7985
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007986 // Request used to optionally keep wifi data active even when higher
7987 // priority networks like ethernet are active.
7988 private final NetworkRequest mDefaultWifiRequest;
7989
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007990 // Request used to optionally keep vehicle internal network always active
7991 private final NetworkRequest mDefaultVehicleRequest;
7992
James Mattisd31bdfa2020-12-23 16:37:26 -08007993 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7994 // network with no service. This NAI should never be matched against, nor should any public API
7995 // ever return the associated network. For this reason, this NAI is not in the list of available
7996 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7997 // default requests that don't support using the device default network which will ultimately
7998 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7999 @VisibleForTesting
8000 final NetworkAgentInfo mNoServiceNetwork;
8001
Chalard Jean5b409c72021-02-04 13:12:59 +09008002 // The NetworkAgentInfo currently satisfying the default request, if any.
8003 private NetworkAgentInfo getDefaultNetwork() {
8004 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008005 }
8006
James Mattis2516da32021-01-31 17:06:19 -08008007 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008008 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008009 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8010 // Currently, all network requests will have the same uids therefore checking the first
8011 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008012 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008013 if (null == uids) {
8014 continue;
8015 }
8016 for (final UidRange range : uids) {
8017 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008018 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008019 highestPriorityNri = nri;
8020 }
James Mattis2516da32021-01-31 17:06:19 -08008021 }
8022 }
8023 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008024 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008025 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008026 }
8027
Varun Ananddf569952019-02-06 10:13:38 -08008028 @Nullable
8029 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8030 return nai != null ? nai.network : null;
8031 }
8032
8033 private void ensureRunningOnConnectivityServiceThread() {
8034 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8035 throw new IllegalStateException(
8036 "Not running on ConnectivityService thread: "
8037 + Thread.currentThread().getName());
8038 }
8039 }
8040
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008041 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008042 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8043 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008044 }
8045
Chalard Jean29d06db2018-05-02 21:14:54 +09008046 /**
8047 * Register a new agent with ConnectivityService to handle a network.
8048 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008049 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008050 * @param networkInfo the initial info associated with this network. It can be updated later :
8051 * see {@link #updateNetworkInfo}.
8052 * @param linkProperties the initial link properties of this network. They can be updated
8053 * later : see {@link #updateLinkProperties}.
8054 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008055 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008056 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008057 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008058 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008059 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008060 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008061 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09008062 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09008063 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
8064 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008065 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8066 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8067 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008068 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008069 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008070 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008071 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008072 } else {
8073 enforceNetworkFactoryPermission();
8074 }
8075
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008076 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008077 final long token = Binder.clearCallingIdentity();
8078 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008079 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09008080 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008081 } finally {
8082 Binder.restoreCallingIdentity(token);
8083 }
8084 }
8085
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008086 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008087 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09008088 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
8089 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008090
Chalard Jeandbc46952022-02-02 00:14:18 +09008091 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8092 // and mutate them at any time.
8093 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8094 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8095 final LinkProperties lpCopy = new LinkProperties(linkProperties);
8096
Chalard Jean366c5252022-01-25 18:27:53 +09008097 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008098 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008099 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8100 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008101 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008102 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09008103 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09008104 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
8105 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008106
Chalard Jeandbc46952022-02-02 00:14:18 +09008107 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008108 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008109 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008110 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008111 mDeps.getNetworkStack().makeNetworkMonitor(
8112 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008113 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8114 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008115 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008116 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008117 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008118 }
8119
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008120 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008121 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008122 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008123 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008124 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008125 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8126 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8127 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008128
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008129 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008130
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008131 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008132 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008133 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008134 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008135
8136 try {
8137 networkMonitor.start();
8138 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008139 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008140 }
Chalard Jean366c5252022-01-25 18:27:53 +09008141
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008142 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008143 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008144 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008145 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008146 }
8147
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008148 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8149 @NonNull public final NetworkOffer offer;
8150
8151 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8152 this.offer = offer;
8153 }
8154
8155 @Override
8156 public void binderDied() {
8157 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8158 }
8159 }
8160
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008161 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8162 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8163 if (npi.providerId == providerId) return true;
8164 }
8165 return false;
8166 }
8167
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008168 /**
8169 * Register or update a network offer.
8170 * @param newOffer The new offer. If the callback member is the same as an existing
8171 * offer, it is an update of that offer.
8172 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008173 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008174 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8175 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008176 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008177 // This may actually happen if a provider updates its score or registers and then
8178 // immediately unregisters. The offer would still be in the handler queue, but the
8179 // provider would have been removed.
8180 if (DBG) log("Received offer from an unregistered provider");
8181 return;
8182 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008183 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8184 if (null != existingOffer) {
8185 handleUnregisterNetworkOffer(existingOffer);
8186 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008187 if (DBG) {
8188 // handleUnregisterNetworkOffer has already logged the old offer
8189 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8190 }
8191 } else {
8192 if (DBG) {
8193 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8194 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008195 }
8196 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8197 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008198 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008199 } catch (RemoteException e) {
8200 noi.binderDied();
8201 return;
8202 }
8203 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008204 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008205 }
8206
8207 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8208 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008209 if (DBG) {
8210 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8211 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008212
8213 // If the provider removes the offer and dies immediately afterwards this
8214 // function may be called twice in a row, but the array will no longer contain
8215 // the offer.
8216 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008217 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008218 }
8219
8220 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8221 @NonNull final INetworkOfferCallback callback) {
8222 ensureRunningOnConnectivityServiceThread();
8223 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008224 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008225 }
8226 return null;
8227 }
8228
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008229 /**
8230 * Called when receiving LinkProperties directly from a NetworkAgent.
8231 * Stores into |nai| any data coming from the agent that might also be written to the network's
8232 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8233 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008234 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008235 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008236 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8237 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008238 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008239 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008240 }
8241
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008242 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008243 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008244 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008245
Lorenzo Colittid523d142020-04-01 20:16:30 +09008246 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8247 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8248 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008249 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008250
Suprabh Shukla1e312032023-01-24 03:36:37 -08008251 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008252
8253 // update filtering rules, need to happen after the interface update so netd knows about the
8254 // new interface (the interface name -> index map becomes initialized)
8255 updateVpnFiltering(newLp, oldLp, networkAgent);
8256
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008257 updateMtu(newLp, oldLp);
8258 // TODO - figure out what to do for clat
8259// for (LinkProperties lp : newLp.getStackedLinks()) {
8260// updateMtu(lp, null);
8261// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008262 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008263 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008264 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8265 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008266
Erik Klineb9888902016-04-05 13:30:49 +09008267 updateRoutes(newLp, oldLp, netId);
8268 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008269 // Make sure LinkProperties represents the latest private DNS status.
8270 // This does not need to be done before updateDnses because the
8271 // LinkProperties are not the source of the private DNS configuration.
8272 // updateDnses will fetch the private DNS configuration from DnsManager.
8273 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008274
Chalard Jean5b409c72021-02-04 13:12:59 +09008275 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008276 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008277 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008278 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008279 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008280
8281 updateWakeOnLan(newLp);
8282
Hai Shalome58bdc62021-01-11 18:45:34 -08008283 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8284 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8285 // does, it needs to be merged here.
8286 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8287 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008288
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008289 // TODO - move this check to cover the whole function
8290 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008291 synchronized (networkAgent) {
8292 networkAgent.linkProperties = newLp;
8293 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008294 // Start or stop DNS64 detection and 464xlat according to network state.
8295 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008296 // Notify NSS when relevant events happened. Currently, NSS only cares about
8297 // interface changed to update clat interfaces accounting.
8298 final boolean interfacesChanged = oldLp == null
8299 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8300 if (interfacesChanged) {
8301 notifyIfacesChangedForNetworkStats();
8302 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008303 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8304 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008305 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008306 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008307
8308 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008309 }
8310
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008311 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8312 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8313 }
8314
Hai Shalome58bdc62021-01-11 18:45:34 -08008315 /**
8316 * @param naData captive portal data from NetworkAgent
8317 * @param apiData captive portal data from capport API
8318 */
8319 @Nullable
8320 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8321 CaptivePortalData apiData) {
8322 if (naData == null || apiData == null) {
8323 return naData == null ? apiData : naData;
8324 }
8325 final CaptivePortalData.Builder captivePortalBuilder =
8326 new CaptivePortalData.Builder(naData);
8327
8328 if (apiData.isCaptive()) {
8329 captivePortalBuilder.setCaptive(true);
8330 }
8331 if (apiData.isSessionExtendable()) {
8332 captivePortalBuilder.setSessionExtendable(true);
8333 }
8334 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8335 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8336 // otherwise data would be inconsistent. Prefer the capport API info if present,
8337 // as it can generally be refreshed more often.
8338 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8339 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8340 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8341 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8342 // No source has time / bytes remaining information: surface the newest refresh time
8343 // for other fields
8344 captivePortalBuilder.setRefreshTime(
8345 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8346 }
8347
Hai Shalom7c6ab402021-02-04 19:34:06 -08008348 // Prioritize the user portal URL from the network agent if the source is authenticated.
8349 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8350 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8351 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8352 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008353 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008354 // Prioritize the venue information URL from the network agent if the source is
8355 // authenticated.
8356 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8357 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8358 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8359 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008360 }
8361 return captivePortalBuilder.build();
8362 }
8363
Suprabh Shukla53e16392023-04-26 18:47:36 -07008364 @VisibleForTesting
8365 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008366 // This needs to be kept in sync and backwards compatible with the decoding logic in
8367 // NetdEventListenerService, which is non-mainline code.
8368 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8369 }
8370
Suprabh Shukla75642282023-04-25 23:15:43 -07008371 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8372 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8373 return true;
8374 }
8375 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8376 return true;
8377 }
8378 return false;
8379 }
8380
Suprabh Shukla1e312032023-01-24 03:36:37 -08008381 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008382 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008383 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008384 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008385 return;
8386 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008387
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008388 // Mask/mark of zero will not detect anything interesting.
8389 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008390 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008391 return;
8392 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008393
Suprabh Shukla1e312032023-01-24 03:36:37 -08008394 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008395 try {
8396 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008397 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008398 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008399 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008400 }
8401 } catch (Exception e) {
8402 loge("Exception modifying wakeup packet monitoring: " + e);
8403 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008404 }
8405
Junyu Lai970963e2022-10-25 15:46:47 +08008406 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008407 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008408 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008409 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008410 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008411 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008412 for (final String iface : interfaceDiff.added) {
8413 try {
8414 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008415 mNetd.networkAddInterface(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008416 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008417 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008418 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008419 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008420 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008421 }
Paul Jensenbff73492014-04-28 10:33:11 -04008422 }
8423 }
Chalard Jean9589e722019-11-19 19:03:53 +09008424 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008425 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008426 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008427 wakeupModifyInterface(iface, nai, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008428 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008429 } catch (Exception e) {
8430 loge("Exception removing interface: " + e);
8431 }
8432 }
8433 }
8434
Tyler Weare4314862019-12-05 14:55:30 -08008435 // TODO: move to frameworks/libs/net.
8436 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
8437 final String nextHop;
8438
8439 switch (route.getType()) {
8440 case RouteInfo.RTN_UNICAST:
8441 if (route.hasGateway()) {
8442 nextHop = route.getGateway().getHostAddress();
8443 } else {
8444 nextHop = INetd.NEXTHOP_NONE;
8445 }
8446 break;
8447 case RouteInfo.RTN_UNREACHABLE:
8448 nextHop = INetd.NEXTHOP_UNREACHABLE;
8449 break;
8450 case RouteInfo.RTN_THROW:
8451 nextHop = INetd.NEXTHOP_THROW;
8452 break;
8453 default:
8454 nextHop = INetd.NEXTHOP_NONE;
8455 break;
8456 }
8457
8458 final RouteInfoParcel rip = new RouteInfoParcel();
8459 rip.ifName = route.getInterface();
8460 rip.destination = route.getDestination().toString();
8461 rip.nextHop = nextHop;
8462 rip.mtu = route.getMtu();
8463
8464 return rip;
8465 }
8466
Paul Jensene0fd4a82014-08-06 15:51:33 -04008467 /**
8468 * Have netd update routes from oldLp to newLp.
8469 * @return true if routes changed between oldLp and newLp
8470 */
Junyu Lai970963e2022-10-25 15:46:47 +08008471 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8472 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008473 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008474 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8475 new CompareOrUpdateResult<>(
8476 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008477 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008478 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008479
8480 // add routes before removing old in case it helps with continuous connectivity
8481
Chalard Jean9dd11612018-06-04 16:52:49 +09008482 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008483 for (RouteInfo route : routeDiff.added) {
8484 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008485 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008486 try {
Tyler Weare4314862019-12-05 14:55:30 -08008487 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008488 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008489 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008490 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008491 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008492 }
8493 }
8494 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008495 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008496 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008497 try {
Tyler Weare4314862019-12-05 14:55:30 -08008498 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008499 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008500 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008501 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008502 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008503 }
8504 }
8505
8506 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008507 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008508 try {
Tyler Weare4314862019-12-05 14:55:30 -08008509 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008510 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08008511 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008512 }
8513 }
Tyler Weare4314862019-12-05 14:55:30 -08008514
8515 for (RouteInfo route : routeDiff.updated) {
8516 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8517 try {
8518 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
8519 } catch (Exception e) {
8520 loge("Exception in networkUpdateRouteParcel: " + e);
8521 }
8522 }
8523 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8524 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008525 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008526
Junyu Lai970963e2022-10-25 15:46:47 +08008527 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8528 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008529 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8530 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008531 }
Erik Klineb9888902016-04-05 13:30:49 +09008532
Erik Kline31b4a9e2018-01-11 21:07:29 +09008533 if (DBG) {
8534 final Collection<InetAddress> dnses = newLp.getDnsServers();
8535 log("Setting DNS servers for network " + netId + " to " + dnses);
8536 }
Erik Klineb9888902016-04-05 13:30:49 +09008537 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008538 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008539 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008540 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008541 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008542 }
Erik Kline54e35c02017-04-07 15:29:29 +09008543 }
8544
Junyu Lai970963e2022-10-25 15:46:47 +08008545 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8546 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008547 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8548 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008549 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8550 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008551
8552 if (!wasFiltering && !needsFiltering) {
8553 // Nothing to do.
8554 return;
8555 }
8556
8557 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8558 // Nothing changed.
8559 return;
8560 }
8561
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008562 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008563 if (ranges == null || ranges.isEmpty()) {
8564 return;
8565 }
8566
Qingxi Libb8da982020-01-17 17:54:27 -08008567 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008568 // TODO: this create a window of opportunity for apps to receive traffic between the time
8569 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008570 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008571 // old rules are being removed.
8572 if (wasFiltering) {
8573 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8574 }
8575 if (needsFiltering) {
8576 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8577 }
8578 }
8579
Valentin Iftime9fa35092019-09-24 13:32:13 +02008580 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008581 if (mWolSupportedInterfaces == null) {
8582 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008583 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008584 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008585 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8586 }
8587
Luke Huangb913c812018-08-24 20:33:16 +08008588 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008589 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008590 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008591 }
8592 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008593 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008594 }
Luke Huangb913c812018-08-24 20:33:16 +08008595 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008596 }
8597
Chalard Jean62edfd82019-12-02 18:39:29 +09008598 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8599 @NonNull final NetworkCapabilities newNc) {
8600 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8601 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008602 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008603 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008604 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008605 } catch (RemoteException | ServiceSpecificException e) {
8606 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008607 }
8608 }
8609 }
8610
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008611 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008612 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008613 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008614 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008615 underlyingNetworks = underlyingNetworksOrDefault(
8616 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008617 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008618 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8619 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008620 // metered if any underlying is metered, or originally declared metered by the agent.
8621 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008622 boolean roaming = false; // roaming if any underlying is roaming
8623 boolean congested = false; // congested if any underlying is congested
8624 boolean suspended = true; // suspended if all underlying are suspended
8625
8626 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008627 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008628 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008629 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008630 for (Network underlyingNetwork : underlyingNetworks) {
8631 final NetworkAgentInfo underlying =
8632 getNetworkAgentInfoForNetwork(underlyingNetwork);
8633 if (underlying == null) continue;
8634
8635 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8636 hadUnderlyingNetworks = true;
8637 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008638 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008639 }
8640
8641 // Merge capabilities of this underlying network. For bandwidth, assume the
8642 // worst case.
8643 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8644 underlyingCaps.getLinkDownstreamBandwidthKbps());
8645 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8646 underlyingCaps.getLinkUpstreamBandwidthKbps());
8647 // If this underlying network is metered, the VPN is metered (it may cost money
8648 // to send packets on this network).
8649 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8650 // If this underlying network is roaming, the VPN is roaming (the billing structure
8651 // is different than the usual, local one).
8652 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8653 // If this underlying network is congested, the VPN is congested (the current
8654 // condition of the network affects the performance of this network).
8655 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8656 // If this network is not suspended, the VPN is not suspended (the VPN
8657 // is able to transfer some data).
8658 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008659 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008660 }
8661 }
8662 if (!hadUnderlyingNetworks) {
8663 // No idea what the underlying networks are; assume reasonable defaults
8664 metered = true;
8665 roaming = false;
8666 congested = false;
8667 suspended = false;
8668 }
8669
Chalard Jean1d420b32022-10-12 16:39:37 +09008670 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008671 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8672 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8673 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8674 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8675 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8676 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008677 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008678 }
8679
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008680 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008681 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8682 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8683 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008684 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008685 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008686 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008687 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008688 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8689 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008690 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008691 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008692 if (nai.everConnected()
8693 && !nai.isVPN()
8694 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008695 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008696 // does not cause any request (that is not a listen) currently matching that agent to
8697 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008698 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008699 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008700 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008701 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008702 }
8703
Paul Jensen53f08952015-06-16 14:27:36 -04008704 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008705 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008706 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008707 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008708 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008709 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008710 }
Chalard Jean254bd162022-08-25 13:04:51 +09008711 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008712 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008713 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008714 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008715 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008716 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008717 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008718 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008719 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008720 }
Chalard Jean254bd162022-08-25 13:04:51 +09008721 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008722 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8723 } else {
8724 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8725 }
lucasline117e2e2019-10-22 18:27:33 +08008726 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008727
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008728 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008729 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8730 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008731 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008732 }
8733
Lorenzo Colittibd079452021-07-02 11:47:57 +09008734 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008735 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008736 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008737 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008738 }
8739
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008740 return newNc;
8741 }
8742
Lorenzo Colitti44840702021-01-11 22:27:57 +09008743 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8744 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8745 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8746 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8747 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8748 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8749 if (prevSuspended != suspended) {
8750 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8751 // onResumed have been removed.
8752 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8753 : ConnectivityManager.CALLBACK_RESUMED);
8754 }
8755 if (prevSuspended != suspended || prevRoaming != roaming) {
8756 // updateNetworkInfo will mix in the suspended info from the capabilities and
8757 // take appropriate action for the network having possibly changed state.
8758 updateNetworkInfo(nai, nai.networkInfo);
8759 }
8760 }
8761
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008762 /**
8763 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8764 *
8765 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8766 * capabilities we manage and store in {@code nai}, such as validated status and captive
8767 * portal status)
8768 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8769 * potentially triggers rematches.
8770 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8771 * change.)
8772 *
8773 * @param oldScore score of the network before any of the changes that prompted us
8774 * to call this function.
8775 * @param nai the network having its capabilities updated.
8776 * @param nc the new network capabilities.
8777 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008778 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008779 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008780 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008781 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008782 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8783 if (null != differences) {
8784 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8785 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008786 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008787 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008788
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008789 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008790 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008791 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008792
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008793 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008794 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8795 // the change we're processing can't affect any requests, it can only affect the listens
8796 // on this network. We might have been called by rematchNetworkAndRequests when a
8797 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008798 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008799 } else {
8800 // If the requestable capabilities have changed or the score changed, we can't have been
8801 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008802 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008803 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008804 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008805 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008806
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008807 final boolean oldMetered = prevNc.isMetered();
8808 final boolean newMetered = newNc.isMetered();
8809 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008810
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008811 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008812 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8813 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008814 }
junyulaif2c67e42018-08-07 19:50:45 +08008815
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008816 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8817 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008818
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008819 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008820 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008821 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008822 }
8823
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008824 // This network might have been underlying another network. Propagate its capabilities.
8825 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008826
8827 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008828 mDnsManager.updateTransportsForNetwork(
8829 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008830 }
lucaslin53e8a262021-06-08 01:43:59 +08008831
8832 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008833 }
8834
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008835 /** Convenience method to update the capabilities for a given network. */
8836 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008837 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008838 }
8839
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008840 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008841 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008842 *
8843 * Ingress interface filtering enforces that all apps under the given network can only receive
8844 * packets from the network's interface (and loopback). This is important for VPNs because
8845 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8846 * non-VPN interfaces.
8847 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008848 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008849 * 1. the network is an app VPN (not legacy VPN)
8850 * 2. the VPN does not allow bypass
8851 * 3. the VPN is fully-routed
8852 * 4. the VPN interface is non-null
8853 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008854 * @see INetd#firewallAddUidInterfaceRules
8855 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008856 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008857 @Nullable
8858 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008859 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008860 if (nc == null || lp == null) return null;
8861 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008862 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008863 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008864 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008865 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008866 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008867 && !lp.hasExcludeRoute()) {
8868 return lp.getInterfaceName();
8869 }
8870 return null;
8871 }
8872
8873 /**
8874 * Returns whether we need to set interface filtering rule or not
8875 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008876 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008877 String isolationIface) {
8878 // Allow rules are always needed if VPN isolation is enabled.
8879 if (isolationIface != null) return true;
8880
8881 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8882 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8883 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09008884 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008885 }
8886
Chiachang Wang28afaff2020-12-10 22:24:47 +08008887 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8888 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8889 int index = 0;
8890 for (UidRange range : ranges) {
8891 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8892 index++;
8893 }
8894 return stableRanges;
8895 }
8896
Chalard Jeane6c95272022-01-25 21:04:21 +09008897 private static UidRangeParcel[] intsToUidRangeStableParcels(
8898 final @NonNull ArraySet<Integer> uids) {
8899 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8900 int index = 0;
8901 for (int uid : uids) {
8902 stableRanges[index] = new UidRangeParcel(uid, uid);
8903 index++;
8904 }
8905 return stableRanges;
8906 }
8907
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008908 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8909 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8910 for (int i = 0; i < ranges.length; i++) {
8911 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8912 }
8913 return stableRanges;
8914 }
8915
Motomu Utsumi93a22182023-03-16 17:04:21 +09008916 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09008917 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08008918 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8919 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09008920 if (mDeps.isAtLeastU()) {
8921 final Set<Integer> exemptUidSet = new ArraySet<>();
8922 for (final int uid: exemptUids) {
8923 exemptUidSet.add(uid);
8924 }
8925 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
8926 } else {
8927 mNetd.socketDestroy(uidRangeParcels, exemptUids);
8928 }
Ken Chen5e65a852020-12-24 12:59:10 +08008929 } catch (Exception e) {
8930 loge("Exception in socket destroy: ", e);
8931 }
8932 }
8933 }
8934
paulhuaa0743d2021-05-26 21:56:03 +08008935 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09008936 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08008937 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8938 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8939 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09008940 exemptUids[0] = VPN_UID;
8941 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08008942 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8943
Motomu Utsumi6345e462023-03-13 13:24:50 +09008944 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09008945 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008946 try {
8947 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008948 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008949 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008950 } else {
paulhu0e79d952021-06-09 16:11:35 +08008951 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008952 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008953 }
8954 } catch (Exception e) {
8955 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8956 " on netId " + nai.network.netId + ". " + e);
8957 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09008958 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09008959 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008960 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008961
lucaslin53e8a262021-06-08 01:43:59 +08008962 private boolean isProxySetOnAnyDefaultNetwork() {
8963 ensureRunningOnConnectivityServiceThread();
8964 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8965 final NetworkAgentInfo nai = nri.getSatisfier();
8966 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8967 return true;
8968 }
8969 }
8970 return false;
8971 }
8972
8973 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8974 NetworkCapabilities newNc) {
8975 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8976 // the proxy might be changed since the default network satisfied by the apps might also
8977 // changed.
8978 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8979 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008980 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8981 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008982 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008983 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8984 mProxyTracker.sendProxyBroadcast();
8985 }
8986 }
8987
Chalard Jeane6c95272022-01-25 21:04:21 +09008988 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8989 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008990 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8991 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008992 if (null == prevRanges) prevRanges = new ArraySet<>();
8993 if (null == newRanges) newRanges = new ArraySet<>();
8994 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8995
8996 prevRanges.removeAll(newRanges);
8997 newRanges.removeAll(prevRangesCopy);
8998
8999 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009000 // When updating the VPN uid routing rules, add the new range first then remove the old
9001 // range. If old range were removed first, there would be a window between the old
9002 // range being removed and the new range being added, during which UIDs contained
9003 // in both ranges are not subject to any VPN routing rules. Adding new range before
9004 // removing old range works because, unlike the filtering rules below, it's possible to
9005 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009006 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9007 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9008 // [1-5] & [1-2],[4-5] == [3]
9009 // Then we can do:
9010 // maybeCloseSockets([3])
9011 // mNetd.networkAddUidRanges([1-2],[4-5])
9012 // mNetd.networkRemoveUidRanges([1-5])
9013 // maybeCloseSockets([3])
9014 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9015 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009016 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009017 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009018 }
9019 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009020 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009021 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009022 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9023 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009024 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9025 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009026 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009027 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009028 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9029 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9030 // were added first and then newRanges got removed later, there would be only one uid
9031 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9032 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9033 // Note that this is in contrast with the (more robust) update of VPN routing rules
9034 // above, where the addition of new ranges happens before the removal of old ranges.
9035 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9036 // to be removed will never overlap with the new range to be added.
9037 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009038 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9039 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009040 }
9041 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009042 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009043 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009044 } catch (Exception e) {
9045 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009046 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009047 }
9048 }
9049
Chalard Jeande665262022-02-25 16:12:12 +09009050 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009051 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9052 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009053 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9054 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009055 if (prevEmpty && newEmpty) return;
9056
9057 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009058 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009059 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009060 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009061
9062 if (prevUids.equals(newUids)) return;
9063
9064 // This implementation is very simple and vastly faster for sets of Integers than
9065 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9066 // a key computed from the value and has storage for that.
9067 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9068 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9069 toRemove.removeAll(newUids);
9070 toAdd.removeAll(prevUids);
9071
9072 try {
9073 if (!toAdd.isEmpty()) {
9074 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9075 nai.network.netId,
9076 intsToUidRangeStableParcels(toAdd),
9077 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9078 }
9079 if (!toRemove.isEmpty()) {
9080 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9081 nai.network.netId,
9082 intsToUidRangeStableParcels(toRemove),
9083 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9084 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009085 } catch (ServiceSpecificException e) {
9086 // Has the interface disappeared since the network was built ?
9087 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009088 } catch (RemoteException e) {
9089 // Netd died. This usually causes a runtime restart anyway.
9090 }
9091 }
9092
Junyu Lai2ed7d412022-10-07 16:52:21 +08009093 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9094 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009095 ensureRunningOnConnectivityServiceThread();
9096
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009097 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009098 // Ignore updates for disconnected networks
9099 return;
9100 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009101 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009102 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009103 + "; created=" + nai.getCreatedTime()
9104 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009105 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009106 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9107 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009108 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009109 }
9110
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009111 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9112 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009113 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009114 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009115 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009116 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9117 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9118 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009119 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9120 // need to be sent as a separate extra.
9121 final NetworkRequest req = nri.isMultilayerRequest()
9122 ? nri.getActiveRequest()
9123 // Non-multilayer listen requests do not have an active request
9124 : nri.mRequests.get(0);
9125 if (req == null) {
9126 Log.wtf(TAG, "No request in NRI " + nri);
9127 }
9128 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009129 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009130 sendIntent(nri.mPendingIntent, intent);
9131 }
9132 // else not handled
9133 }
9134
9135 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9136 mPendingIntentWakeLock.acquire();
9137 try {
9138 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009139 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009140 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009141 // Explicitly disallow the receiver from starting activities, to prevent apps from
9142 // utilizing the PendingIntent as a backdoor to do this.
9143 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9144 }
9145 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9146 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009147 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009148 } catch (PendingIntent.CanceledException e) {
9149 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9150 mPendingIntentWakeLock.release();
9151 releasePendingNetworkRequest(pendingIntent);
9152 }
9153 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9154 }
9155
9156 @Override
9157 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9158 String resultData, Bundle resultExtras) {
9159 if (DBG) log("Finished sending " + pendingIntent);
9160 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009161 // Release with a delay so the receiving client has an opportunity to put in its
9162 // own request.
9163 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009164 }
9165
Chalard Jean46bfbf02022-02-02 00:56:25 +09009166 // networkAgent is only allowed to be null if notificationType is
9167 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9168 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009169 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009170 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009171 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009172 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009173 // Default request has no msgr. Also prevents callbacks from being invoked for
9174 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9175 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9176 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009177 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009178 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009179 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009180 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009181 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009182 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009183 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009184 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9185 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009186 }
Roshan Pius951c0032020-12-22 15:10:42 -08009187 final boolean includeLocationSensitiveInfo =
9188 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009189 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009190 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009191 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009192 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009193 networkCapabilitiesRestrictedForCallerPermissions(
9194 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9195 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009196 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009197 nri.mCallingAttributionTag);
9198 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009199 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9200 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08009201 // For this notification, arg1 contains the blocked status.
9202 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009203 break;
9204 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009205 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009206 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009207 break;
9208 }
9209 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009210 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009211 final NetworkCapabilities netCap =
9212 networkCapabilitiesRestrictedForCallerPermissions(
9213 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9214 putParcelable(
9215 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009216 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009217 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009218 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009219 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009220 break;
9221 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009222 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009223 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9224 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009225 break;
9226 }
junyulaif2c67e42018-08-07 19:50:45 +08009227 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009228 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009229 msg.arg1 = arg1;
9230 break;
9231 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009232 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009233 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009234 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009235 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009236 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009237 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009238 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009239 }
James Mattis45d81842021-01-10 14:24:24 -08009240 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009241 } catch (RemoteException e) {
9242 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009243 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009244 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009245 }
9246
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009247 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9248 bundle.putParcelable(t.getClass().getSimpleName(), t);
9249 }
9250
Chalard Jean0702f982021-09-16 21:50:07 +09009251 /**
9252 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9253 *
9254 * When a request should be assigned to a new network, it is normally lingered to give
9255 * time for apps to gracefully migrate their connections. When both networks are on the same
9256 * radio, but that radio can't do time-sharing efficiently, this may end up being
9257 * counter-productive because any traffic on the old network may drastically reduce the
9258 * performance of the new network.
9259 * The stack supports a configuration to let modem vendors state that their radio can't
9260 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9261 * from one cell network to another can't be done gracefully.
9262 *
9263 * @param oldNai the old network serving the request
9264 * @param newNai the new network serving the request
9265 * @return whether the switch can be graceful
9266 */
9267 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9268 @NonNull final NetworkAgentInfo newSatisfier) {
9269 if (mCellularRadioTimesharingCapable) return true;
9270 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9271 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9272 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9273 }
9274
Paul Jensenaf94b982014-09-30 15:37:41 -04009275 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009276 if (nai.numRequestNetworkRequests() != 0) {
9277 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9278 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009279 // Ignore listening and track default requests.
9280 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009281 loge("Dead network still had at least " + nr);
9282 break;
9283 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009284 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009285 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009286 }
9287
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009288 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9289 if (oldNetwork == null) {
9290 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9291 return;
9292 }
Chalard Jean49707572019-12-10 21:07:02 +09009293 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009294
9295 // If we get here it means that the last linger timeout for this network expired. So there
9296 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009297 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009298
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009299 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009300 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009301 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009302 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009303 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009304 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009305 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009306 }
9307
James Mattise3ef1912020-12-20 11:09:58 -08009308 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9309 boolean isDefaultChanged = false;
9310 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9311 final NetworkReassignment.RequestReassignment reassignment =
9312 changes.getReassignment(defaultRequestInfo);
9313 if (null == reassignment) {
9314 continue;
9315 }
9316 // reassignment only contains those instances where the satisfying network changed.
9317 isDefaultChanged = true;
9318 // Notify system services of the new default.
9319 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9320 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009321
James Mattise3ef1912020-12-20 11:09:58 -08009322 if (isDefaultChanged) {
9323 // Hold a wakelock for a short time to help apps in migrating to a new default.
9324 scheduleReleaseNetworkTransitionWakelock();
9325 }
9326 }
9327
Aaron Huang9fe47be2021-06-08 13:11:45 +08009328 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9329 if (null == oldDefaultNetwork) return;
9330 // The network stopped being the default. If it was using a PAC proxy, then the
9331 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9332 // to the local proxy server, which would forward them over the newly default network.
9333 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9334 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9335 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9336 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9337 }
9338
James Mattise3ef1912020-12-20 11:09:58 -08009339 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9340 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9341 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9342 if (DBG) {
9343 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9344 }
Chalard Jean8e382112019-12-03 20:45:30 +09009345
James Mattisd31bdfa2020-12-23 16:37:26 -08009346 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9347 if (newDefaultNetwork != null) {
9348 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009349 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009350
James Mattisd31bdfa2020-12-23 16:37:26 -08009351 // Set an app level managed default and return since further processing only applies to the
9352 // default network.
9353 if (mDefaultRequest != nri) {
9354 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9355 return;
9356 }
9357
9358 makeDefaultNetwork(newDefaultNetwork);
9359
James Mattise3ef1912020-12-20 11:09:58 -08009360 if (oldDefaultNetwork != null) {
9361 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9362 }
9363 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009364 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009365 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009366 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009367 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009368 updateTcpBufferSizes(null != newDefaultNetwork
9369 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009370 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009371 }
9372
James Mattisd31bdfa2020-12-23 16:37:26 -08009373 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9374 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9375 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9376 try {
9377 if (VDBG) {
9378 log("Setting default network for " + nri
9379 + " using UIDs " + nri.getUids()
9380 + " with old network " + (oldDefaultNetwork != null
9381 ? oldDefaultNetwork.network().getNetId() : "null")
9382 + " and new network " + (newDefaultNetwork != null
9383 ? newDefaultNetwork.network().getNetId() : "null"));
9384 }
9385 if (nri.getUids().isEmpty()) {
9386 throw new IllegalStateException("makeDefaultForApps called without specifying"
9387 + " any applications to set as the default." + nri);
9388 }
9389 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009390 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009391 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009392 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009393 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009394 }
9395 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009396 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009397 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009398 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009399 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009400 }
9401 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009402 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009403 }
9404 }
9405
Junyu Lai35665cc2022-12-19 17:37:48 +08009406 /**
9407 * Collect restricted uid ranges for the given network and UserHandle, these uids
9408 * are not restricted for matched enterprise networks but being restricted for non-matched
9409 * enterprise networks and non-enterprise networks.
9410 */
9411 @NonNull
9412 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9413 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9414 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9415 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9416 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9417
9418 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9419 // The NC is built from a `ProfileNetworkPreference` which has only one
9420 // enterprise ID, so it's guaranteed to have exactly one.
9421 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9422 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9423 continue;
9424 }
9425 }
9426
9427 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9428 pref.capabilities.getUidRanges())) {
9429 throw new IllegalArgumentException(
9430 "Overlapping uid range in preference: " + pref);
9431 }
9432 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9433 }
9434 return restrictedUidRanges;
9435 }
9436
9437 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009438 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +09009439 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009440
Junyu Lai35665cc2022-12-19 17:37:48 +08009441 ensureRunningOnConnectivityServiceThread();
9442 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9443 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9444 .getUserHandles(true /* excludeDying */);
9445 if (users.isEmpty()) {
9446 throw new IllegalStateException("No user is available");
9447 }
9448
9449 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9450 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9451 for (final UserHandle user : users) {
9452 final ArraySet<UidRange> restrictedUidRanges =
9453 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9454 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9455 UidRange.createForUser(user), restrictedUidRanges));
9456 }
9457
9458 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9459 configs.add(new NativeUidRangeConfig(
9460 nai.network.netId, rangesParcel, 0 /* subPriority */));
9461 }
9462
9463 // The netd API replaces the previous configs with the current configs.
9464 // Thus, for network disconnection or preference removal, no need to
9465 // unset previous config. Instead, collecting all currently needed
9466 // configs and issue to netd.
9467 try {
9468 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9469 } catch (ServiceSpecificException e) {
9470 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009471 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009472 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009473 // Netd died. This will cause a runtime restart anyway.
9474 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009475 }
9476 }
9477
James Mattisd31bdfa2020-12-23 16:37:26 -08009478 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9479 try {
9480 if (null != newDefaultNetwork) {
9481 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9482 } else {
9483 mNetd.networkClearDefault();
9484 }
9485 } catch (RemoteException | ServiceSpecificException e) {
9486 loge("Exception setting default network :" + e);
9487 }
9488 }
9489
Chalard Jean05cbe972019-12-09 11:50:38 +09009490 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009491 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009492 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009493 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009494 processNewlySatisfiedListenRequests(nai);
9495 }
9496
9497 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009498 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9499 if (nri.isMultilayerRequest()) {
9500 continue;
9501 }
9502 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009503 if (!nr.isListen()) continue;
9504 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009505 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009506 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9507 }
9508 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009509 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009510
Chalard Jeancd397a22019-11-22 22:33:33 +09009511 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009512 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9513 if (nri.isMultilayerRequest()) {
9514 continue;
9515 }
9516 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009517 if (!nr.isListen()) continue;
9518 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9519 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009520 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009521 }
9522 }
9523 }
9524
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009525 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009526 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009527 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009528 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009529 @Nullable public final NetworkRequest mOldNetworkRequest;
9530 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009531 @Nullable public final NetworkAgentInfo mOldNetwork;
9532 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009533 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009534 @Nullable final NetworkRequest oldNetworkRequest,
9535 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009536 @Nullable final NetworkAgentInfo oldNetwork,
9537 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009538 mNetworkRequestInfo = networkRequestInfo;
9539 mOldNetworkRequest = oldNetworkRequest;
9540 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009541 mOldNetwork = oldNetwork;
9542 mNewNetwork = newNetwork;
9543 }
Chalard Jean49707572019-12-10 21:07:02 +09009544
9545 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009546 final NetworkRequest requestToShow = null != mNewNetworkRequest
9547 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9548 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009549 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9550 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009551 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009552 }
9553
Chalard Jean46a62372019-12-10 21:25:24 +09009554 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009555
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009556 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009557 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009558 }
9559
9560 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009561 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009562 // The code is never supposed to add two reassignments of the same request. Make
9563 // sure this stays true, but without imposing this expensive check on all
9564 // reassignments on all user devices.
9565 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009566 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009567 throw new IllegalStateException("Trying to reassign ["
9568 + reassignment + "] but already have ["
9569 + existing + "]");
9570 }
9571 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009572 }
Chalard Jean46a62372019-12-10 21:25:24 +09009573 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009574 }
9575
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009576 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009577 // the passed request.
9578 @Nullable
9579 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009580 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009581 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009582 }
9583 return null;
9584 }
Chalard Jean49707572019-12-10 21:07:02 +09009585
9586 public String toString() {
9587 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9588 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009589 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009590 for (final RequestReassignment rr : getRequestReassignments()) {
9591 sj.add(rr.toString());
9592 }
9593 return sj.toString();
9594 }
9595
9596 public String debugString() {
9597 final StringBuilder sb = new StringBuilder();
9598 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009599 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009600 for (final RequestReassignment rr : getRequestReassignments()) {
9601 sb.append("\n ").append(rr);
9602 }
9603 return sb.append("\n").toString();
9604 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009605 }
9606
Chalard Jean24344d72019-12-04 13:32:31 +09009607 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009608 @Nullable final NetworkRequest previousRequest,
9609 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009610 @Nullable final NetworkAgentInfo previousSatisfier,
9611 @Nullable final NetworkAgentInfo newSatisfier,
9612 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009613 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009614 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009615 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009616 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009617 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09009618 }
James Mattisa076c532020-12-02 14:12:41 -08009619 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009620 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009621 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009622 // If this network switch can't be supported gracefully, the request is not
9623 // lingered. This allows letting go of the network sooner to reclaim some
9624 // performance on the new network, since the radio can't do both at the same
9625 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009626 //
9627 // Also don't linger the request if the old network has been destroyed.
9628 // A destroyed network does not provide actual network connectivity, so
9629 // lingering it is not useful. In particular this ensures that a destroyed
9630 // network is outscored by its replacement,
9631 // then it is torn down immediately instead of being lingered, and any apps that
9632 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009633 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9634 }
Chalard Jean24344d72019-12-04 13:32:31 +09009635 } else {
9636 if (VDBG || DDBG) log(" accepting network in place of null");
9637 }
junyulai0ac374f2020-12-14 18:41:52 +08009638
9639 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9640 // and immediately satisfies a request then remove the timer. This will happen for
9641 // all networks except in the case of an underlying network for a VCN.
9642 if (newSatisfier.isNascent()) {
9643 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009644 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009645 }
9646
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009647 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009648 newSatisfier.unlingerRequest(newRequest.requestId);
9649 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009650 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009651 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009652 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009653 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009654 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009655 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009656 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009657 }
James Mattisa076c532020-12-02 14:12:41 -08009658 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009659 }
James Mattisa076c532020-12-02 14:12:41 -08009660 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009661 }
9662
James Mattisa076c532020-12-02 14:12:41 -08009663 /**
9664 * This function is triggered when something can affect what network should satisfy what
9665 * request, and it computes the network reassignment from the passed collection of requests to
9666 * network match to the one that the system should now have. That data is encoded in an
9667 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9668 * satisfier.
9669 *
9670 * After the reassignment is computed, it is applied to the state objects.
9671 *
9672 * @param networkRequests the nri objects to evaluate for possible network reassignment
9673 * @return NetworkReassignment listing of proposed network assignment changes
9674 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009675 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009676 private NetworkReassignment computeNetworkReassignment(
9677 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009678 final NetworkReassignment changes = new NetworkReassignment();
9679
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009680 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009681 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009682 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009683 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009684 }
Chalard Jean857a1712019-12-10 21:08:07 +09009685
James Mattisa076c532020-12-02 14:12:41 -08009686 for (final NetworkRequestInfo nri : networkRequests) {
9687 // Non-multilayer listen requests can be ignored.
9688 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9689 continue;
9690 }
9691 NetworkAgentInfo bestNetwork = null;
9692 NetworkRequest bestRequest = null;
9693 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009694 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009695 // Stop evaluating as the highest possible priority request is satisfied.
9696 if (null != bestNetwork) {
9697 bestRequest = req;
9698 break;
9699 }
9700 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009701 if (null == bestNetwork && isDefaultBlocked(nri)) {
9702 // Remove default networking if disallowed for managed default requests.
9703 bestNetwork = mNoServiceNetwork;
9704 }
9705 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009706 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009707 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009708 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009709 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009710 }
9711 return changes;
9712 }
9713
James Mattisa076c532020-12-02 14:12:41 -08009714 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9715 return new HashSet<>(mNetworkRequests.values());
9716 }
9717
Paul Jensenc88b39b2015-06-16 14:27:36 -04009718 /**
James Mattisa076c532020-12-02 14:12:41 -08009719 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009720 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009721 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009722 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009723 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9724 }
9725
9726 /**
9727 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9728 * being disconnected.
9729 */
9730 private void rematchNetworksAndRequests(
9731 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9732 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009733 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009734 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009735 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009736 final long computed = SystemClock.elapsedRealtime();
9737 applyNetworkReassignment(changes, start);
9738 final long applied = SystemClock.elapsedRealtime();
9739 issueNetworkNeeds();
9740 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009741 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009742 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9743 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009744 log(changes.debugString());
9745 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009746 // Shorter form, only one line of log
9747 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9748 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009749 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009750 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009751
Chalard Jeand7f762d2019-12-10 19:01:29 +09009752 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009753 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009754 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009755
9756 // Since most of the time there are only 0 or 1 background networks, it would probably
9757 // be more efficient to just use an ArrayList here. TODO : measure performance
9758 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9759 for (final NetworkAgentInfo nai : nais) {
9760 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9761 }
9762
Chalard Jeand7f762d2019-12-10 19:01:29 +09009763 // First, update the lists of satisfied requests in the network agents. This is necessary
9764 // because some code later depends on this state to be correct, most prominently computing
9765 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009766 for (final NetworkReassignment.RequestReassignment event :
9767 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009768 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9769 event.mOldNetworkRequest, event.mNewNetworkRequest,
9770 event.mOldNetwork, event.mNewNetwork,
9771 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009772 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009773
James Mattise3ef1912020-12-20 11:09:58 -08009774 // Process default network changes if applicable.
9775 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009776
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009777 // Notify requested networks are available after the default net is switched, but
9778 // before LegacyTypeTracker sends legacy broadcasts
9779 for (final NetworkReassignment.RequestReassignment event :
9780 changes.getRequestReassignments()) {
9781 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009782 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009783 } else {
James Mattisa076c532020-12-02 14:12:41 -08009784 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009785 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009786 }
9787 }
9788
junyulai0ac374f2020-12-14 18:41:52 +08009789 // Update the inactivity state before processing listen callbacks, because the background
9790 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009791 // just yet though, because they have to be sent after the listens are processed to keep
9792 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009793 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009794 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009795 // Rematching may have altered the inactivity state of some networks, so update all
9796 // inactivity timers. updateInactivityState reads the state from the network agent
9797 // and does nothing if the state has not changed : the source of truth is controlled
9798 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9799 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009800 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009801 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009802 }
9803 }
9804
Chalard Jeanb10ab412019-12-11 14:12:30 +09009805 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009806 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009807 // Process listen requests and update capabilities if the background state has
9808 // changed for this network. For consistency with previous behavior, send onLost
9809 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009810 processNewlyLostListenRequests(nai);
9811 if (oldBackground != nai.isBackgroundNetwork()) {
9812 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009813 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009814 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009815 }
9816
junyulai0ac374f2020-12-14 18:41:52 +08009817 for (final NetworkAgentInfo nai : inactiveNetworks) {
9818 // For nascent networks, if connecting with no foreground request, skip broadcasting
9819 // LOSING for backward compatibility. This is typical when mobile data connected while
9820 // wifi connected with mobile data always-on enabled.
9821 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009822 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009823 }
9824
James Mattise3ef1912020-12-20 11:09:58 -08009825 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009826
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009827 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +00009828 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009829 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009830 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009831 // This network has active linger timers and no requests, but is not
9832 // lingering. Linger it.
9833 //
9834 // One way (the only way?) this can happen if this network is unvalidated
9835 // and became unneeded due to another network improving its score to the
9836 // point where this network will no longer be able to satisfy any requests
9837 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009838 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009839 notifyNetworkLosing(nai, now);
9840 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009841 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009842 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009843 teardownUnneededNetwork(nai);
9844 }
9845 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009846 }
9847 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009848
Chalard Jean62edfd82019-12-02 18:39:29 +09009849 /**
9850 * Apply a change in background state resulting from rematching networks with requests.
9851 *
9852 * During rematch, a network may change background states by starting to satisfy or stopping
9853 * to satisfy a foreground request. Listens don't count for this. When a network changes
9854 * background states, its capabilities need to be updated and callbacks fired for the
9855 * capability change.
9856 *
9857 * @param nai The network that changed background states
9858 */
9859 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
9860 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
9861 if (Objects.equals(nai.networkCapabilities, newNc)) return;
9862 updateNetworkPermissions(nai, newNc);
9863 nai.getAndSetNetworkCapabilities(newNc);
9864 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
9865 }
9866
Chalard Jeanf0344532019-11-19 19:23:38 +09009867 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08009868 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009869 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09009870 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
9871 changes.getReassignment(mDefaultRequest);
9872 final NetworkAgentInfo oldDefaultNetwork =
9873 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
9874 final NetworkAgentInfo newDefaultNetwork =
9875 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08009876
Chalard Jean5b409c72021-02-04 13:12:59 +09009877 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009878 // Maintain the illusion : since the legacy API only understands one network at a time,
9879 // if the default network changed, apps should see a disconnected broadcast for the
9880 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009881 if (oldDefaultNetwork != null) {
9882 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9883 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009884 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009885 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009886 // The new default network can be newly null if and only if the old default
9887 // network doesn't satisfy the default request any more because it lost a
9888 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009889 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009890 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009891 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009892 }
9893 }
9894
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009895 // Now that all the callbacks have been sent, send the legacy network broadcasts
9896 // as needed. This is necessary so that legacy requests correctly bind dns
9897 // requests to this network. The legacy users are listening for this broadcast
9898 // and will generally do a dns request so they can ensureRouteToHost and if
9899 // they do that before the callbacks happen they'll use the default network.
9900 //
9901 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
9902 // callbacks, but if apps can receive the broadcast before the callback, they still might
9903 // have an inconsistent view of networking.
9904 //
9905 // This *does* introduce a race where if the user uses the new api
9906 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
9907 // they may get old info. Reverse this after the old startUsing api is removed.
9908 // This is on top of the multiple intent sequencing referenced in the todo above.
9909 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09009910 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009911 addNetworkToLegacyTypeTracker(nai);
9912 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08009913 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009914 }
9915
Chalard Jean0354d8c2021-01-12 10:58:56 +09009916 private void issueNetworkNeeds() {
9917 ensureRunningOnConnectivityServiceThread();
9918 for (final NetworkOfferInfo noi : mNetworkOffers) {
9919 issueNetworkNeeds(noi);
9920 }
9921 }
9922
9923 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
9924 ensureRunningOnConnectivityServiceThread();
9925 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9926 informOffer(nri, noi.offer, mNetworkRanker);
9927 }
9928 }
9929
9930 /**
9931 * Inform a NetworkOffer about any new situation of a request.
9932 *
9933 * This function handles updates to offers. A number of events may happen that require
9934 * updating the registrant for this offer about the situation :
9935 * • The offer itself was updated. This may lead the offer to no longer being able
9936 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
9937 * or conversely being strengthened enough to beat the satisfier (and therefore
9938 * start being needed)
9939 * • The network satisfying a request changed (including cases where the request
9940 * starts or stops being satisfied). The new network may be a stronger or weaker
9941 * match than the old one, possibly affecting whether the offer is needed.
9942 * • The network satisfying a request updated their score. This may lead the offer
9943 * to no longer be able to beat it if the current satisfier got better, or
9944 * conversely start being a good choice if the current satisfier got weaker.
9945 *
9946 * @param nri The request
9947 * @param offer The offer. This may be an updated offer.
9948 */
9949 private static void informOffer(@NonNull NetworkRequestInfo nri,
9950 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9951 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9952 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009953
9954 // Multi-layer requests have a currently active request, the one being satisfied.
9955 // Since the system will try to bring up a better network than is currently satisfying
9956 // the request, NetworkProviders need to be told the offers matching the requests *above*
9957 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9958 // not needed, and the offer is needed for the active request iff the offer can beat
9959 // the satisfier.
9960 // For non-multilayer requests, the logic above gracefully degenerates to only the
9961 // last case.
9962 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9963 // providers that the offer is needed for this request, until the active request is found.
9964 // In a second phase, deal with the currently active request. In a third phase, inform
9965 // the providers that offer is unneeded for the remaining requests.
9966
9967 // First phase : inform providers of all requests above the active request.
9968 int i;
9969 for (i = 0; nri.mRequests.size() > i; ++i) {
9970 final NetworkRequest request = nri.mRequests.get(i);
9971 if (activeRequest == request) break; // Found the active request : go to phase 2
9972 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9973 // Since this request is higher-priority than the one currently satisfied, if the
9974 // offer can satisfy it, the provider should try and bring up the network for sure ;
9975 // no need to even ask the ranker – an offer that can satisfy is always better than
9976 // no network. Hence tell the provider so unless it already knew.
9977 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9978 offer.onNetworkNeeded(request);
9979 }
9980 }
9981
9982 // Second phase : deal with the active request (if any)
9983 if (null != activeRequest && activeRequest.isRequest()) {
9984 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009985 // If an offer can satisfy the request, it is considered needed if it is currently
9986 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009987 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009988 && satisfier.factorySerialNumber == offer.providerId
9989 && activeRequest.canBeSatisfiedBy(offer.caps);
9990 final boolean newNeeded = currentlyServing
9991 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009992 if (newNeeded != oldNeeded) {
9993 if (newNeeded) {
9994 offer.onNetworkNeeded(activeRequest);
9995 } else {
9996 // The offer used to be able to beat the satisfier. Now it can't.
9997 offer.onNetworkUnneeded(activeRequest);
9998 }
9999 }
10000 }
10001
10002 // Third phase : inform the providers that the offer isn't needed for any request
10003 // below the active one.
10004 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10005 final NetworkRequest request = nri.mRequests.get(i);
10006 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10007 // Since this request is lower-priority than the one currently satisfied, if the
10008 // offer can satisfy it, the provider should not try and bring up the network.
10009 // Hence tell the provider so unless it already knew.
10010 if (offer.neededFor(request)) {
10011 offer.onNetworkUnneeded(request);
10012 }
10013 }
10014 }
10015
Chalard Jean61c79252019-11-07 23:07:32 +090010016 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10017 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10018 NetworkRequest nr = nai.requestAt(i);
10019 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10020 // legacy type tracker filters out repeat adds
10021 mLegacyTypeTracker.add(nr.legacyType, nai);
10022 }
10023 }
10024
10025 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010026 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010027 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10028 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10029 if (nai.isVPN()) {
10030 mLegacyTypeTracker.add(TYPE_VPN, nai);
10031 }
10032 }
10033
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010034 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010035 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010036 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010037 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010038 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010039 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010040
Chalard Jean254bd162022-08-25 13:04:51 +090010041 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010042 // Don't repeat publish.
10043 if (newInetCondition == mDefaultInetConditionPublished) return;
10044
10045 mDefaultInetConditionPublished = newInetCondition;
10046 sendInetConditionBroadcast(nai.networkInfo);
10047 }
10048
Chalard Jeand61375d2020-01-14 22:46:36 +090010049 @NonNull
10050 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10051 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010052 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010053 final boolean suspended =
10054 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10055 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10056 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10057 // state. This is because the network could have been suspended before connecting,
10058 // or it could be disconnecting while being suspended, and in both these cases
10059 // the state should not be overridden. Note that the only detailed state that
10060 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10061 // worry about multiple different substates of CONNECTED.
10062 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10063 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010064 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10065 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10066 // network agent is created, then goes to suspended, then goes out of suspended without
10067 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010068 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010069 ? NetworkInfo.DetailedState.CONNECTED
10070 : NetworkInfo.DetailedState.CONNECTING,
10071 info.getReason(),
10072 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010073 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010074 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010075 return newInfo;
10076 }
10077
10078 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10079 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10080
Erik Kline99f301b2017-02-15 19:59:17 +090010081 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010082 NetworkInfo oldInfo = null;
10083 synchronized (networkAgent) {
10084 oldInfo = networkAgent.networkInfo;
10085 networkAgent.networkInfo = newInfo;
10086 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010087
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010088 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010089 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10090 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010091 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010092
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010093 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010094 // A network that has just connected has zero requests and is thus a foreground network.
10095 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10096
Luke Huangfdd11f82019-04-09 18:41:49 +080010097 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010098
10099 networkAgent.setCreated();
10100
10101 // If the network is created immediately on register, then apply the LinkProperties now.
10102 // Otherwise, this is done further down when the network goes into connected state.
10103 // Applying the LinkProperties means that the network is ready to carry traffic -
10104 // interfaces and routing rules have been added, DNS servers programmed, etc.
10105 // For VPNs, this must be done before the capabilities are updated, because as soon as
10106 // that happens, UIDs are routed to the network.
10107 if (shouldCreateNetworksImmediately()) {
10108 applyInitialLinkProperties(networkAgent);
10109 }
10110
10111 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10112 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010113 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010114 // Initialize the network's capabilities to their starting values according to the
10115 // underlying networks. This ensures that the capabilities are correct before
10116 // anything happens to the network.
10117 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010118 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010119 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010120 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010121 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010122 }
10123
Chalard Jean254bd162022-08-25 13:04:51 +090010124 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10125 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010126
lucaslin45e639b2019-04-03 17:09:28 +080010127 // NetworkCapabilities need to be set before sending the private DNS config to
10128 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010129 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10130
Erik Kline9a62f012018-03-21 07:18:33 -070010131 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010132 if (!shouldCreateNetworksImmediately()) {
10133 applyInitialLinkProperties(networkAgent);
10134 } else {
10135 // The network was created when the agent registered, and the LinkProperties are
10136 // already up-to-date. However, updateLinkProperties also makes some changes only
10137 // when the network connects. Apply those changes here. On T and below these are
10138 // handled by the applyInitialLinkProperties call just above.
10139 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10140 // If something depends on both LinkProperties and connected state, it should be in
10141 // this method as well.
10142 networkAgent.clatd.update();
10143 updateProxy(networkAgent.linkProperties, null);
10144 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010145
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010146 // If a rate limit has been configured and is applicable to this network (network
10147 // provides internet connectivity), apply it. The tc police filter cannot be attached
10148 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
10149 // updateInterfaces -> INetd#networkAddInterface.
10150 // Note: in case of a system server crash, the NetworkController constructor in netd
10151 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10152 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10153 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10154 mIngressRateLimit);
10155 }
10156
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010157 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10158 // command must be sent after updating LinkProperties to maximize chances of
10159 // NetworkMonitor seeing the correct LinkProperties when starting.
10160 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010161 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010162 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010163 }
Chalard Jeand4900722022-02-06 12:25:38 +090010164 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10165 params.networkAgentConfig = networkAgent.networkAgentConfig;
10166 params.networkCapabilities = networkAgent.networkCapabilities;
10167 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10168 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010169 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10170 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10171 // call that would cause a Log.wtf to be emitted from the system_server process, and
10172 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10173 // process to check the interface version, just use an SDK check. NetworkStack will
10174 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010175 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010176 networkAgent.networkMonitor().notifyNetworkConnected(params);
10177 } else {
10178 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10179 params.networkCapabilities);
10180 }
Chalard Jean0f141332023-06-05 19:26:17 +090010181 final long evaluationDelay;
10182 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10183 // If the network is anything other than pure wifi, use the default timeout.
10184 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10185 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10186 // If the network is explicitly selected, use the default timeout because it's
10187 // shorter and the user is likely staring at the screen expecting it to validate
10188 // right away.
10189 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10190 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10191 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10192 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10193 } else {
10194 // It's wifi, automatically connected, and bad wifi is preferred : use the
10195 // longer timeout to avoid the device switching to captive portals with bad
10196 // signal or very slow response.
10197 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10198 }
10199 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010200
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010201 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10202 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10203 // capabilities, so it only needs to be done once on initial connect, not every time the
10204 // network's capabilities change. Note that we do this before rematching the network,
10205 // so we could decide to tear it down immediately afterwards. That's fine though - on
10206 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10207 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010208 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010209
junyulai0ac374f2020-12-14 18:41:52 +080010210 // Before first rematching networks, put an inactivity timer without any request, this
10211 // allows {@code updateInactivityState} to update the state accordingly and prevent
10212 // tearing down for any {@code unneeded} evaluation in this period.
10213 // Note that the timer will not be rescheduled since the expiry time is
10214 // fixed after connection regardless of the network satisfying other requests or not.
10215 // But it will be removed as soon as the network satisfies a request for the first time.
10216 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10217 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010218 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010219
Paul Jensen05e85ee2014-09-11 11:00:39 -040010220 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010221 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010222
10223 // This has to happen after matching the requests, because callbacks are just requests.
10224 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010225 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010226 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010227 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010228 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010229 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010230 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010231 if (networkAgent.isVPN()) {
10232 // As the active or bound network changes for apps, broadcast the default proxy, as
10233 // apps may need to update their proxy data. This is called after disconnecting from
10234 // VPN to make sure we do not broadcast the old proxy data.
10235 // TODO(b/122649188): send the broadcast only to VPN users.
10236 mProxyTracker.sendProxyBroadcast();
10237 }
Chalard Jean254bd162022-08-25 13:04:51 +090010238 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10239 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010240 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010241 }
10242 }
10243
Chalard Jean28018572020-12-21 18:36:52 +090010244 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010245 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10246 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010247 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010248 }
10249
Erik Kline99f301b2017-02-15 19:59:17 +090010250 // Notify only this one new request of the current state. Transfer all the
10251 // current state by calling NetworkCapabilities and LinkProperties callbacks
10252 // so that callers can be guaranteed to have as close to atomicity in state
10253 // transfer as can be supported by this current API.
10254 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010255 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010256 if (nri.mPendingIntent != null) {
10257 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10258 // Attempt no subsequent state pushes where intents are involved.
10259 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010260 }
Erik Kline99f301b2017-02-15 19:59:17 +090010261
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010262 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010263 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010264 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10265 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10266 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010267 }
10268
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010269 // Notify the requests on this NAI that the network is now lingered.
10270 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010271 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010272 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10273 }
10274
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010275 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10276 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10277 return vpnBlocked
10278 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10279 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10280 }
10281
10282 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10283 if (blockedReasons == BLOCKED_REASON_NONE) {
10284 mUidBlockedReasons.delete(uid);
10285 } else {
10286 mUidBlockedReasons.put(uid, blockedReasons);
10287 }
10288 }
10289
junyulaif2c67e42018-08-07 19:50:45 +080010290 /**
10291 * Notify of the blocked state apps with a registered callback matching a given NAI.
10292 *
10293 * Unlike other callbacks, blocked status is different between each individual uid. So for
10294 * any given nai, all requests need to be considered according to the uid who filed it.
10295 *
10296 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010297 * @param oldMetered True if the previous network capabilities were metered.
10298 * @param newMetered True if the current network capabilities are metered.
10299 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10300 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010301 */
10302 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010303 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10304 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010305
10306 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10307 NetworkRequest nr = nai.requestAt(i);
10308 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010309
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010310 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10311 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10312 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010313 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010314 : oldVpnBlocked;
10315
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010316 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10317 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10318 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010319 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010320 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010321 }
10322 }
10323 }
10324
10325 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010326 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010327 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010328 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010329 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010330 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010331 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010332 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010333 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010334
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010335 final int oldBlockedState = getBlockedState(
10336 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10337 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10338 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010339 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010340 }
junyulaif2c67e42018-08-07 19:50:45 +080010341 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10342 NetworkRequest nr = nai.requestAt(i);
10343 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010344 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010345 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10346 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010347 }
10348 }
10349 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010350 }
10351
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010352 @VisibleForTesting
10353 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010354 // The NetworkInfo we actually send out has no bearing on the real
10355 // state of affairs. For example, if the default connection is mobile,
10356 // and a request for HIPRI has just gone away, we need to pretend that
10357 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10358 // the state to DISCONNECTED, even though the network is of type MOBILE
10359 // and is still connected.
10360 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10361 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010362 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010363 if (state != DetailedState.DISCONNECTED) {
10364 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010365 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010366 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010367 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010368 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10369 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10370 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10371 if (info.isFailover()) {
10372 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10373 nai.networkInfo.setFailover(false);
10374 }
10375 if (info.getReason() != null) {
10376 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10377 }
10378 if (info.getExtraInfo() != null) {
10379 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10380 }
10381 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010382 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010383 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010384 if (newDefaultAgent != null) {
10385 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10386 newDefaultAgent.networkInfo);
10387 } else {
10388 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10389 }
10390 }
10391 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10392 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010393 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010394 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010395 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010396 }
10397 }
10398 }
10399
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010400 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010401 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010402 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010403 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010404 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010405 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10406 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010407 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10408 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010409 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010410 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010411 } else {
10412 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10413 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010414 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010415 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010416
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010417 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10418 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10419 }
10420
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010421 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010422 * Returns the list of all interfaces that could be used by network traffic that does not
10423 * explicitly specify a network. This includes the default network, but also all VPNs that are
10424 * currently connected.
10425 *
10426 * Must be called on the handler thread.
10427 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010428 @NonNull
10429 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010430 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010431 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010432 final Set<Integer> activeNetIds = new ArraySet<>();
10433 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10434 if (nri.isBeingSatisfied()) {
10435 activeNetIds.add(nri.getSatisfier().network().netId);
10436 }
10437 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010438 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010439 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010440 defaultNetworks.add(nai.network);
10441 }
10442 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010443 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010444 }
10445
10446 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010447 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10448 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010449 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010450 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010451 ensureRunningOnConnectivityServiceThread();
10452 String activeIface = null;
10453 LinkProperties activeLinkProperties = getActiveLinkProperties();
10454 if (activeLinkProperties != null) {
10455 activeIface = activeLinkProperties.getInterfaceName();
10456 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010457
junyulai2050bed2021-01-23 09:46:34 +080010458 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010459 try {
junyulaide41fc22021-01-22 22:46:01 +080010460 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010461 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010462 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10463 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010464 } catch (Exception ignored) {
10465 }
10466 }
10467
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010468 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010469 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010470 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010471 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010472 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010473
10474 if (!TextUtils.isEmpty(settingUrl)) {
10475 return settingUrl;
10476 }
10477
10478 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010479 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010480 if (!TextUtils.isEmpty(settingUrl)) {
10481 return settingUrl;
10482 }
10483
10484 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010485 }
10486
10487 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010488 public void startNattKeepalive(Network network, int intervalSeconds,
10489 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010490 enforceKeepalivePermission();
10491 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010492 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010493 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10494 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010495 // false and set the underpinned network to null because there is no way and no
10496 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10497 // deprecated method.
10498 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010499 }
10500
10501 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010502 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010503 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010504 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010505 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010506 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010507 mKeepaliveTracker.startNattKeepalive(
10508 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010509 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10510 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010511 } finally {
10512 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10513 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010514 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10515 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010516 }
10517 }
junyulaid05a1922019-01-15 11:32:44 +080010518 }
10519
10520 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010521 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010522 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010523 try {
10524 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010525 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010526 mKeepaliveTracker.startTcpKeepalive(
10527 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10528 } finally {
10529 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10530 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010531 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10532 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010533 }
10534 }
junyulai0835a1e2019-01-08 20:04:33 +080010535 }
10536
10537 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010538 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010539 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010540 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10541 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010542 }
10543
10544 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090010545 public int[] getSupportedKeepalives() {
10546 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10547 // Backwards compatibility with CTS 13
10548 android.Manifest.permission.QUERY_ALL_PACKAGES);
10549
10550 return BinderUtils.withCleanCallingIdentity(() ->
10551 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10552 }
10553
10554 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010555 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010556 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010557
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010558 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010559 final long token = Binder.clearCallingIdentity();
10560 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010561 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10562 UserHandle.getUserHandleForUid(uid))) {
10563 return;
10564 }
10565
Heemin Seogdb8489d2019-06-12 09:21:44 -070010566 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10567 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010568
10569 // Turn airplane mode off
10570 setAirplaneMode(false);
10571
10572 // restore private DNS settings to default mode (opportunistic)
10573 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10574 UserHandle.getUserHandleForUid(uid))) {
10575 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10576 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10577 }
10578
10579 Settings.Global.putString(mContext.getContentResolver(),
10580 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010581 } finally {
10582 Binder.restoreCallingIdentity(token);
10583 }
Stuart Scottd5463642015-04-02 18:00:02 -070010584 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010585
Ricky Wai7097cc92018-01-23 04:09:45 +000010586 @Override
10587 public byte[] getNetworkWatchlistConfigHash() {
10588 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10589 if (nwm == null) {
10590 loge("Unable to get NetworkWatchlistManager");
10591 return null;
10592 }
10593 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10594 return nwm.getWatchlistConfigHash();
10595 }
10596
Hugo Benichibe0c7652016-05-31 16:28:06 +090010597 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010598 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010599 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010600 }
Hugo Benichif4210292017-04-21 15:07:12 +090010601
10602 private static boolean toBool(int encodedBoolean) {
10603 return encodedBoolean != 0; // Only 0 means false.
10604 }
10605
10606 private static int encodeBool(boolean b) {
10607 return b ? 1 : 0;
10608 }
mswest4632928412018-03-12 10:34:34 -070010609
10610 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010611 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10612 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10613 @NonNull String[] args) {
10614 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10615 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010616 }
10617
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010618 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010619 @Override
10620 public int onCommand(String cmd) {
10621 if (cmd == null) {
10622 return handleDefaultCommands(cmd);
10623 }
10624 final PrintWriter pw = getOutPrintWriter();
10625 try {
10626 switch (cmd) {
10627 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010628 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
10629 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070010630 final String action = getNextArg();
10631 if ("enable".equals(action)) {
10632 setAirplaneMode(true);
10633 return 0;
10634 } else if ("disable".equals(action)) {
10635 setAirplaneMode(false);
10636 return 0;
10637 } else if (action == null) {
10638 final ContentResolver cr = mContext.getContentResolver();
10639 final int enabled = Settings.Global.getInt(cr,
10640 Settings.Global.AIRPLANE_MODE_ON);
10641 pw.println(enabled == 0 ? "disabled" : "enabled");
10642 return 0;
10643 } else {
10644 onHelp();
10645 return -1;
10646 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010647 case "reevaluate":
10648 // Usage : adb shell cmd connectivity reevaluate <netId>
10649 // If netId is omitted, then reevaluate the default network
10650 final String netId = getNextArg();
10651 final NetworkAgentInfo nai;
10652 if (null == netId) {
10653 // Note that the command is running on the wrong thread to call this,
10654 // so this could in principle return stale data. But it can't crash.
10655 nai = getDefaultNetwork();
10656 } else {
10657 // If netId can't be parsed, this throws NumberFormatException, which
10658 // is passed back to adb who prints it.
10659 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10660 }
10661 if (null == nai) {
10662 pw.println("Unknown network (net ID not found or no default network)");
10663 return 0;
10664 }
10665 Log.d(TAG, "Reevaluating network " + nai.network);
10666 reportNetworkConnectivity(nai.network, !nai.isValidated());
10667 return 0;
mswest4632928412018-03-12 10:34:34 -070010668 default:
10669 return handleDefaultCommands(cmd);
10670 }
10671 } catch (Exception e) {
10672 pw.println(e);
10673 }
10674 return -1;
10675 }
10676
10677 @Override
10678 public void onHelp() {
10679 PrintWriter pw = getOutPrintWriter();
10680 pw.println("Connectivity service commands:");
10681 pw.println(" help");
10682 pw.println(" Print this help text.");
10683 pw.println(" airplane-mode [enable|disable]");
10684 pw.println(" Turn airplane mode on or off.");
10685 pw.println(" airplane-mode");
10686 pw.println(" Get airplane mode.");
10687 }
10688 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010689
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010690 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010691 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10692 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10693 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010694 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010695 }
10696
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010697 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10698 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010699 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10700 final TransportInfo newInfo = nc.getTransportInfo();
10701 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10702 return;
10703 }
10704 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010705 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010706 }
10707 }
10708
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010709 /**
10710 * @param connectionInfo the connection to resolve.
10711 * @return {@code uid} if the connection is found and the app has permission to observe it
10712 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10713 * connection is not found.
10714 */
10715 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010716 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10717 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10718 }
10719
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010720 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010721 connectionInfo.local, connectionInfo.remote);
10722
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010723 if (uid == INVALID_UID) return uid; // Not found.
10724
10725 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10726 // VPN, if any, that applies to the UID that owns the connection.
10727 if (checkNetworkStackPermission()) return uid;
10728
10729 final NetworkAgentInfo vpn = getVpnForUid(uid);
10730 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010731 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010732 return INVALID_UID;
10733 }
10734
10735 return uid;
10736 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010737
Benedict Wong493e04b2018-11-09 14:45:34 -080010738 /**
10739 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10740 *
10741 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10742 */
10743 @Override
10744 public IBinder startOrGetTestNetworkService() {
10745 synchronized (mTNSLock) {
10746 TestNetworkService.enforceTestNetworkPermissions(mContext);
10747
10748 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010749 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010750 }
10751
10752 return mTNS;
10753 }
10754 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010755
Cody Kesting73708bf2019-12-18 10:57:50 -080010756 /**
10757 * Handler used for managing all Connectivity Diagnostics related functions.
10758 *
10759 * @see android.net.ConnectivityDiagnosticsManager
10760 *
10761 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10762 */
10763 @VisibleForTesting
10764 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010765 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10766
Cody Kesting73708bf2019-12-18 10:57:50 -080010767 /**
10768 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10769 * android.net.ConnectivityDiagnosticsManager}.
10770 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10771 * NetworkRequestInfo to be registered
10772 */
10773 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10774
10775 /**
10776 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10777 * android.net.ConnectivityDiagnosticsManager}.
10778 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10779 * arg1 = the uid of the caller
10780 */
10781 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10782
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010783 /**
10784 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010785 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010786 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10787 * NetworkMonitor.
10788 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010789 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010790 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010791
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010792 /**
10793 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10794 * been detected on the network.
10795 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10796 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10797 * arg2 = NetID.
10798 * data = PersistableBundle of extras passed from NetworkMonitor.
10799 */
10800 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10801
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010802 /**
10803 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10804 * the platform. This event will invoke {@link
10805 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10806 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070010807 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010808 */
10809 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
10810
Cody Kesting73708bf2019-12-18 10:57:50 -080010811 private ConnectivityDiagnosticsHandler(Looper looper) {
10812 super(looper);
10813 }
10814
10815 @Override
10816 public void handleMessage(Message msg) {
10817 switch (msg.what) {
10818 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10819 handleRegisterConnectivityDiagnosticsCallback(
10820 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
10821 break;
10822 }
10823 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10824 handleUnregisterConnectivityDiagnosticsCallback(
10825 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
10826 break;
10827 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010828 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010829 final ConnectivityReportEvent reportEvent =
10830 (ConnectivityReportEvent) msg.obj;
10831
Aaron Huang959d3642021-01-21 15:47:41 +080010832 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010833 break;
10834 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010835 case EVENT_DATA_STALL_SUSPECTED: {
10836 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080010837 final Pair<Long, PersistableBundle> arg =
10838 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010839 if (nai == null) break;
10840
Aaron Huang959d3642021-01-21 15:47:41 +080010841 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010842 break;
10843 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010844 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070010845 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010846 break;
10847 }
10848 default: {
10849 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
10850 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010851 }
10852 }
10853 }
10854
10855 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
10856 @VisibleForTesting
10857 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
10858 @NonNull private final IConnectivityDiagnosticsCallback mCb;
10859 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010860 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010861
10862 @VisibleForTesting
10863 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010864 @NonNull IConnectivityDiagnosticsCallback cb,
10865 @NonNull NetworkRequestInfo nri,
10866 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010867 mCb = cb;
10868 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010869 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010870 }
10871
10872 @Override
10873 public void binderDied() {
10874 log("ConnectivityDiagnosticsCallback IBinder died.");
10875 unregisterConnectivityDiagnosticsCallback(mCb);
10876 }
10877 }
10878
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010879 /**
10880 * Class used for sending information from {@link
10881 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
10882 */
10883 private static class NetworkTestedResults {
10884 private final int mNetId;
10885 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010886 @Nullable private final String mRedirectUrl;
10887
10888 private NetworkTestedResults(
10889 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
10890 mNetId = netId;
10891 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010892 mRedirectUrl = redirectUrl;
10893 }
10894 }
10895
10896 /**
10897 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
10898 * ConnectivityDiagnosticsHandler}.
10899 */
10900 private static class ConnectivityReportEvent {
10901 private final long mTimestampMillis;
10902 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080010903 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010904
Aaron Huang959d3642021-01-21 15:47:41 +080010905 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
10906 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010907 mTimestampMillis = timestampMillis;
10908 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080010909 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010910 }
10911 }
10912
Cody Kestingf1120be2020-08-03 18:01:40 -070010913 /**
10914 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
10915 * ConnectivityDiagnosticsHandler}.
10916 */
10917 private static class ReportedNetworkConnectivityInfo {
10918 public final boolean hasConnectivity;
10919 public final boolean isNetworkRevalidating;
10920 public final int reporterUid;
10921 @NonNull public final NetworkAgentInfo nai;
10922
10923 private ReportedNetworkConnectivityInfo(
10924 boolean hasConnectivity,
10925 boolean isNetworkRevalidating,
10926 int reporterUid,
10927 @NonNull NetworkAgentInfo nai) {
10928 this.hasConnectivity = hasConnectivity;
10929 this.isNetworkRevalidating = isNetworkRevalidating;
10930 this.reporterUid = reporterUid;
10931 this.nai = nai;
10932 }
10933 }
10934
Cody Kesting73708bf2019-12-18 10:57:50 -080010935 private void handleRegisterConnectivityDiagnosticsCallback(
10936 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
10937 ensureRunningOnConnectivityServiceThread();
10938
10939 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080010940 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010941 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
10942
James Mattis64b8b0f2020-11-24 17:40:49 -080010943 // Connectivity Diagnostics are meant to be used with a single network request. It would be
10944 // confusing for these networks to change when an NRI is satisfied in another layer.
10945 if (nri.isMultilayerRequest()) {
10946 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
10947 + "network requests.");
10948 }
10949
Cody Kesting73708bf2019-12-18 10:57:50 -080010950 // This means that the client registered the same callback multiple times. Do
10951 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080010952 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010953 if (VDBG) log("Diagnostics callback is already registered");
10954
10955 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10956 // incremented when the NetworkRequestInfo is created as part of
10957 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010958 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080010959 return;
10960 }
10961
Cody Kesting31f1ff62020-03-05 10:46:02 -080010962 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080010963
10964 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080010965 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010966 } catch (RemoteException e) {
10967 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080010968 return;
10969 }
10970
10971 // Once registered, provide ConnectivityReports for matching Networks
10972 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
10973 synchronized (mNetworkForNetId) {
10974 for (int i = 0; i < mNetworkForNetId.size(); i++) {
10975 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080010976 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
10977 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080010978 matchingNetworks.add(nai);
10979 }
10980 }
10981 }
10982 for (final NetworkAgentInfo nai : matchingNetworks) {
10983 final ConnectivityReport report = nai.getConnectivityReport();
10984 if (report == null) {
10985 continue;
10986 }
10987 if (!checkConnectivityDiagnosticsPermissions(
10988 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10989 continue;
10990 }
10991
10992 try {
10993 cb.onConnectivityReportAvailable(report);
10994 } catch (RemoteException e) {
10995 // Exception while sending the ConnectivityReport. Move on to the next network.
10996 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010997 }
10998 }
10999
11000 private void handleUnregisterConnectivityDiagnosticsCallback(
11001 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11002 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011003 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011004
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011005 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11006 mConnectivityDiagnosticsCallbacks.remove(iCb);
11007 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011008 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11009 return;
11010 }
11011
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011012 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011013
Cody Kesting70fa2b22020-12-02 12:16:56 -080011014 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11015 // (if the Binder died)
11016 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11017 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011018 return;
11019 }
11020
Cody Kesting46cb1672020-03-04 13:35:20 -080011021 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11022 // incremented when the NetworkRequestInfo is created as part of
11023 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011024 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011025
Cody Kesting31f1ff62020-03-05 10:46:02 -080011026 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011027 }
11028
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011029 private void handleNetworkTestedWithExtras(
11030 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11031 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011032 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011033 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011034 final ConnectivityReport report =
11035 new ConnectivityReport(
11036 reportEvent.mNai.network,
11037 reportEvent.mTimestampMillis,
11038 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011039 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011040 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011041 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011042
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011043 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011044 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011045 for (final IConnectivityDiagnosticsCallback cb : results) {
11046 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011047 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011048 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011049 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011050 }
11051 }
11052 }
11053
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011054 private void handleDataStallSuspected(
11055 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11056 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011057 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011058 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011059 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011060 new DataStallReport(
11061 nai.network,
11062 timestampMillis,
11063 detectionMethod,
11064 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011065 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011066 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011067 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011068 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011069 for (final IConnectivityDiagnosticsCallback cb : results) {
11070 try {
11071 cb.onDataStallSuspected(report);
11072 } catch (RemoteException ex) {
11073 loge("Error invoking onDataStallSuspected", ex);
11074 }
11075 }
11076 }
11077
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011078 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011079 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11080 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11081 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11082
11083 // If the Network is being re-validated as a result of this call to
11084 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11085 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011086 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011087 getMatchingPermissionedCallbacks(
11088 nai,
11089 reportedNetworkConnectivityInfo.isNetworkRevalidating
11090 ? Process.INVALID_UID
11091 : reportedNetworkConnectivityInfo.reporterUid);
11092
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011093 for (final IConnectivityDiagnosticsCallback cb : results) {
11094 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011095 cb.onNetworkConnectivityReported(
11096 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011097 } catch (RemoteException ex) {
11098 loge("Error invoking onNetworkConnectivityReported", ex);
11099 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011100
11101 // If the Network isn't re-validating, also provide the cached report. If there is no
11102 // cached report, the Network is still being validated and a report will be sent once
11103 // validation is complete. Note that networks which never undergo validation will still
11104 // have a cached ConnectivityReport with RESULT_SKIPPED.
11105 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11106 try {
11107 cb.onConnectivityReportAvailable(cachedReport);
11108 } catch (RemoteException ex) {
11109 loge("Error invoking onConnectivityReportAvailable", ex);
11110 }
11111 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011112 }
11113 }
11114
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011115 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011116 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11117 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011118 sanitized.setUids(null);
11119 sanitized.setAdministratorUids(new int[0]);
11120 sanitized.setOwnerUid(Process.INVALID_UID);
11121 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011122 }
11123
Cody Kestingf1120be2020-08-03 18:01:40 -070011124 /**
11125 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11126 *
11127 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11128 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011129 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011130 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011131 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011132 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011133 mConnectivityDiagnosticsCallbacks.entrySet()) {
11134 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11135 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011136
James Mattis64b8b0f2020-11-24 17:40:49 -080011137 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011138 if (!nai.satisfies(nri.mRequests.get(0))) {
11139 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011140 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011141
11142 // UID for this callback must either be:
11143 // - INVALID_UID (which sends callbacks to all UIDs), or
11144 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11145 // notified as a result)
11146 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11147 continue;
11148 }
11149
11150 if (!checkConnectivityDiagnosticsPermissions(
11151 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11152 continue;
11153 }
11154
11155 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011156 }
11157 return results;
11158 }
11159
Cody Kesting7474f672021-05-11 14:22:40 -070011160 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11161 @NonNull NetworkAgentInfo nai) {
11162 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11163 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11164 }
11165
Cody Kesting160ef392021-05-05 13:17:22 -070011166 private boolean hasLocationPermission(String packageName, int uid) {
11167 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11168 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11169 // call in a try-catch.
11170 try {
11171 if (!mLocationPermissionChecker.checkLocationPermission(
11172 packageName, null /* featureId */, uid, null /* message */)) {
11173 return false;
11174 }
11175 } catch (SecurityException e) {
11176 return false;
11177 }
11178
11179 return true;
11180 }
11181
11182 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11183 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011184 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011185 && virtual.networkCapabilities.getOwnerUid() == uid
11186 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11187 return true;
11188 }
11189 }
11190
11191 return false;
11192 }
11193
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011194 @VisibleForTesting
11195 boolean checkConnectivityDiagnosticsPermissions(
11196 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
11197 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
11198 return true;
11199 }
11200
Cody Kesting160ef392021-05-05 13:17:22 -070011201 // Administrator UIDs also contains the Owner UID
11202 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11203 if (!CollectionUtils.contains(administratorUids, callbackUid)
11204 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011205 return false;
11206 }
11207
Cody Kesting7474f672021-05-11 14:22:40 -070011208 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11209 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011210 }
11211
Cody Kestingd199a9d2019-12-17 12:55:28 -080011212 @Override
11213 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011214 @NonNull IConnectivityDiagnosticsCallback callback,
11215 @NonNull NetworkRequest request,
11216 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011217 Objects.requireNonNull(callback, "callback must not be null");
11218 Objects.requireNonNull(request, "request must not be null");
11219 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11220
Cody Kesting73708bf2019-12-18 10:57:50 -080011221 if (request.legacyType != TYPE_NONE) {
11222 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11223 + " Please use NetworkCapabilities instead.");
11224 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011225 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011226 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011227
11228 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11229 // and administrator uids to be safe.
11230 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011231 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011232
11233 final NetworkRequest requestWithId =
11234 new NetworkRequest(
11235 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11236
11237 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11238 //
11239 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11240 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11241 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011242 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011243 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011244 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011245
11246 mConnectivityDiagnosticsHandler.sendMessage(
11247 mConnectivityDiagnosticsHandler.obtainMessage(
11248 ConnectivityDiagnosticsHandler
11249 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11250 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011251 }
11252
11253 @Override
11254 public void unregisterConnectivityDiagnosticsCallback(
11255 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011256 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011257 mConnectivityDiagnosticsHandler.sendMessage(
11258 mConnectivityDiagnosticsHandler.obtainMessage(
11259 ConnectivityDiagnosticsHandler
11260 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011261 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011262 0,
11263 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011264 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011265
Yan Yanfe96dde2022-12-05 23:00:01 +000011266 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11267 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11268 if (underlyingNetworks == null) return false;
11269
11270 for (Network network : underlyingNetworks) {
11271 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11272 return true;
11273 }
11274 }
11275 return false;
11276 }
11277
Cody Kestingf53a0752020-04-15 12:33:28 -070011278 @Override
11279 public void simulateDataStall(int detectionMethod, long timestampMillis,
11280 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011281 Objects.requireNonNull(network, "network must not be null");
11282 Objects.requireNonNull(extras, "extras must not be null");
11283
paulhu3ffffe72021-09-16 10:15:22 +080011284 enforceAnyPermissionOf(mContext,
11285 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011286 android.Manifest.permission.NETWORK_STACK);
11287 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011288 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11289 throw new SecurityException(
11290 "Data Stall simulation is only possible for test networks or networks built on"
11291 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011292 }
11293
11294 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011295 if (nai == null
11296 || (nai.creatorUid != mDeps.getCallingUid()
11297 && nai.creatorUid != Process.SYSTEM_UID)) {
11298 throw new SecurityException(
11299 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011300 }
11301
Cody Kesting652e3ec2020-05-21 12:08:21 -070011302 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11303 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11304 // Data Stall information as a DataStallReportParcelable and passing to
11305 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11306 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011307 final DataStallReportParcelable p = new DataStallReportParcelable();
11308 p.timestampMillis = timestampMillis;
11309 p.detectionMethod = detectionMethod;
11310
11311 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11312 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11313 }
11314 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11315 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11316 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11317 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11318 }
11319
Serik Beketayevec8ad212020-12-07 22:43:07 -080011320 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011321 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011322
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011323 /**
11324 * Class to hold the information for network activity change event from idle timers
11325 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
11326 */
11327 private static final class NetworkActivityParams {
11328 public final boolean isActive;
11329 // Label used for idle timer. Transport type is used as label.
11330 // label is int since NMS was using the identifier as int, and it has not been changed
11331 public final int label;
11332 public final long timestampNs;
11333 // Uid represents the uid that was responsible for waking the radio.
11334 // -1 for no uid and uid is -1 if isActive is false.
11335 public final int uid;
11336
11337 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
11338 this.isActive = isActive;
11339 this.label = label;
11340 this.timestampNs = timestampNs;
11341 this.uid = uid;
11342 }
11343 }
11344
lucaslin66f44212021-02-23 01:12:55 +080011345 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11346 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011347 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080011348 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011349 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
11350 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080011351 }
lucaslin37a16d92021-01-21 19:48:09 +080011352
11353 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011354 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011355 mHandler.post(() -> {
11356 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
11357 nai.clatd.interfaceLinkStateChanged(iface, up);
11358 }
11359 });
lucaslin37a16d92021-01-21 19:48:09 +080011360 }
11361
11362 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011363 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011364 mHandler.post(() -> {
11365 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
11366 nai.clatd.interfaceRemoved(iface);
11367 }
11368 });
lucaslin66f44212021-02-23 01:12:55 +080011369 }
11370 }
11371
lucaslin1a8b4c62021-01-21 02:02:55 +080011372 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11373
11374 /**
11375 * Class used for updating network activity tracking with netd and notify network activity
11376 * changes.
11377 */
11378 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011379 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011380 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011381 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011382 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080011383 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11384 new RemoteCallbackList<>();
11385 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090011386 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011387 // If there is no default network, default network is considered active to keep the existing
11388 // behavior. Initial value is used until first connect to the default network.
11389 private volatile boolean mIsDefaultNetworkActive = true;
Chalard Jean46bfbf02022-02-02 00:56:25 +090011390 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080011391
Chalard Jean46bfbf02022-02-02 00:56:25 +090011392 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011393 public final int timeout;
11394 public final int transportType;
11395
11396 IdleTimerParams(int timeout, int transport) {
11397 this.timeout = timeout;
11398 this.transportType = transport;
11399 }
11400 }
11401
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011402 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011403 @NonNull Handler handler) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011404 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011405 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011406 mHandler = handler;
11407 }
11408
11409 private void ensureRunningOnConnectivityServiceThread() {
11410 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
11411 throw new IllegalStateException("Not running on ConnectivityService thread: "
11412 + Thread.currentThread().getName());
11413 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011414 }
11415
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011416 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011417 ensureRunningOnConnectivityServiceThread();
Motomu Utsumic298cf02023-05-31 12:06:12 +090011418 if (mActiveIdleTimers.isEmpty()) {
11419 // This activity change is not for the current default network.
11420 // This can happen if netd callback post activity change event message but
11421 // the default network is lost before processing this message.
11422 return;
11423 }
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011424 sendDataActivityBroadcast(transportTypeToLegacyType(activityParams.label),
11425 activityParams.isActive, activityParams.timestampNs);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011426 mIsDefaultNetworkActive = activityParams.isActive;
11427 if (mIsDefaultNetworkActive) {
11428 reportNetworkActive();
lucaslin66f44212021-02-23 01:12:55 +080011429 }
11430 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011431
lucaslin1193a5d2021-01-21 02:04:15 +080011432 private void reportNetworkActive() {
11433 final int length = mNetworkActivityListeners.beginBroadcast();
11434 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
11435 try {
11436 for (int i = 0; i < length; i++) {
11437 try {
11438 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
11439 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011440 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080011441 }
11442 }
11443 } finally {
11444 mNetworkActivityListeners.finishBroadcast();
11445 }
11446 }
11447
lucaslin1a8b4c62021-01-21 02:02:55 +080011448 // This is deprecated and only to support legacy use cases.
11449 private int transportTypeToLegacyType(int type) {
11450 switch (type) {
11451 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011452 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080011453 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011454 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080011455 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011456 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080011457 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011458 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080011459 default:
11460 loge("Unexpected transport in transportTypeToLegacyType: " + type);
11461 }
11462 return ConnectivityManager.TYPE_NONE;
11463 }
11464
11465 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
11466 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
11467 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
11468 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
11469 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
11470 final long ident = Binder.clearCallingIdentity();
11471 try {
11472 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
11473 RECEIVE_DATA_ACTIVITY_CHANGE,
11474 null /* resultReceiver */,
11475 null /* scheduler */,
11476 0 /* initialCode */,
11477 null /* initialData */,
11478 null /* initialExtra */);
11479 } finally {
11480 Binder.restoreCallingIdentity(ident);
11481 }
11482 }
11483
11484 /**
11485 * Setup data activity tracking for the given network.
11486 *
11487 * Every {@code setupDataActivityTracking} should be paired with a
11488 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090011489 *
11490 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080011491 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090011492 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011493 final String iface = networkAgent.linkProperties.getInterfaceName();
11494
11495 final int timeout;
11496 final int type;
11497
11498 if (networkAgent.networkCapabilities.hasTransport(
11499 NetworkCapabilities.TRANSPORT_CELLULAR)) {
11500 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011501 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080011502 10);
11503 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11504 } else if (networkAgent.networkCapabilities.hasTransport(
11505 NetworkCapabilities.TRANSPORT_WIFI)) {
11506 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011507 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080011508 15);
11509 type = NetworkCapabilities.TRANSPORT_WIFI;
11510 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011511 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080011512 }
11513
lucaslinb961efc2021-01-21 02:03:17 +080011514 updateRadioPowerState(true /* isActive */, type);
11515
lucaslin1a8b4c62021-01-21 02:02:55 +080011516 if (timeout > 0 && iface != null) {
11517 try {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011518 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
11519 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
Motomu Utsumi6225d572023-05-29 15:08:57 +090011520 return true;
lucaslin1a8b4c62021-01-21 02:02:55 +080011521 } catch (Exception e) {
11522 // You shall not crash!
11523 loge("Exception in setupDataActivityTracking " + e);
11524 }
11525 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011526 return false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011527 }
11528
11529 /**
11530 * Remove data activity tracking when network disconnects.
11531 */
11532 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
11533 final String iface = networkAgent.linkProperties.getInterfaceName();
11534 final NetworkCapabilities caps = networkAgent.networkCapabilities;
11535
lucaslinb961efc2021-01-21 02:03:17 +080011536 if (iface == null) return;
11537
11538 final int type;
11539 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
11540 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11541 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
11542 type = NetworkCapabilities.TRANSPORT_WIFI;
11543 } else {
11544 return; // do not track any other networks
11545 }
11546
11547 try {
11548 updateRadioPowerState(false /* isActive */, type);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011549 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
11550 if (params == null) {
11551 // IdleTimer is not added if the configured timeout is 0 or negative value
11552 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080011553 }
Motomu Utsumic298cf02023-05-31 12:06:12 +090011554 // The call fails silently if no idle timer setup for this interface
11555 mNetd.idletimerRemoveInterface(iface, params.timeout,
11556 Integer.toString(params.transportType));
lucaslinb961efc2021-01-21 02:03:17 +080011557 } catch (Exception e) {
11558 // You shall not crash!
11559 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080011560 }
11561 }
11562
Motomu Utsumi6225d572023-05-29 15:08:57 +090011563 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
11564 boolean hasIdleTimer) {
11565 if (defaultNetwork != null) {
11566 mIsDefaultNetworkActive = true;
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011567 // Callbacks are called only when the network has the idle timer.
11568 if (hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011569 reportNetworkActive();
11570 }
11571 } else {
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011572 // If there is no default network, default network is considered active to keep the
11573 // existing behavior.
11574 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090011575 }
11576 }
11577
lucaslin1a8b4c62021-01-21 02:02:55 +080011578 /**
11579 * Update data activity tracking when network state is updated.
11580 */
11581 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
11582 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011583 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi6225d572023-05-29 15:08:57 +090011584 boolean hasIdleTimer = false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011585 if (newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011586 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080011587 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011588 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
lucaslin1a8b4c62021-01-21 02:02:55 +080011589 if (oldNetwork != null) {
11590 removeDataActivityTracking(oldNetwork);
11591 }
11592 }
lucaslinb961efc2021-01-21 02:03:17 +080011593
11594 private void updateRadioPowerState(boolean isActive, int transportType) {
11595 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
11596 switch (transportType) {
11597 case NetworkCapabilities.TRANSPORT_CELLULAR:
11598 bs.reportMobileRadioPowerState(isActive, NO_UID);
11599 break;
11600 case NetworkCapabilities.TRANSPORT_WIFI:
11601 bs.reportWifiRadioPowerState(isActive, NO_UID);
11602 break;
11603 default:
11604 logw("Untracked transport type:" + transportType);
11605 }
11606 }
lucaslin1193a5d2021-01-21 02:04:15 +080011607
11608 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011609 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080011610 }
11611
11612 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
11613 mNetworkActivityListeners.register(l);
11614 }
11615
11616 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
11617 mNetworkActivityListeners.unregister(l);
11618 }
lucaslin012f7a12021-01-21 02:04:35 +080011619
11620 public void dump(IndentingPrintWriter pw) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011621 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
11622 pw.println("Idle timers:");
11623 try {
11624 for (Map.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
lucaslin012f7a12021-01-21 02:04:35 +080011625 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
11626 final IdleTimerParams params = ent.getValue();
11627 pw.print(" timeout="); pw.print(params.timeout);
11628 pw.print(" type="); pw.println(params.transportType);
11629 }
Motomu Utsumic298cf02023-05-31 12:06:12 +090011630 } catch (Exception e) {
11631 // mActiveIdleTimers should only be accessed from handler thread, except dump().
11632 // As dump() is never called in normal usage, it would be needlessly expensive
11633 // to lock the collection only for its benefit.
11634 // Also, mActiveIdleTimers is not expected to be updated frequently.
11635 // So catching the exception and logging.
11636 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080011637 }
11638 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011639 }
James Mattis47db0582021-01-01 14:13:35 -080011640
Daniel Brightf9e945b2020-06-15 16:10:01 -070011641 /**
11642 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
11643 *
11644 * @param socketInfo the socket information
11645 * @param callback the callback to register
11646 */
11647 @Override
11648 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
11649 @NonNull final IQosCallback callback) {
11650 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
11651 if (nai == null || nai.networkCapabilities == null) {
11652 try {
11653 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
11654 } catch (final RemoteException ex) {
11655 loge("registerQosCallbackInternal: RemoteException", ex);
11656 }
11657 return;
11658 }
11659 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
11660 }
11661
11662 /**
11663 * Register a {@link IQosCallback} with base {@link QosFilter}.
11664 *
11665 * @param filter the filter to register
11666 * @param callback the callback to register
11667 * @param nai the agent information related to the filter's network
11668 */
11669 @VisibleForTesting
11670 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
11671 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011672 Objects.requireNonNull(filter, "filter must be non-null");
11673 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011674
11675 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080011676 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
11677 // on this network is unregistered when the app loses permission or b) no QoS
11678 // callbacks are sent for restricted networks unless the app currently has permission
11679 // to access restricted networks.
11680 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070011681 }
11682 mQosCallbackTracker.registerCallback(callback, filter, nai);
11683 }
11684
11685 /**
11686 * Unregisters the given callback.
11687 *
11688 * @param callback the callback to unregister
11689 */
11690 @Override
11691 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011692 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011693 mQosCallbackTracker.unregisterCallback(callback);
11694 }
James Mattis47db0582021-01-01 14:13:35 -080011695
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011696 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
11697 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
11698 // Enterprise device can be fully managed like device owner and such use case
11699 // also should be supported. Calling app check for work profile and fully managed device
11700 // is already done in DevicePolicyManager.
11701 // This check is an extra caution to be sure device is fully managed or not.
11702 final UserManager um = mContext.getSystemService(UserManager.class);
11703 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
11704 if (um.isManagedProfile(profile.getIdentifier())) {
11705 return true;
11706 }
Chalard Jeandf29a852023-05-29 17:02:43 +090011707 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011708 return false;
11709 }
11710
James Mattis45d81842021-01-10 14:24:24 -080011711 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011712 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011713 *
11714 * See the documentation for the individual preferences for a description of the supported
11715 * behaviors.
11716 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011717 * @param profile If the device owner is set, any profile is allowed.
11718 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011719 * @param preferences the list of profile network preferences for the
11720 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011721 * @param listener an optional listener to listen for completion of the operation.
11722 */
11723 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011724 public void setProfileNetworkPreferences(
11725 @NonNull final UserHandle profile,
11726 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090011727 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011728 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011729 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011730
11731 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011732 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11733 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11734 .build();
11735 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011736 }
11737
paulhu3ffffe72021-09-16 10:15:22 +080011738 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011739 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011740 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011741 }
11742 if (profile.getIdentifier() < 0) {
11743 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11744 + "UserHandle.CURRENT not supported)");
11745 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011746 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11747 throw new IllegalArgumentException("Profile must be a managed profile "
11748 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011749 }
paulhuaa0743d2021-05-26 21:56:03 +080011750
Chalard Jean0606fc82022-12-14 20:34:43 +090011751 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011752 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011753 for (final ProfileNetworkPreference preference : preferences) {
11754 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011755 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011756 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011757 switch (preference.getPreference()) {
11758 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11759 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011760 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011761 if (preference.getPreferenceEnterpriseId() != 0) {
11762 throw new IllegalArgumentException(
11763 "Invalid enterprise identifier in setProfileNetworkPreferences");
11764 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011765 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011766 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11767 blockingNonEnterprise = true;
11768 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011769 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11770 allowFallback = false;
11771 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011772 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011773 // This code is needed even though there is a check later on,
11774 // because isRangeAlreadyInPreferenceList assumes that every preference
11775 // has a UID list.
11776 if (hasDefaultPreference) {
11777 throw new IllegalArgumentException(
11778 "Default profile preference should not be set along with other "
11779 + "preference");
11780 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011781 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11782 throw new IllegalArgumentException(
11783 "Invalid enterprise identifier in setProfileNetworkPreferences");
11784 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011785 final Set<UidRange> uidRangeSet =
11786 getUidListToBeAppliedForNetworkPreference(profile, preference);
11787 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11788 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11789 } else {
11790 throw new IllegalArgumentException(
11791 "Overlapping uid range in setProfileNetworkPreferences");
11792 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011793 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011794 nc.addEnterpriseId(
11795 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011796 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11797 break;
11798 default:
11799 throw new IllegalArgumentException(
11800 "Invalid preference in setProfileNetworkPreferences");
11801 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011802 preferenceList.add(new ProfileNetworkPreferenceInfo(
11803 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011804 if (hasDefaultPreference && preferenceList.size() > 1) {
11805 throw new IllegalArgumentException(
11806 "Default profile preference should not be set along with other preference");
11807 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011808 }
11809 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011810 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011811 }
11812
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011813 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
11814 @NonNull final UserHandle profile,
11815 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
11816 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080011817 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
11818 profileNetworkPreference.getIncludedUids());
11819
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011820 if (uidRangeSet.size() > 0) {
11821 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
11822 throw new IllegalArgumentException(
11823 "Allow uid range is outside the uid range of profile.");
11824 }
11825 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080011826 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011827 profileNetworkPreference.getExcludedUids());
11828 if (disallowUidRangeSet.size() > 0) {
11829 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
11830 throw new IllegalArgumentException(
11831 "disallow uid range is outside the uid range of profile.");
11832 }
11833 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
11834 disallowUidRangeSet);
11835 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011836 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011837 uidRangeSet.add(profileUids);
11838 }
11839 }
11840 return uidRangeSet;
11841 }
11842
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011843 private boolean isEnterpriseIdentifierValid(
11844 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011845 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011846 return true;
11847 }
11848 return false;
11849 }
11850
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011851 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090011852 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011853 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090011854 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011855 // The NRI for a user should contain the request for capabilities.
11856 // If fallback to default network is needed then NRI should include
11857 // the request for the default network. Create an image of it to
11858 // have the correct UIDs in it (also a request can only be part of one NRI, because
11859 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011860 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
11861 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011862 if (pref.allowFallback) {
11863 nrs.add(createDefaultInternetRequestForTransport(
11864 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11865 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011866 if (VDBG) {
11867 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
11868 pref.capabilities.getUids()));
11869 }
11870
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011871 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080011872 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080011873 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011874 result.add(nri);
11875 }
11876 return result;
11877 }
11878
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011879 /**
11880 * Compare if the given UID range sets have the same UIDs.
11881 *
11882 */
11883 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090011884 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011885 @NonNull Set<UidRange> uidRangeSet) {
11886 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
11887 return false;
11888 }
Chalard Jean0606fc82022-12-14 20:34:43 +090011889 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011890 if (UidRangeUtils.doesRangeSetOverlap(
11891 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
11892 return true;
11893 }
11894 }
11895 return false;
11896 }
11897
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011898 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090011899 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011900 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011901 /*
11902 * handleSetProfileNetworkPreference is always called for single user.
11903 * preferenceList only contains preferences for different uids within the same user
11904 * (enforced by getUidListToBeAppliedForNetworkPreference).
11905 * Clear all the existing preferences for the user before applying new preferences.
11906 *
11907 */
Chalard Jean0606fc82022-12-14 20:34:43 +090011908 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
11909 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011910 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
11911 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011912
paulhu74128522021-09-28 02:29:03 +000011913 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
11914 addPerAppDefaultNetworkRequests(
11915 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080011916 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080011917
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011918 // Finally, rematch.
11919 rematchAllNetworksAndRequests();
11920
11921 if (null != listener) {
11922 try {
11923 listener.onComplete();
11924 } catch (RemoteException e) {
11925 loge("Listener for setProfileNetworkPreference has died");
11926 }
11927 }
11928 }
11929
paulhu51f77dc2021-06-07 02:34:20 +000011930 @VisibleForTesting
11931 @NonNull
11932 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
11933 @NonNull final Set<Integer> uids) {
11934 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11935 if (uids.size() == 0) {
11936 // Should not create NetworkRequestInfo if no preferences. Without uid range in
11937 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
11938 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
11939 return nris;
11940 }
11941
11942 final List<NetworkRequest> requests = new ArrayList<>();
11943 // The NRI should be comprised of two layers:
11944 // - The request for the mobile network preferred.
11945 // - The request for the default network, for fallback.
11946 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090011947 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000011948 requests.add(createDefaultInternetRequestForTransport(
11949 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11950 final Set<UidRange> ranges = new ArraySet<>();
11951 for (final int uid : uids) {
11952 ranges.add(new UidRange(uid, uid));
11953 }
11954 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080011955 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080011956 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000011957 return nris;
11958 }
11959
11960 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000011961 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000011962 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
11963 addPerAppDefaultNetworkRequests(
11964 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000011965 // Finally, rematch.
11966 rematchAllNetworksAndRequests();
11967 }
11968
Patrick Rohr2857ac42022-01-21 14:58:16 +010011969 private void handleIngressRateLimitChanged() {
11970 final long oldIngressRateLimit = mIngressRateLimit;
11971 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
11972 mContext);
11973 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
11974 if (canNetworkBeRateLimited(networkAgent)) {
11975 // If rate limit has previously been enabled, remove the old limit first.
11976 if (oldIngressRateLimit >= 0) {
11977 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
11978 }
11979 if (mIngressRateLimit >= 0) {
11980 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
11981 mIngressRateLimit);
11982 }
11983 }
11984 }
11985 }
11986
11987 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090011988 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090011989 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090011990
Patrick Rohrff3b3f82022-02-09 15:15:52 +010011991 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
11992 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
11993 // internet connectivity can be rate limited.
11994 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
11995 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010011996 return false;
11997 }
11998
11999 final String iface = networkAgent.linkProperties.getInterfaceName();
12000 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012001 // This may happen in tests, but if there is no interface then there is nothing that
12002 // can be rate limited.
12003 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012004 return false;
12005 }
12006 return true;
12007 }
12008
James Mattis45d81842021-01-10 14:24:24 -080012009 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012010 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12011 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012012 }
12013
12014 /**
12015 * Used by automotive devices to set the network preferences used to direct traffic at an
12016 * application level as per the given OemNetworkPreferences. An example use-case would be an
12017 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12018 * vehicle via a particular network.
12019 *
12020 * Calling this will overwrite the existing preference.
12021 *
James Mattisda32cfe2021-01-26 16:23:52 -080012022 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012023 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012024 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012025 */
James Mattis47db0582021-01-01 14:13:35 -080012026 @Override
James Mattis45d81842021-01-10 14:24:24 -080012027 public void setOemNetworkPreference(
12028 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012029 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012030
James Mattisfa270db2021-05-31 17:11:10 -070012031 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12032 // Only bypass the permission/device checks if this is a valid test request.
12033 if (isValidTestOemNetworkPreference(preference)) {
12034 enforceManageTestNetworksPermission();
12035 } else {
12036 enforceAutomotiveDevice();
12037 enforceOemNetworkPreferencesPermission();
12038 validateOemNetworkPreferences(preference);
12039 }
James Mattis45d81842021-01-10 14:24:24 -080012040
James Mattis45d81842021-01-10 14:24:24 -080012041 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12042 new Pair<>(preference, listener)));
12043 }
12044
James Mattisfa270db2021-05-31 17:11:10 -070012045 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012046 * Sets the specified UIDs to get/receive the VPN as the only default network.
12047 *
12048 * Calling this will overwrite the existing network preference for this session, and the
12049 * specified UIDs won't get any default network when no VPN is connected.
12050 *
12051 * @param session The VPN session which manages the passed UIDs.
12052 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12053 * setting for this session if the array is empty. Null is not allowed, the
12054 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12055 * @hide
12056 */
12057 @Override
12058 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12059 Objects.requireNonNull(ranges);
12060 enforceNetworkStackOrSettingsPermission();
12061 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12062 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12063 throw new IllegalArgumentException(
12064 "setVpnNetworkPreference: Passed UID ranges overlap");
12065 }
12066
12067 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12068 new VpnNetworkPreferenceInfo(session,
12069 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12070 }
12071
12072 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12073 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12074
12075 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12076 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12077
12078 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12079 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12080 // Finally, rematch.
12081 rematchAllNetworksAndRequests();
12082 }
12083
12084 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12085 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12086 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12087 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
12088 final List<NetworkRequest> requests = new ArrayList<>();
12089 // Request VPN only, so other networks won't be the fallback options when VPN is not
12090 // connected temporarily.
12091 requests.add(createVpnRequest());
12092 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
12093 setNetworkRequestUids(requests, uidRanges);
12094 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
12095 }
12096 return nris;
12097 }
12098
12099 /**
James Mattisfa270db2021-05-31 17:11:10 -070012100 * Check the validity of an OEM network preference to be used for testing purposes.
12101 * @param preference the preference to validate
12102 * @return true if this is a valid OEM network preference test request.
12103 */
12104 private boolean isValidTestOemNetworkPreference(
12105 @NonNull final OemNetworkPreferences preference) {
12106 // Allow for clearing of an existing OemNetworkPreference used for testing.
12107 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
12108 // changes after this check is complete. This is an unlikely scenario as calling of this API
12109 // is controlled by the OEM therefore the added complexity is not worth adding given those
12110 // circumstances. That said, it is an edge case to be aware of hence this comment.
12111 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
12112 && isTestOemNetworkPreference(mOemNetworkPreferences);
12113 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
12114 }
12115
12116 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
12117 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
12118 return prefMap.size() == 1
12119 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
12120 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
12121 }
12122
James Mattis45d81842021-01-10 14:24:24 -080012123 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
12124 for (@OemNetworkPreferences.OemNetworkPreference final int pref
12125 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070012126 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
12127 throw new IllegalArgumentException(
12128 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
12129 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080012130 }
12131 }
12132 }
12133
12134 private void handleSetOemNetworkPreference(
12135 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012136 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080012137 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12138 if (DBG) {
12139 log("set OEM network preferences :" + preference.toString());
12140 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012141
James Mattiscb1e0362021-04-06 17:07:42 -070012142 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012143 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12144 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12145 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012146 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012147
12148 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012149 try {
12150 listener.onComplete();
12151 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012152 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012153 }
James Mattis45d81842021-01-10 14:24:24 -080012154 }
12155 }
12156
paulhu74128522021-09-28 02:29:03 +000012157 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012158 // Skip the requests which are set by other network preference. Because the uid range rules
12159 // should stay in netd.
12160 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012161 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012162 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012163 }
12164
James Mattis3ce3d3c2021-02-09 18:18:28 -080012165 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12166 ensureRunningOnConnectivityServiceThread();
12167 mDefaultNetworkRequests.addAll(nris);
12168 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12169 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012170 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012171 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12172 nrisToRegister.addAll(
12173 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12174 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012175 }
12176
12177 /**
12178 * All current requests that are tracking the default network need to be assessed as to whether
12179 * or not the current set of per-application default requests will be changing their default
12180 * network. If so, those requests will need to be updated so that they will send callbacks for
12181 * default network changes at the appropriate time. Additionally, those requests tracking the
12182 * default that were previously updated by this flow will need to be reassessed.
12183 * @return the nris which will need to be updated.
12184 */
12185 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12186 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12187 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12188 // same nri in the map's values for each of its NetworkRequest objects.
12189 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012190 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012191 // Include this nri if it is currently being tracked.
12192 if (isPerAppTrackedNri(nri)) {
12193 defaultCallbackRequests.add(nri);
12194 continue;
12195 }
12196 // We only track callbacks for requests tracking the default.
12197 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12198 continue;
12199 }
12200 // Include this nri if it will be tracked by the new per-app default requests.
12201 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012202 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012203 if (isNriGoingToBeTracked) {
12204 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012205 }
12206 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012207 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012208 }
12209
James Mattis3ce3d3c2021-02-09 18:18:28 -080012210 /**
12211 * Create nris for those network requests that are currently tracking the default network that
12212 * are being controlled by a per-application default.
12213 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12214 * foundation when creating the nri. Important items include the calling uid's original
12215 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12216 * requests are assumed to have already been validated as needing to be updated.
12217 * @return the Set of nris to use when registering network requests.
12218 */
12219 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12220 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12221 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12222 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12223 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012224 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012225
Chalard Jean9473c982021-07-29 20:03:04 +090012226 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012227 if (trackingNri == mDefaultRequest) {
12228 callbackRequestsToRegister.add(new NetworkRequestInfo(
12229 callbackRequest,
12230 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12231 continue;
12232 }
12233
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012234 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012235 callbackRequestsToRegister.add(new NetworkRequestInfo(
12236 callbackRequest,
12237 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012238 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012239 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012240 }
12241 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012242 }
12243
Chalard Jean17215832021-03-01 14:06:28 +090012244 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12245 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012246 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012247 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012248 }
12249 }
12250
James Mattis45d81842021-01-10 14:24:24 -080012251 /**
12252 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12253 */
12254 @VisibleForTesting
12255 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012256 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080012257 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012258 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080012259 final SparseArray<Set<Integer>> uids =
12260 createUidsFromOemNetworkPreferences(preference);
12261 for (int i = 0; i < uids.size(); i++) {
12262 final int key = uids.keyAt(i);
12263 final Set<Integer> value = uids.valueAt(i);
12264 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
12265 // No need to add an nri without any requests.
12266 if (0 == nri.mRequests.size()) {
12267 continue;
12268 }
12269 nris.add(nri);
12270 }
12271
12272 return nris;
12273 }
12274
12275 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
12276 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070012277 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080012278 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080012279 final List<UserHandle> users =
12280 mContext.getSystemService(UserManager.class).getUserHandles(true);
12281 if (null == users || users.size() == 0) {
12282 if (VDBG || DDBG) {
12283 log("No users currently available for setting the OEM network preference.");
12284 }
James Mattisb6b6a432021-06-01 22:30:36 -070012285 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080012286 }
James Mattis45d81842021-01-10 14:24:24 -080012287 for (final Map.Entry<String, Integer> entry :
12288 preference.getNetworkPreferences().entrySet()) {
12289 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070012290 // Add the rules for all users as this policy is device wide.
12291 for (final UserHandle user : users) {
12292 try {
12293 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
12294 if (!prefToUids.contains(pref)) {
12295 prefToUids.put(pref, new ArraySet<>());
12296 }
12297 prefToUids.get(pref).add(uid);
12298 } catch (PackageManager.NameNotFoundException e) {
12299 // Although this may seem like an error scenario, it is ok that uninstalled
12300 // packages are sent on a network preference as the system will watch for
12301 // package installations associated with this network preference and update
12302 // accordingly. This is done to minimize race conditions on app install.
12303 continue;
James Mattis45d81842021-01-10 14:24:24 -080012304 }
James Mattis45d81842021-01-10 14:24:24 -080012305 }
12306 }
James Mattisb6b6a432021-06-01 22:30:36 -070012307 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080012308 }
12309
12310 private NetworkRequestInfo createNriFromOemNetworkPreferences(
12311 @OemNetworkPreferences.OemNetworkPreference final int preference,
12312 @NonNull final Set<Integer> uids) {
12313 final List<NetworkRequest> requests = new ArrayList<>();
12314 // Requests will ultimately be evaluated by order of insertion therefore it matters.
12315 switch (preference) {
12316 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
12317 requests.add(createUnmeteredNetworkRequest());
12318 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070012319 requests.add(createDefaultInternetRequestForTransport(
12320 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080012321 break;
12322 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
12323 requests.add(createUnmeteredNetworkRequest());
12324 requests.add(createOemPaidNetworkRequest());
12325 break;
12326 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
12327 requests.add(createOemPaidNetworkRequest());
12328 break;
12329 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
12330 requests.add(createOemPrivateNetworkRequest());
12331 break;
James Mattisfa270db2021-05-31 17:11:10 -070012332 case OEM_NETWORK_PREFERENCE_TEST:
12333 requests.add(createUnmeteredNetworkRequest());
12334 requests.add(createTestNetworkRequest());
12335 requests.add(createDefaultRequest());
12336 break;
12337 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
12338 requests.add(createTestNetworkRequest());
12339 break;
James Mattis45d81842021-01-10 14:24:24 -080012340 default:
12341 // This should never happen.
12342 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
12343 + " called with invalid preference of " + preference);
12344 }
12345
James Mattisfa270db2021-05-31 17:11:10 -070012346 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090012347 for (final int uid : uids) {
12348 ranges.add(new UidRange(uid, uid));
12349 }
12350 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080012351 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080012352 }
12353
12354 private NetworkRequest createUnmeteredNetworkRequest() {
12355 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12356 .addCapability(NET_CAPABILITY_NOT_METERED)
12357 .addCapability(NET_CAPABILITY_VALIDATED);
12358 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
12359 }
12360
12361 private NetworkRequest createOemPaidNetworkRequest() {
12362 // NET_CAPABILITY_OEM_PAID is a restricted capability.
12363 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12364 .addCapability(NET_CAPABILITY_OEM_PAID)
12365 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12366 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12367 }
12368
12369 private NetworkRequest createOemPrivateNetworkRequest() {
12370 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
12371 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12372 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
12373 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12374 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12375 }
12376
12377 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070012378 final NetworkCapabilities netcap = new NetworkCapabilities();
12379 netcap.addCapability(NET_CAPABILITY_INTERNET);
12380 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
12381 return netcap;
12382 }
12383
12384 private NetworkRequest createTestNetworkRequest() {
12385 final NetworkCapabilities netcap = new NetworkCapabilities();
12386 netcap.clearAll();
12387 netcap.addTransportType(TRANSPORT_TEST);
12388 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080012389 }
James Mattis47db0582021-01-01 14:13:35 -080012390 }
markchien738ad912021-12-09 18:15:45 +080012391
12392 @Override
12393 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
12394 enforceNetworkStackOrSettingsPermission();
12395
12396 try {
12397 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012398 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012399 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012400 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012401 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012402 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012403 throw new IllegalStateException(e);
12404 }
12405 }
12406
12407 @Override
12408 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
12409 enforceNetworkStackOrSettingsPermission();
12410
12411 try {
12412 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012413 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012414 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012415 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012416 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012417 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012418 throw new IllegalStateException(e);
12419 }
12420 }
markchiene1561fa2021-12-09 22:00:56 +080012421
12422 @Override
markchien3c04e662022-03-22 16:29:56 +080012423 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080012424 enforceNetworkStackOrSettingsPermission();
12425
markchien3c04e662022-03-22 16:29:56 +080012426 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
12427 int firewallRule = getFirewallRuleType(chain, rule);
12428
12429 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
12430 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
12431 }
12432
markchiene1561fa2021-12-09 22:00:56 +080012433 try {
markchien3c04e662022-03-22 16:29:56 +080012434 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012435 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080012436 throw new IllegalStateException(e);
12437 }
12438 }
markchien98a6f952022-01-13 23:43:53 +080012439
Motomu Utsumi900b8062023-01-19 16:16:49 +090012440 @Override
12441 public int getUidFirewallRule(final int chain, final int uid) {
12442 enforceNetworkStackOrSettingsPermission();
12443 return mBpfNetMaps.getUidRule(chain, uid);
12444 }
12445
markchien3c04e662022-03-22 16:29:56 +080012446 private int getFirewallRuleType(int chain, int rule) {
12447 final int defaultRule;
12448 switch (chain) {
12449 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000012450 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
12451 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000012452 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080012453 defaultRule = FIREWALL_RULE_ALLOW;
12454 break;
12455 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
12456 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
12457 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
12458 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
12459 defaultRule = FIREWALL_RULE_DENY;
12460 break;
12461 default:
12462 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
12463 }
12464 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
12465
12466 return rule;
12467 }
12468
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012469 private void closeSocketsForFirewallChainLocked(final int chain)
12470 throws ErrnoException, SocketException, InterruptedIOException {
12471 if (mBpfNetMaps.isFirewallAllowList(chain)) {
12472 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
12473 // So, close all non-system socket owned by uids that are not explicitly allowed
12474 Set<Range<Integer>> ranges = new ArraySet<>();
12475 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
12476 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
12477 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
12478 } else {
12479 // Denylist means the firewall allows all by default, uids must be explicitly denied
12480 // So, close socket owned by uids that are explicitly denied
12481 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
12482 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
12483 }
12484 }
12485
markchien98a6f952022-01-13 23:43:53 +080012486 @Override
12487 public void setFirewallChainEnabled(final int chain, final boolean enable) {
12488 enforceNetworkStackOrSettingsPermission();
12489
12490 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012491 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012492 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080012493 throw new IllegalStateException(e);
12494 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012495
Chalard Jeandf29a852023-05-29 17:02:43 +090012496 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012497 try {
12498 closeSocketsForFirewallChainLocked(chain);
12499 } catch (ErrnoException | SocketException | InterruptedIOException e) {
12500 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
12501 }
12502 }
markchien98a6f952022-01-13 23:43:53 +080012503 }
12504
markchien00a0bed2022-01-13 23:46:13 +080012505 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012506 public boolean getFirewallChainEnabled(final int chain) {
12507 enforceNetworkStackOrSettingsPermission();
12508
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000012509 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012510 }
12511
12512 @Override
markchien00a0bed2022-01-13 23:46:13 +080012513 public void replaceFirewallChain(final int chain, final int[] uids) {
12514 enforceNetworkStackOrSettingsPermission();
12515
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000012516 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080012517 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080012518
12519 @Override
12520 public IBinder getCompanionDeviceManagerProxyService() {
12521 enforceNetworkStackPermission(mContext);
12522 return mCdmps;
12523 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070012524}