blob: 01ffb03b5087419658374a6200e353ce3dd13eaf [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;
Xiao Ma60142372022-07-16 17:30:20 +0900100import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Junyu Lai4c6fe232023-04-11 11:33:46 +0800101import static com.android.net.module.util.PermissionUtils.checkAnyPermissionOf;
paulhu3ffffe72021-09-16 10:15:22 +0800102import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
103import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
104import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900105import static com.android.server.ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800106import static java.util.Map.Entry;
107
Chalard Jean5b639762020-03-09 21:25:37 +0900108import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000109import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800110import android.annotation.Nullable;
Michael Groover73f69482023-01-27 11:01:25 -0600111import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800112import android.annotation.TargetApi;
Mark Fasheh7c999d82023-05-04 20:23:11 +0000113import android.app.ActivityManager;
114import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800115import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800116import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700117import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700118import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900119import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800120import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700121import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800122import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800123import android.content.ContentResolver;
124import android.content.Context;
125import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700126import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800127import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900128import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700129import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900130import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900131import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700132import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800133import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800134import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800135import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900136import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800137import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900138import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800139import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900140import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800141import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700142import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900143import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800144import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800145import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800146import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800147import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800148import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900149import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900150import android.net.INetworkMonitor;
151import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900152import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900153import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700154import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800155import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900156import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900157import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900158import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800159import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100160import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800161import android.net.NativeNetworkConfig;
162import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800163import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700164import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700165import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900166import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700167import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800168import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700169import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900170import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900171import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000172import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900173import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700174import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900175import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700176import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900177import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700178import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800179import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900180import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700181import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000182import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800183import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900184import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800185import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400186import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700187import android.net.QosCallbackException;
188import android.net.QosFilter;
189import android.net.QosSocketFilter;
190import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700191import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800192import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800193import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800194import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900195import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400196import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800197import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800198import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400199import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800200import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900201import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900202import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900203import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900204import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800205import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900206import android.net.networkstack.ModuleNetworkStackClient;
207import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900208import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800209import android.net.resolv.aidl.DnsHealthEventParcel;
210import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
211import android.net.resolv.aidl.Nat64PrefixEventParcel;
212import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900213import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900214import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800215import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800216import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800217import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700218import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000219import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800220import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700221import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700222import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800223import android.os.Looper;
224import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700225import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700226import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900227import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800228import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700229import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700230import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800231import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700232import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900233import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900234import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700235import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700236import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400237import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800238import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900239import android.stats.connectivity.MeteredState;
240import android.stats.connectivity.RequestType;
241import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900242import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700243import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700244import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700245import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800246import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900247import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000248import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600249import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900250import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900251import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700252import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700253import android.util.SparseIntArray;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900254import android.util.StatsEvent;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800255
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800256import androidx.annotation.RequiresApi;
257
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900258import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400259import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400260import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700261import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900262import com.android.internal.util.MessageUtils;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900263import com.android.metrics.ConnectionDurationForTransports;
264import com.android.metrics.ConnectionDurationPerTransports;
265import com.android.metrics.ConnectivitySampleMetricsHelper;
266import com.android.metrics.ConnectivityStateSample;
267import com.android.metrics.NetworkCountForTransports;
268import com.android.metrics.NetworkCountPerTransports;
269import com.android.metrics.NetworkDescription;
270import com.android.metrics.NetworkList;
271import com.android.metrics.NetworkRequestCount;
272import com.android.metrics.RequestCountForType;
Chiachang Wang62740142020-11-02 16:51:24 +0800273import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900274import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800275import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000276import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900277import com.android.net.module.util.BitUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900278import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900279import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100280import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900281import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
282import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900283import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800284import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800285import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100286import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000287import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800288import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
289import com.android.networkstack.apishim.ConstantsShim;
290import com.android.networkstack.apishim.common.BroadcastOptionsShim;
291import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900292import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900293import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000294import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900295import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800296import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800297import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900298import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900299import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900300import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500301import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700302import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900303import com.android.server.connectivity.FullScore;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900304import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900305import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000306import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100307import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700308import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900309import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700310import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600311import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900312import com.android.server.connectivity.NetworkNotificationManager;
313import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900314import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900315import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900316import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700317import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900318import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900319import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700320import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800321import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000322import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800323import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600324
Josh Gao461a1222020-06-16 15:58:11 -0700325import libcore.io.IoUtils;
326
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900327import org.xmlpull.v1.XmlPullParserException;
328
The Android Open Source Project28527d22009-03-03 19:31:44 -0800329import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100330import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900331import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800332import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900333import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700334import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700335import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900336import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900337import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700338import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700339import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700340import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700341import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800342import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900343import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800344import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700345import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700346import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700347import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700348import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900349import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700350import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900351import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600352import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900353import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600354import java.util.TreeSet;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900355import java.util.concurrent.TimeUnit;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900356import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800357
358/**
359 * @hide
360 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800361public class ConnectivityService extends IConnectivityManager.Stub
362 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900363 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800364
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900365 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900366 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900367 private static final String NETWORK_ARG = "networks";
368 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800369 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900370
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900371 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900372 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
373 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800374
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900375 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700376
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100377 /**
378 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
379 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800380 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100381 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
382 * (preferably via runtime resource overlays).
383 */
384 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
385 "http://connectivitycheck.gstatic.com/generate_204";
386
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700387 // TODO: create better separation between radio types and network types
388
Robert Greenwalt2034b912009-08-12 16:08:25 -0700389 // how long to wait before switching back to a radio's default network
390 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
391 // system property that can override the above value
392 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
393 "android.telephony.apn-restore";
394
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900395 // How long to wait before putting up a "This network doesn't have an Internet connection,
396 // connect anyway?" dialog after the user selects a network that doesn't validate.
397 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
398
Chalard Jean5fb43c72022-09-08 19:03:14 +0900399 // How long to wait before considering that a network is bad in the absence of any form
400 // of connectivity (valid, partial, captive portal). If none has been detected after this
401 // delay, the stack considers this network bad, which may affect how it's handled in ranking
402 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900403 // Timeout in case the "actively prefer bad wifi" feature is on
404 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
405 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900406 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900407
junyulai0ac374f2020-12-14 18:41:52 +0800408 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900409 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
410 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800411 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700412
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800413 // Delimiter used when creating the broadcast delivery group for sending
414 // CONNECTIVITY_ACTION broadcast.
415 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
416
he_won.hwang881307a2022-03-15 21:23:52 +0900417 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900418 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900419
Daniel Brightf9e945b2020-06-15 16:10:01 -0700420 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900421 @VisibleForTesting
422 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700423
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900424 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700425 @VisibleForTesting
426 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900427
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900428 @VisibleForTesting
429 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800430 @VisibleForTesting
431 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900432 // True if the cell radio of the device is capable of time-sharing.
433 @VisibleForTesting
434 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900435
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800436 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800437 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800438 private final int mReleasePendingIntentDelayMs;
439
Chalard Jean46bfbf02022-02-02 00:56:25 +0900440 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900441
Motomu Utsumif360aa62023-01-30 17:52:20 +0900442 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700443
Chalard Jean9473c982021-07-29 20:03:04 +0900444 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800445 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700446 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800447 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700448
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900449 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700450
junyulaif2c67e42018-08-07 19:50:45 +0800451 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000452 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
453 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800454 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900455 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800456
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900457 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900458 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000459 private final int mWakeUpMark;
460 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000461 // The Context is created for UserHandle.ALL.
462 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900463 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900464 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700465 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700466 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800467
Chenbo Feng15416292018-11-08 17:36:21 -0800468 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800469 protected IDnsResolver mDnsResolver;
470 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800471 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700472 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900473 private final NetworkStatsManager mStatsManager;
474 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800475 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700476
Benedict Wong493e04b2018-11-09 14:45:34 -0800477 /**
478 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
479 * instances.
480 */
481 @GuardedBy("mTNSLock")
482 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800483 private final CompanionDeviceManagerProxyService mCdmps;
Benedict Wong493e04b2018-11-09 14:45:34 -0800484
485 private final Object mTNSLock = new Object();
486
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700487 private String mCurrentTcpBufferSizes;
488
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900489 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000490 new Class[] {
491 ConnectivityService.class,
492 NetworkAgent.class,
493 NetworkAgentInfo.class,
494 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900495
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500496 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400497 // Tear down networks that have no chance (e.g. even if validated) of becoming
498 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500499 // all networks have been rematched against all NetworkRequests.
500 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400501 // Don't reap networks. This should be passed when some networks have not yet been
502 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500503 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900504 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500505
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900506 private enum UnneededFor {
507 LINGER, // Determine whether this network is unneeded and should be lingered.
508 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
509 }
510
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700511 /**
paulhuaa0743d2021-05-26 21:56:03 +0800512 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800513 * should have priority. The order is passed to netd which will use it together
514 * with UID ranges to generate the corresponding IP rule. This serves to
515 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800516 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800517 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000518 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800519 *
paulhu48291862021-07-14 14:53:57 +0800520 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
521 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800522 */
paulhu48291862021-07-14 14:53:57 +0800523 // Used when sending to netd to code for "no order".
524 static final int PREFERENCE_ORDER_NONE = 0;
525 // Order for requests that don't code for a per-app preference. As it is
526 // out of the valid range, the corresponding order should be
527 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800528 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800529 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800530 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800531 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
532 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800533 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800534 static final int PREFERENCE_ORDER_OEM = 10;
535 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800536 // See {@link #setProfileNetworkPreference}.
537 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800538 static final int PREFERENCE_ORDER_PROFILE = 20;
539 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800540 // better scores are connected.
541 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800542 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800543 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900544 // Preference order that signifies the network shouldn't be set as a default network for
545 // the UIDs, only give them access to it. TODO : replace this with a boolean
546 // in NativeUidRangeConfig
547 @VisibleForTesting
548 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
549 // Bound for the lowest valid preference order.
550 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800551
552 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700553 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700554 * from one net to another. Clear happens when we get a new
555 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
556 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700557 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700558 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700559
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700560 /**
561 * used internally to reload global proxy settings
562 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700563 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700564
Robert Greenwalt34848c02011-03-25 13:09:25 -0700565 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400566 * PAC manager has received new port.
567 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800568 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400569
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700570 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900571 * used internally when registering NetworkProviders
572 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700573 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900574 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700575
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700576 /**
577 * used internally when registering NetworkAgents
578 * obj = Messenger
579 */
580 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
581
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700582 /**
583 * used to add a network request
584 * includes a NetworkRequestInfo
585 */
586 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
587
588 /**
589 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900590 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700591 * cancel it.
592 * includes a NetworkRequestInfo
593 */
594 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
595
596 /**
597 * used to add a network listener - no request
598 * includes a NetworkRequestInfo
599 */
600 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
601
602 /**
603 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400604 * arg1 = UID of caller
605 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700606 */
607 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
608
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700609 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900610 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700611 * obj = Messenger
612 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900613 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700614
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700615 /**
616 * used internally to expire a wakelock when transitioning
617 * from one net to another. Expire happens when we fail to find
618 * a new network (typically after 1 minute) -
619 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
620 * a replacement network.
621 */
622 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
623
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700624 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800625 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400626 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800627 */
628 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
629
630 /**
631 * used to remove a pending intent and its associated network request.
632 * arg1 = UID of caller
633 * obj = PendingIntent
634 */
635 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
636
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900637 /**
638 * used to specify whether a network should be used even if unvalidated.
639 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
640 * arg2 = whether to remember this choice in the future (1 or 0)
641 * obj = network
642 */
643 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
644
645 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700646 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900647 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700648 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900649
Paul Jensenc8873fc2015-06-17 14:15:39 -0400650 /**
651 * used to add a network listener with a pending intent
652 * obj = NetworkRequestInfo
653 */
654 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
655
Hugo Benichid6b510a2017-04-06 17:22:18 +0900656 /**
657 * used to specify whether a network should not be penalized when it becomes unvalidated.
658 */
659 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
660
661 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700662 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900663 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700664 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900665
Erik Kline31b4a9e2018-01-11 21:07:29 +0900666 // Handle changes in Private DNS settings.
667 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
668
dalyk1720e542018-03-05 12:42:22 -0500669 // Handle private DNS validation status updates.
670 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
671
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900672 /**
673 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
674 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800675 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
676 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
677 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900678 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900679 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900680
681 /**
682 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
683 * config was resolved.
684 * obj = PrivateDnsConfig
685 * arg2 = netid
686 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900687 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900688
689 /**
690 * Request ConnectivityService display provisioning notification.
691 * arg1 = Whether to make the notification visible.
692 * arg2 = NetID.
693 * obj = Intent to be launched when notification selected by user, null if !arg1.
694 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900695 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900696
697 /**
lucaslin2240ef62019-03-12 13:08:03 +0800698 * Used to specify whether a network should be used even if connectivity is partial.
699 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
700 * false)
701 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
702 * obj = network
703 */
lucaslin444d43a2020-02-20 16:56:59 +0800704 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800705
706 /**
lucasline117e2e2019-10-22 18:27:33 +0800707 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
708 * Both of the arguments are bitmasks, and the value of bits come from
709 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900710 * arg1 = unused
711 * arg2 = netId
712 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800713 */
lucaslin444d43a2020-02-20 16:56:59 +0800714 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800715
716 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900717 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
718 * arg1 = unused
719 * arg2 = netId
720 * obj = captive portal data
721 */
lucaslin444d43a2020-02-20 16:56:59 +0800722 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900723
724 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900725 * Used by setRequireVpnForUids.
726 * arg1 = whether the specified UID ranges are required to use a VPN.
727 * obj = Array of UidRange objects.
728 */
729 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
730
731 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900732 * Used internally when setting the default networks for OemNetworkPreferences.
733 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800734 */
735 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
736
737 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800738 * Used to indicate the system default network becomes active.
739 */
740 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
741
742 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900743 * Used internally when setting a network preference for a user profile.
744 * obj = Pair<ProfileNetworkPreference, Listener>
745 */
746 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
747
748 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000749 * Event to specify that reasons for why an uid is blocked changed.
750 * arg1 = uid
751 * arg2 = blockedReasons
752 */
753 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
754
755 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900756 * Event to register a new network offer
757 * obj = NetworkOffer
758 */
759 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
760
761 /**
762 * Event to unregister an existing network offer
763 * obj = INetworkOfferCallback
764 */
765 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
766
767 /**
paulhu51f77dc2021-06-07 02:34:20 +0000768 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
769 */
770 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
771
772 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800773 * Event to set temporary allow bad wifi within a limited time to override
774 * {@code config_networkAvoidBadWifi}.
775 */
776 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
777
778 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100779 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
780 */
781 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
782
783 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900784 * The initial evaluation period is over for this network.
785 *
786 * If no form of connectivity has been found on this network (valid, partial, captive portal)
787 * then the stack will now consider it to have been determined bad.
788 */
789 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
790
791 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000792 * Used internally when the user does not want the network from captive portal app.
793 * obj = Network
794 */
795 private static final int EVENT_USER_DOES_NOT_WANT = 58;
796
797 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000798 * Event to set VPN as preferred network for specific apps.
799 * obj = VpnNetworkPreferenceInfo
800 */
801 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
802
803 /**
chiachangwange0192a72023-02-06 13:25:01 +0000804 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
805 */
806 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
807
808 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000809 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
810 */
811 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
812
813 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900814 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
815 * should be shown.
816 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900817 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900818
819 /**
820 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
821 * should be hidden.
822 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900823 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900824
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800825 /**
826 * The maximum alive time to allow bad wifi configuration for testing.
827 */
828 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
829
Patrick Rohr2857ac42022-01-21 14:58:16 +0100830 /**
chiachangwange0192a72023-02-06 13:25:01 +0000831 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
832 * testing.
833 */
834 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
835
836 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100837 * The priority of the tc police rate limiter -- smaller value is higher priority.
838 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
839 */
840 private static final short TC_PRIO_POLICE = 1;
841
842 /**
843 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
844 */
845 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700846 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100847
Hugo Benichi47011212017-03-30 10:46:05 +0900848 private static String eventName(int what) {
849 return sMagicDecoderRing.get(what, Integer.toString(what));
850 }
851
paulhua10d8212020-11-10 15:32:56 +0800852 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900853 final DnsResolverServiceManager dsm = context.getSystemService(
854 DnsResolverServiceManager.class);
855 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800856 }
857
Cody Kesting73708bf2019-12-18 10:57:50 -0800858 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900859 @VisibleForTesting
860 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700861 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700862 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700863 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700864 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800865 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
866 @VisibleForTesting
867 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
868
Erik Kline32120082017-12-13 19:40:49 +0900869 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900870 @VisibleForTesting
871 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700872
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400873 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800874 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400875
Chalard Jean46bfbf02022-02-02 00:56:25 +0900876 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800877 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700878
Chalard Jean5d70ba42018-06-07 16:44:04 +0900879 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
880 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800881 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400882
Erik Kline05f2b402015-04-30 12:58:40 +0900883 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700884
Chalard Jean46bfbf02022-02-02 00:56:25 +0900885 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400886
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700887 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900888 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700889
Valentin Iftime9fa35092019-09-24 13:32:13 +0200890 private Set<String> mWolSupportedInterfaces;
891
Roshan Pius08c94fb2020-01-16 12:17:17 -0800892 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800893 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800894 private final AppOpsManager mAppOpsManager;
895
896 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400897
chiachangwang3d60bac2023-01-17 14:38:08 +0000898 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900899 private final QosCallbackTracker mQosCallbackTracker;
900 private final NetworkNotificationManager mNotifier;
901 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900902
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700903 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800904 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700905
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900906 // Sequence number for NetworkProvider IDs.
907 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
908 NetworkProvider.FIRST_PROVIDER_ID);
909
Erik Klineedf878b2015-07-09 18:24:03 +0900910 // NetworkRequest activity String log entries.
911 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
912 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
913
Hugo Benichid159fdd2016-07-11 11:05:12 +0900914 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900915 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900916 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
917
Hugo Benichi47011212017-03-30 10:46:05 +0900918 private static final int MAX_WAKELOCK_LOGS = 20;
919 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900920 private int mTotalWakelockAcquisitions = 0;
921 private int mTotalWakelockReleases = 0;
922 private long mTotalWakelockDurationMs = 0;
923 private long mMaxWakelockDurationMs = 0;
924 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900925
Hugo Benichi208c0102016-07-28 17:53:06 +0900926 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900927
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700928 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900929 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700930
Erik Kline95ecfee2016-10-02 18:02:14 +0900931 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900932 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900933
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900934 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800935 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
936 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800937
Patrick Rohr2857ac42022-01-21 14:58:16 +0100938 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
939 // configured via {@link
940 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
941 // Only the handler thread is allowed to access this field.
942 private long mIngressRateLimit = -1;
943
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900944 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
945 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900946 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900947 @GuardedBy("mSelfCertifiedCapabilityCache")
948 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
949 mSelfCertifiedCapabilityCache = new HashMap<>();
950
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900951 // Flag to enable the feature of closing frozen app sockets.
952 private final boolean mDestroyFrozenSockets;
953
954 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
955 private final boolean mDelayDestroyFrozenSockets;
956
957 // Uids that ConnectivityService is pending to close sockets of.
958 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
959
Robert Greenwalt802c1102014-06-02 15:32:02 -0700960 /**
961 * Implements support for the legacy "one network per network type" model.
962 *
963 * We used to have a static array of NetworkStateTrackers, one for each
964 * network type, but that doesn't work any more now that we can have,
965 * for example, more that one wifi network. This class stores all the
966 * NetworkAgentInfo objects that support a given type, but the legacy
967 * API will only see the first one.
968 *
969 * It serves two main purposes:
970 *
971 * 1. Provide information about "the network for a given type" (since this
972 * API only supports one).
973 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
974 * the first network for a given type changes, or if the default network
975 * changes.
976 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900977 @VisibleForTesting
978 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900979
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900980 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900981 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900982
Robert Greenwalt802c1102014-06-02 15:32:02 -0700983 /**
984 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
985 * Each list holds references to all NetworkAgentInfos that are used to
986 * satisfy requests for that network type.
987 *
988 * This array is built out at startup such that an unsupported network
989 * doesn't get an ArrayList instance, making this a tristate:
990 * unsupported, supported but not active and active.
991 *
992 * The actual lists are populated when we scan the network types that
993 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900994 *
995 * Threading model:
996 * - addSupportedType() is only called in the constructor
997 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
998 * They are therefore not thread-safe with respect to each other.
999 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1000 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001001 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001002 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001003 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001004 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001005 @NonNull
1006 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001007
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001008 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1009 // an entry have no timer (equivalent to -1). Lazily loaded.
1010 @NonNull
1011 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1012
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001013 LegacyTypeTracker(@NonNull ConnectivityService service) {
1014 mService = service;
1015 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001016 }
1017
Chiachang Wang3bc52762021-11-25 14:17:57 +08001018 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1019 // addressed.
1020 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001021 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1022 final PackageManager pm = ctx.getPackageManager();
1023 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1024 addSupportedType(TYPE_WIFI);
1025 }
1026 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1027 addSupportedType(TYPE_WIFI_P2P);
1028 }
1029 if (tm.isDataCapable()) {
1030 // Telephony does not have granular support for these types: they are either all
1031 // supported, or none is supported
1032 addSupportedType(TYPE_MOBILE);
1033 addSupportedType(TYPE_MOBILE_MMS);
1034 addSupportedType(TYPE_MOBILE_SUPL);
1035 addSupportedType(TYPE_MOBILE_DUN);
1036 addSupportedType(TYPE_MOBILE_HIPRI);
1037 addSupportedType(TYPE_MOBILE_FOTA);
1038 addSupportedType(TYPE_MOBILE_IMS);
1039 addSupportedType(TYPE_MOBILE_CBS);
1040 addSupportedType(TYPE_MOBILE_IA);
1041 addSupportedType(TYPE_MOBILE_EMERGENCY);
1042 }
1043 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1044 addSupportedType(TYPE_BLUETOOTH);
1045 }
1046 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1047 // TYPE_PROXY is only used on Wear
1048 addSupportedType(TYPE_PROXY);
1049 }
1050 // Ethernet is often not specified in the configs, although many devices can use it via
1051 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001052 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001053 addSupportedType(TYPE_ETHERNET);
1054 }
1055
1056 // Always add TYPE_VPN as a supported type
1057 addSupportedType(TYPE_VPN);
1058 }
1059
1060 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001061 if (mTypeLists[type] != null) {
1062 throw new IllegalStateException(
1063 "legacy list for type " + type + "already initialized");
1064 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001065 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001066 }
1067
Robert Greenwalt802c1102014-06-02 15:32:02 -07001068 public boolean isTypeSupported(int type) {
1069 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1070 }
1071
1072 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001073 synchronized (mTypeLists) {
1074 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1075 return mTypeLists[type].get(0);
1076 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001077 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001078 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001079 }
1080
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001081 public int getRestoreTimerForType(int type) {
1082 synchronized (mTypeLists) {
1083 if (mRestoreTimers == null) {
1084 mRestoreTimers = loadRestoreTimers();
1085 }
1086 return mRestoreTimers.getOrDefault(type, -1);
1087 }
1088 }
1089
1090 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1091 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001092 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001093 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1094 for (final String config : configs) {
1095 final String[] splits = TextUtils.split(config, ",");
1096 if (splits.length != 2) {
1097 logwtf("Invalid restore timer token count: " + config);
1098 continue;
1099 }
1100 try {
1101 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1102 } catch (NumberFormatException e) {
1103 logwtf("Invalid restore timer number format: " + config, e);
1104 }
1105 }
1106 return ret;
1107 }
1108
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001109 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001110 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001111 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001112 log("Sending " + state
1113 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001114 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001115 }
1116 }
1117
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001118 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1119 // network type, to preserve previous behaviour.
1120 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1121 if (vpnNai != mService.getLegacyLockdownNai()) return;
1122
1123 if (vpnNai.declaredUnderlyingNetworks == null
1124 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1125 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1126 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1127 return;
1128 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001129 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001130 vpnNai.declaredUnderlyingNetworks[0]);
1131 if (underlyingNai == null) return;
1132
1133 final int type = underlyingNai.networkInfo.getType();
1134 final DetailedState state = DetailedState.CONNECTED;
1135 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1136 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1137 }
1138
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001139 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001140 public void add(int type, NetworkAgentInfo nai) {
1141 if (!isTypeSupported(type)) {
1142 return; // Invalid network type.
1143 }
1144 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1145
1146 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1147 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001148 return;
1149 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001150 synchronized (mTypeLists) {
1151 list.add(nai);
1152 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001153
Chalard Jean5b409c72021-02-04 13:12:59 +09001154 // Send a broadcast if this is the first network of its type or if it's the default.
1155 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001156
1157 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1158 // to preserve previous behaviour.
1159 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001160 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001161 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1162 mService.sendLegacyNetworkBroadcast(nai, state, type);
1163 }
1164
1165 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1166 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001167 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001168 }
1169
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001170 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001171 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001172 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1173 if (list == null || list.isEmpty()) {
1174 return;
1175 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001176 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001177
Hugo Benichi389633f2016-06-21 09:48:07 +09001178 synchronized (mTypeLists) {
1179 if (!list.remove(nai)) {
1180 return;
1181 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001182 }
1183
Lorenzo Colitti49767722015-05-01 00:30:10 +09001184 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001185 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1186 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001187 }
1188
1189 if (!list.isEmpty() && wasFirstNetwork) {
1190 if (DBG) log("Other network available for type " + type +
1191 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001192 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001193 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001194 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001195 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001196 }
1197 }
1198
1199 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001200 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1201 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001202 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001203 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001204 }
1205 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001206
Chalard Jean46bfbf02022-02-02 00:56:25 +09001207 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001208 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001209 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001210 final DetailedState state = nai.networkInfo.getDetailedState();
1211 for (int type = 0; type < mTypeLists.length; type++) {
1212 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001213 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001214 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001215 if (isFirst || contains && isDefault) {
1216 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001217 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001218 }
1219 }
1220 }
1221
Robert Greenwalt94e22142014-07-30 16:31:24 -07001222 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001223 pw.println("mLegacyTypeTracker:");
1224 pw.increaseIndent();
1225 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001226 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001227 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001228 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001229 pw.println();
1230 pw.println("Current state:");
1231 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001232 synchronized (mTypeLists) {
1233 for (int type = 0; type < mTypeLists.length; type++) {
1234 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1235 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001236 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001237 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001238 }
1239 }
1240 pw.decreaseIndent();
1241 pw.decreaseIndent();
1242 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001243 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001244 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001245 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001246
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001247 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001248 /**
1249 * Helper class which parses out priority arguments and dumps sections according to their
1250 * priority. If priority arguments are omitted, function calls the legacy dump command.
1251 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001252 private class LocalPriorityDump {
1253 private static final String PRIORITY_ARG = "--dump-priority";
1254 private static final String PRIORITY_ARG_HIGH = "HIGH";
1255 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1256
1257 LocalPriorityDump() {}
1258
1259 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1260 doDump(fd, pw, new String[] {DIAG_ARG});
1261 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001262 }
1263
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001264 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1265 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001266 }
1267
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001268 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1269 if (args == null) {
1270 dumpNormal(fd, pw, args);
1271 return;
1272 }
1273
1274 String priority = null;
1275 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1276 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1277 argIndex++;
1278 priority = args[argIndex];
1279 }
1280 }
1281
1282 if (PRIORITY_ARG_HIGH.equals(priority)) {
1283 dumpHigh(fd, pw);
1284 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1285 dumpNormal(fd, pw, args);
1286 } else {
1287 // ConnectivityService publishes binder service using publishBinderService() with
1288 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001289 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1290 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001291 // TODO: Integrate into signal dump.
1292 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001293 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001294 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001295 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001296
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001297 /**
1298 * Dependencies of ConnectivityService, for injection in tests.
1299 */
1300 @VisibleForTesting
1301 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001302 public int getCallingUid() {
1303 return Binder.getCallingUid();
1304 }
1305
Chalard Jeandf29a852023-05-29 17:02:43 +09001306 public boolean isAtLeastS() {
1307 return SdkLevel.isAtLeastS();
1308 }
1309
1310 public boolean isAtLeastT() {
1311 return SdkLevel.isAtLeastT();
1312 }
1313
1314 public boolean isAtLeastU() {
1315 return SdkLevel.isAtLeastU();
1316 }
1317
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001318 /**
1319 * Get system properties to use in ConnectivityService.
1320 */
1321 public MockableSystemProperties getSystemProperties() {
1322 return new MockableSystemProperties();
1323 }
1324
1325 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001326 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1327 */
1328 public ConnectivityResources getResources(@NonNull Context ctx) {
1329 return new ConnectivityResources(ctx);
1330 }
1331
1332 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001333 * Create a HandlerThread to use in ConnectivityService.
1334 */
1335 public HandlerThread makeHandlerThread() {
1336 return new HandlerThread("ConnectivityServiceThread");
1337 }
1338
1339 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001340 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001341 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001342 public NetworkStackClientBase getNetworkStack() {
1343 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001344 }
1345
1346 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001347 * @see ProxyTracker
1348 */
1349 public ProxyTracker makeProxyTracker(@NonNull Context context,
1350 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001351 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001352 }
1353
1354 /**
1355 * @see NetIdManager
1356 */
1357 public NetIdManager makeNetIdManager() {
1358 return new NetIdManager();
1359 }
1360
1361 /**
1362 * @see NetworkUtils#queryUserAccess(int, int)
1363 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001364 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1365 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001366 }
1367
1368 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001369 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1370 * requires CAP_NET_ADMIN, which the unit tests do not have.
1371 */
1372 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1373 InetSocketAddress remote) {
1374 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1375 }
1376
1377 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001378 * @see MultinetworkPolicyTracker
1379 */
1380 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1381 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1382 return new MultinetworkPolicyTracker(c, h, r);
1383 }
1384
Aaron Huang330a4c02020-10-27 03:36:19 +08001385 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001386 * @see AutomaticOnOffKeepaliveTracker
1387 */
1388 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1389 @NonNull Context c, @NonNull Handler h) {
1390 return new AutomaticOnOffKeepaliveTracker(c, h);
1391 }
1392
1393 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001394 * @see BatteryStatsManager
1395 */
1396 public void reportNetworkInterfaceForTransports(Context context, String iface,
1397 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001398 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001399 context.getSystemService(BatteryStatsManager.class);
1400 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1401 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001402
1403 public boolean getCellular464XlatEnabled() {
1404 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1405 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001406
1407 /**
1408 * @see PendingIntent#intentFilterEquals
1409 */
1410 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1411 return a.intentFilterEquals(b);
1412 }
1413
1414 /**
1415 * @see LocationPermissionChecker
1416 */
1417 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1418 return new LocationPermissionChecker(context);
1419 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001420
1421 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001422 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001423 *
1424 * This method returns null in versions before T, where carrier privilege
1425 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001426 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001427 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001428 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1429 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001430 if (isAtLeastT()) {
Chalard Jean84dfa9f2023-01-30 11:23:20 +09001431 return new CarrierPrivilegeAuthenticator(context, this, tm);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001432 } else {
1433 return null;
1434 }
1435 }
1436
1437 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001438 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001439 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001440 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001441 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001442 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001443
1444 /**
1445 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001446 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001447 * @return BpfNetMaps implementation.
1448 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001449 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1450 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001451 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001452
1453 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001454 * @see ClatCoordinator
1455 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001456 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001457 public ClatCoordinator getClatCoordinator(INetd netd) {
1458 return new ClatCoordinator(
1459 new ClatCoordinator.Dependencies() {
1460 @NonNull
1461 public INetd getNetd() {
1462 return netd;
1463 }
1464 });
1465 }
1466
1467 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001468 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1469 */
1470 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1471 final InterfaceParams params = InterfaceParams.getByName(iface);
1472 if (params == null) {
1473 // the interface might have disappeared.
1474 logw("Failed to get interface params for interface " + iface);
1475 return;
1476 }
1477 try {
1478 // converting rateInBytesPerSecond from long to int is safe here because the
1479 // setting's range is limited to INT_MAX.
1480 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001481 Log.i(TAG,
1482 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001483 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1484 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1485 } catch (IOException e) {
1486 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1487 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1488 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1489 + ") failure: ", e);
1490 }
1491 }
1492
1493 /**
1494 * Wraps {@link TcUtils#tcFilterDelDev}
1495 */
1496 public void disableIngressRateLimit(String iface) {
1497 final InterfaceParams params = InterfaceParams.getByName(iface);
1498 if (params == null) {
1499 // the interface might have disappeared.
1500 logw("Failed to get interface params for interface " + iface);
1501 return;
1502 }
1503 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001504 Log.i(TAG,
1505 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001506 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1507 } catch (IOException e) {
1508 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1509 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1510 }
1511 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001512
1513 /**
1514 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1515 */
1516 // TODO: when available in all active branches:
1517 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1518 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1519 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1520 return BroadcastOptionsShimImpl.newInstance(options);
1521 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001522
1523 /**
1524 * Wrapper method for
1525 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1526 *
1527 * @param changeId The ID of the compatibility change in question.
1528 * @param packageName The package name of the app in question.
1529 * @param user The user that the operation is done for.
1530 * @return {@code true} if the change is enabled for the specified package.
1531 */
1532 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1533 @NonNull final UserHandle user) {
1534 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1535 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001536
1537 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001538 * As above but with a UID.
1539 * @see CompatChanges#isChangeEnabled(long, int)
1540 */
1541 public boolean isChangeEnabled(final long changeId, final int uid) {
1542 return CompatChanges.isChangeEnabled(changeId, uid);
1543 }
1544
1545 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001546 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1547 *
1548 * @param ranges target uid ranges
1549 * @param exemptUids uids to skip close socket
1550 */
1551 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1552 @NonNull final Set<Integer> exemptUids)
1553 throws SocketException, InterruptedIOException, ErrnoException {
1554 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1555 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001556
1557 /**
1558 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1559 *
1560 * @param ownerUids target uids to close sockets
1561 */
1562 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1563 throws SocketException, InterruptedIOException, ErrnoException {
1564 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1565 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001566
1567 /**
1568 * Schedule the evaluation timeout.
1569 *
1570 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1571 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1572 * of these events happen, this time will run out, after which the network is considered
1573 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1574 * on this network and considers it won't provide connectivity. In particular, that means
1575 * it's when the system prefers it to cell if it's wifi and configuration says it should
1576 * prefer bad wifi to cell.
1577 */
1578 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1579 @NonNull final Network network, final long delayMs) {
1580 handler.sendMessageDelayed(
1581 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1582 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001583 }
1584
junyulaie7c7d2a2021-01-26 15:29:15 +08001585 public ConnectivityService(Context context) {
1586 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001587 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1588 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001589 }
1590
1591 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001592 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1593 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001594 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001595
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001596 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001597 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001598 mSystemProperties = mDeps.getSystemProperties();
1599 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001600 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001601 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001602 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1603 // Pass limit - 1 to maintain backward compatibility.
1604 // TODO: Remove the workaround.
1605 mNetworkRequestCounter =
1606 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1607 mSystemNetworkRequestCounter =
1608 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001609
Hugo Benichi208c0102016-07-28 17:53:06 +09001610 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001611 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1612 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001613 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001614 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001615 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001616 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1617 mDefaultNetworkRequests.add(mDefaultRequest);
1618 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001619
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001620 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001621 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001622
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001623 // The default WiFi request is a background request so that apps using WiFi are
1624 // migrated to a better network (typically ethernet) when one comes up, instead
1625 // of staying on WiFi forever.
1626 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1627 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1628
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001629 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1630 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1631 NetworkRequest.Type.BACKGROUND_REQUEST);
1632
Chalard Jean0702f982021-09-16 21:50:07 +09001633 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1634 // TODO: Consider making the timer customizable.
1635 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1636 mCellularRadioTimesharingCapable =
1637 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1638
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001639 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1640 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1641
1642 if (SdkLevel.isAtLeastU()) {
1643 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1644 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1645 final int defaultUMarkMask = 0x80000000; // u32
1646
1647 if ((mark == 0) || (mask == 0)) {
1648 // simply treat unset/disabled as the default U value
1649 mark = defaultUMarkMask;
1650 mask = defaultUMarkMask;
1651 }
1652 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1653 // invalid device overlay settings
1654 throw new IllegalArgumentException(
1655 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1656 }
1657 }
1658
1659 mWakeUpMark = mark;
1660 mWakeUpMask = mask;
1661
Paul Hu51f816b2022-08-11 14:43:47 +00001662 mNetd = netd;
1663 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001664 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001665 mPermissionMonitor =
1666 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001667 mHandlerThread.start();
1668 mHandler = new InternalHandler(mHandlerThread.getLooper());
1669 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001670 mConnectivityDiagnosticsHandler =
1671 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001672
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001673 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001674 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001675
junyulaie7c7d2a2021-01-26 15:29:15 +08001676 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001677 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001678 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001679 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001680
Wink Saville32506bc2013-06-29 21:10:57 -07001681 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001682 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001683 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001684 mCarrierPrivilegeAuthenticator =
1685 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001686
Sudheer Shanka9967d462021-03-18 19:09:25 +00001687 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001688 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1689 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001690 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001691
1692 final PowerManager powerManager = (PowerManager) context.getSystemService(
1693 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001694 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001695 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001696
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001697 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1698 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001699 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001700 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001701 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001702 mProtectedNetworks.add(p);
1703 } else {
1704 if (DBG) loge("Ignoring protectedNetwork " + p);
1705 }
1706 }
1707
soma, kawata29444ae2019-05-23 09:30:40 +09001708 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1709
James Mattis02220e22021-03-13 19:27:21 -08001710 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001711 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001712 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001713 final IntentFilter userIntentFilter = new IntentFilter();
1714 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1715 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1716 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1717 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001718
James Mattis02220e22021-03-13 19:27:21 -08001719 // Listen to package add/removes for netd
1720 final IntentFilter packageIntentFilter = new IntentFilter();
1721 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1722 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1723 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1724 packageIntentFilter.addDataScheme("package");
1725 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001726 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001727
Motomu Utsumi1e51a642023-07-18 15:11:41 +09001728 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001729
Chalard Jean46bfbf02022-02-02 00:56:25 +09001730 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001731 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001732 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001733 } catch (RemoteException | ServiceSpecificException e) {
1734 loge("Error registering event listener :" + e);
1735 }
1736
Erik Kline05f2b402015-04-30 12:58:40 +09001737 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1738 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001739
chiachangwang7c17c282023-02-02 05:58:59 +00001740 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001741 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001742 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001743
1744 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001745 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001746 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1747 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001748 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001749 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1750 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001751
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001752 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001753 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001754 mNetworkRanker =
1755 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1756
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001757 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001758
Chiachang Wangc1215d32020-10-20 15:38:58 +08001759 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001760 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001761
Chalard Jean28018572020-12-21 18:36:52 +09001762 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1763 // request that doesn't allow fallback to the default network. It should never be visible
1764 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1765 // arguments like the handler or the DnsResolver.
1766 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001767 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001768 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001769 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001770 new LinkProperties(), new NetworkCapabilities(),
1771 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001772 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1773 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001774
1775 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001776 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1777 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1778 // Even if it could, running on S would at least require mocking out the BPF map,
1779 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1780 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001781 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001782 mDscpPolicyTracker = new DscpPolicyTracker();
1783 }
Tyler Wear72388212021-09-09 14:49:02 -07001784 } catch (ErrnoException e) {
1785 loge("Unable to create DscpPolicyTracker");
1786 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001787
1788 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1789 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001790
Chalard Jeandf29a852023-05-29 17:02:43 +09001791 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001792 mCdmps = new CompanionDeviceManagerProxyService(context);
1793 } else {
1794 mCdmps = null;
1795 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001796
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001797 mDestroyFrozenSockets = mDeps.isAtLeastU()
1798 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
1799 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1800 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
1801 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001802 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1803 new UidFrozenStateChangedCallback() {
1804 @Override
1805 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1806 if (uids.length != frozenStates.length) {
1807 Log.wtf(TAG, "uids has length " + uids.length
1808 + " but frozenStates has length " + frozenStates.length);
1809 return;
1810 }
1811
1812 final UidFrozenStateChangedArgs args =
1813 new UidFrozenStateChangedArgs(uids, frozenStates);
1814
1815 mHandler.sendMessage(
1816 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1817 }
1818 };
1819
1820 final ActivityManager activityManager =
1821 mContext.getSystemService(ActivityManager.class);
1822 activityManager.registerUidFrozenStateChangedCallback(
1823 (Runnable r) -> r.run(), frozenStateChangedCallback);
1824 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001825 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001826
Xiao Ma0a171c02022-01-23 16:14:51 +00001827 /**
1828 * Check whether or not the device supports Ethernet transport.
1829 */
1830 public static boolean deviceSupportsEthernet(final Context context) {
1831 final PackageManager pm = context.getPackageManager();
1832 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1833 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1834 }
1835
Chalard Jean46adcf32018-04-18 20:18:38 +09001836 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001837 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1838 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001839 }
1840
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001841 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1842 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001843 final NetworkCapabilities netCap = new NetworkCapabilities();
1844 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001845 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001846 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001847 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001848 return netCap;
1849 }
1850
James Mattis45d81842021-01-10 14:24:24 -08001851 private NetworkRequest createDefaultRequest() {
1852 return createDefaultInternetRequestForTransport(
1853 TYPE_NONE, NetworkRequest.Type.REQUEST);
1854 }
1855
lucaslin3ba7cc22022-12-19 02:35:33 +00001856 private NetworkRequest createVpnRequest() {
1857 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1858 .withoutDefaultCapabilities()
1859 .addTransportType(TRANSPORT_VPN)
1860 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1861 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1862 .build();
1863 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1864 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1865 }
1866
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001867 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001868 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001869 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001870 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001871 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001872 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001873 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001874 netCap.addTransportType(transportType);
1875 }
James Mattis45d81842021-01-10 14:24:24 -08001876 return createNetworkRequest(type, netCap);
1877 }
1878
1879 private NetworkRequest createNetworkRequest(
1880 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001881 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001882 }
1883
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001884 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1885 NetworkRequest.Type type) {
1886 final NetworkCapabilities netCap = new NetworkCapabilities();
1887 netCap.clearAll();
1888 netCap.addCapability(capability);
1889 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1890 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1891 }
1892
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001893 // Used only for testing.
1894 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001895 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001896 // changing ContentResolver to make registerContentObserver non-final).
1897 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1898 // by subclassing SettingsObserver.
1899 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001900 void updateAlwaysOnNetworks() {
1901 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001902 }
1903
Erik Kline9a62f012018-03-21 07:18:33 -07001904 // See FakeSettingsProvider comment above.
1905 @VisibleForTesting
1906 void updatePrivateDnsSettings() {
1907 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1908 }
1909
paulhu51f77dc2021-06-07 02:34:20 +00001910 @VisibleForTesting
1911 void updateMobileDataPreferredUids() {
1912 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1913 }
1914
Patrick Rohr2857ac42022-01-21 14:58:16 +01001915 @VisibleForTesting
1916 void updateIngressRateLimit() {
1917 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1918 }
1919
Aaron Huang40b52442021-06-08 04:34:24 +08001920 @VisibleForTesting
1921 void simulateUpdateProxyInfo(@Nullable final Network network,
1922 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001923 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08001924 new Pair<>(network, proxyInfo)).sendToTarget();
1925 }
1926
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001927 private void handleAlwaysOnNetworkRequest(
1928 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001929 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001930 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001931 handleAlwaysOnNetworkRequest(networkRequest, enable);
1932 }
1933
1934 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001935 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001936 if (enable == isEnabled) {
1937 return; // Nothing to do.
1938 }
1939
1940 if (enable) {
1941 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001942 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001943 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001944 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001945 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001946 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1947 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001948 }
1949 }
1950
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001951 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001952 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1953 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1954 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1955 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001956 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1957 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001958 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001959 }
1960
paulhu51f77dc2021-06-07 02:34:20 +00001961 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001962 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001963 private void registerSettingsCallbacks() {
1964 // Watch for global HTTP proxy changes.
1965 mSettingsObserver.observe(
1966 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1967 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1968
Chalard Jean46bfbf02022-02-02 00:56:25 +09001969 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001970 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001971 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001972 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1973
Chalard Jean46bfbf02022-02-02 00:56:25 +09001974 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001975 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001976 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001977 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001978
1979 // Watch for mobile data preferred uids changes.
1980 mSettingsObserver.observe(
1981 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1982 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001983
1984 // Watch for ingress rate limit changes.
1985 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01001986 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01001987 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1988 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001989 }
1990
Erik Kline31b4a9e2018-01-11 21:07:29 +09001991 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001992 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1993 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001994 }
1995 }
1996
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001997 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001998 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1999 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002000 return mNextNetworkRequestId++;
2001 }
2002
junyulai74f9a8b2018-06-13 15:00:37 +08002003 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002004 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002005 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002006 if (network == null) {
2007 return null;
2008 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002009 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002010 }
2011
2012 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002013 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002014 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002015 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002016 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002017
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002018 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002019 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002020 private NetworkAgentInfo getVpnForUid(int uid) {
2021 synchronized (mNetworkForNetId) {
2022 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2023 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002024 if (nai.isVPN() && nai.everConnected()
2025 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002026 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002027 }
2028 }
2029 }
2030 return null;
2031 }
2032
Chalard Jean46bfbf02022-02-02 00:56:25 +09002033 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002034 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002035 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002036 final NetworkAgentInfo nai = getVpnForUid(uid);
2037 if (nai != null) return nai.declaredUnderlyingNetworks;
2038 return null;
2039 }
2040
Lorenzo Colittia7574052021-01-19 01:33:05 +09002041 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002042 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002043
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002044 final Network[] networks = getVpnUnderlyingNetworks(uid);
2045 if (networks != null) {
2046 // getUnderlyingNetworks() returns:
2047 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2048 // empty array => the VPN explicitly said "no default network".
2049 // non-empty array => the VPN specified one or more default networks; we use the
2050 // first one.
2051 if (networks.length > 0) {
2052 nai = getNetworkAgentInfoForNetwork(networks[0]);
2053 } else {
2054 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002055 }
2056 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002057 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002058 }
2059
2060 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002061 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002062 */
paulhu7aeba372020-12-30 00:42:19 +08002063 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2064 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002065 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002066 if (ignoreBlocked) {
2067 return false;
2068 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002069 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002070 final long ident = Binder.clearCallingIdentity();
2071 try {
2072 final boolean metered = nc == null ? true : nc.isMetered();
2073 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2074 } finally {
2075 Binder.restoreCallingIdentity(ident);
2076 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002077 }
2078
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002079 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002080 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2081 return;
2082 }
Hugo Benichi47011212017-03-30 10:46:05 +09002083 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002084 synchronized (mBlockedAppUids) {
2085 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002086 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002087 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002088 blocked = false;
2089 } else {
2090 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002091 }
2092 }
Hugo Benichi47011212017-03-30 10:46:05 +09002093 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2094 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2095 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002096 }
2097
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002098 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002099 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2100 return;
2101 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002102 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002103 final int requestId = nri.getActiveRequest() != null
2104 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002105 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002106 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002107 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002108 }
2109
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002110 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002111 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002112 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002113 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002114 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002115 @NonNull
2116 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2117 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002118 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2119 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2120 // but only exists if an app asks about them or requests them. Ensure the requesting app
2121 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002122 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002123 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2124 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2125 null /* extraInfo */);
2126 }
2127 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002128 return filtered;
2129 }
2130
2131 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2132 boolean ignoreBlocked) {
2133 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2134 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002135 }
2136
2137 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002138 * Return NetworkInfo for the active (i.e., connected) network interface.
2139 * It is assumed that at most one network is active at a time. If more
2140 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002141 * @return the info for the active network, or {@code null} if none is
2142 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002143 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002144 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002145 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002146 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002147 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002148 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002149 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2150 if (nai == null) return null;
2151 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2152 maybeLogBlockedNetworkInfo(networkInfo, uid);
2153 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002154 }
2155
Paul Jensen1f567382015-02-13 14:18:39 -05002156 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002157 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002158 public Network getActiveNetwork() {
2159 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002160 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002161 }
2162
2163 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002164 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002165 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002166 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002167 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002168 }
2169
Chalard Jean46bfbf02022-02-02 00:56:25 +09002170 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002171 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002172 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2173 if (vpnNai != null) {
2174 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2175 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2176 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002177 }
Paul Jensen1f567382015-02-13 14:18:39 -05002178 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002179
James Mattis2516da32021-01-31 17:06:19 -08002180 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002181 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2182 ignoreBlocked)) {
2183 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002184 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002185 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002186 }
2187
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002188 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002189 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002190 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002191 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002192 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2193 if (nai == null) return null;
2194 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002195 }
2196
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002197 /** Returns a NetworkInfo object for a network that doesn't exist. */
2198 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2199 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2200 getNetworkTypeName(networkType), "" /* subtypeName */);
2201 info.setIsAvailable(true);
2202 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2203 // background data is restricted.
2204 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2205 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2206 ? DetailedState.BLOCKED
2207 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002208 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2209 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002210 return info;
2211 }
2212
Lorenzo Colittia7574052021-01-19 01:33:05 +09002213 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002214 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2215 return null;
2216 }
2217 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002218 if (nai == null) {
2219 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002220 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002221 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2222 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002223 }
2224
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002225 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002226 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002227 public NetworkInfo getNetworkInfo(int networkType) {
2228 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002229 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002230 if (getVpnUnderlyingNetworks(uid) != null) {
2231 // A VPN is active, so we may need to return one of its underlying networks. This
2232 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002233 // getNetworkAgentInfoForUid.
2234 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2235 if (nai == null) return null;
2236 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2237 if (networkInfo.getType() == networkType) {
2238 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002239 }
2240 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002241 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002242 }
2243
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002244 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002245 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002246 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002247 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002248 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002249 if (nai == null) return null;
2250 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002251 }
2252
2253 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002254 public NetworkInfo[] getAllNetworkInfo() {
2255 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002256 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002257 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2258 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002259 NetworkInfo info = getNetworkInfo(networkType);
2260 if (info != null) {
2261 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002262 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002263 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002264 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002265 }
2266
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002267 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002268 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002269 public Network getNetworkForType(int networkType) {
2270 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002271 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2272 return null;
2273 }
2274 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2275 if (nai == null) {
2276 return null;
2277 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002278 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002279 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2280 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002281 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002282 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002283 }
2284
2285 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002286 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002287 public Network[] getAllNetworks() {
2288 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002289 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002290 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002291 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002292 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002293 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002294 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002295 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002296 }
2297
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002298 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002299 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002300 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002301 // The basic principle is: if an app's traffic could possibly go over a
2302 // network, without the app doing anything multinetwork-specific,
2303 // (hence, by "default"), then include that network's capabilities in
2304 // the array.
2305 //
2306 // In the normal case, app traffic only goes over the system's default
2307 // network connection, so that's the only network returned.
2308 //
2309 // With a VPN in force, some app traffic may go into the VPN, and thus
2310 // over whatever underlying networks the VPN specifies, while other app
2311 // traffic may go over the system default network (e.g.: a split-tunnel
2312 // VPN, or an app disallowed by the VPN), so the set of networks
2313 // returned includes the VPN's underlying networks and the system
2314 // default.
2315 enforceAccessPermission();
2316
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002317 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002318
James Mattis2516da32021-01-31 17:06:19 -08002319 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2320 if (!nri.isBeingSatisfied()) {
2321 continue;
2322 }
2323 final NetworkAgentInfo nai = nri.getSatisfier();
2324 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2325 if (null != nc
2326 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2327 && !result.containsKey(nai.network)) {
2328 result.put(
2329 nai.network,
2330 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002331 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002332 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2333 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002334 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002335 }
2336
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002337 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002338 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002339 if (null != networks) {
2340 for (final Network network : networks) {
2341 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2342 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002343 result.put(
2344 network,
2345 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002346 nc,
2347 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002348 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002349 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002350 }
2351 }
2352 }
2353
2354 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2355 out = result.values().toArray(out);
2356 return out;
2357 }
2358
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002359 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2360 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2361 // can call sampleConnectivityState and make the checks on it.
2362 @NonNull
2363 private StatsEvent sampleConnectivityStateToStatsEvent() {
2364 final ConnectivityStateSample sample = sampleConnectivityState();
2365 return ConnectivityStatsLog.buildStatsEvent(
2366 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2367 sample.getNetworkCountPerTransports().toByteArray(),
2368 sample.getConnectionDurationPerTransports().toByteArray(),
2369 sample.getNetworkRequestCount().toByteArray(),
2370 sample.getNetworks().toByteArray());
2371 }
2372
2373 /**
2374 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2375 *
2376 * This is used for metrics. These snapshots will be sampled and constitute a base for
2377 * statistics about connectivity state of devices.
2378 */
2379 @VisibleForTesting
2380 @NonNull
2381 public ConnectivityStateSample sampleConnectivityState() {
2382 ensureRunningOnConnectivityServiceThread();
2383 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2384 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2385 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2386 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2387 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2388 return builder.build();
2389 }
2390
2391 private static NetworkCountPerTransports sampleNetworkCount(
2392 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2393 final SparseIntArray countPerTransports = new SparseIntArray();
2394 for (final NetworkAgentInfo nai : nais) {
2395 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2396 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2397 }
2398 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2399 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2400 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2401 c.setTransportTypes(countPerTransports.keyAt(i));
2402 c.setNetworkCount(countPerTransports.valueAt(i));
2403 builder.addNetworkCountForTransports(c);
2404 }
2405 return builder.build();
2406 }
2407
2408 private static ConnectionDurationPerTransports sampleConnectionDuration(
2409 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2410 final ConnectionDurationPerTransports.Builder builder =
2411 ConnectionDurationPerTransports.newBuilder();
2412 for (final NetworkAgentInfo nai : nais) {
2413 final ConnectionDurationForTransports.Builder c =
2414 ConnectionDurationForTransports.newBuilder();
2415 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2416 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2417 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2418 // Add millisPerSecond/2 to round up or down to the nearest value
2419 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2420 builder.addConnectionDurationForTransports(c);
2421 }
2422 return builder.build();
2423 }
2424
2425 private static NetworkRequestCount sampleNetworkRequestCount(
2426 @NonNull final Collection<NetworkRequestInfo> nris) {
2427 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2428 final SparseIntArray countPerType = new SparseIntArray();
2429 for (final NetworkRequestInfo nri : nris) {
2430 final int type;
2431 if (Process.SYSTEM_UID == nri.mAsUid) {
2432 // The request is filed "as" the system, so it's the system on its own behalf.
2433 type = RequestType.RT_SYSTEM.getNumber();
2434 } else if (Process.SYSTEM_UID == nri.mUid) {
2435 // The request is filed by the system as some other app, so it's the system on
2436 // behalf of an app.
2437 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2438 } else {
2439 // Not the system, so it's an app requesting on its own behalf.
2440 type = RequestType.RT_APP.getNumber();
2441 }
2442 countPerType.put(type, countPerType.get(type, 0));
2443 }
2444 for (int i = countPerType.size() - 1; i >= 0; --i) {
2445 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2446 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2447 r.setRequestCount(countPerType.valueAt(i));
2448 builder.addRequestCountForType(r);
2449 }
2450 return builder.build();
2451 }
2452
2453 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2454 final NetworkList.Builder builder = NetworkList.newBuilder();
2455 for (final NetworkAgentInfo nai : nais) {
2456 final NetworkCapabilities nc = nai.networkCapabilities;
2457 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2458 d.setTransportTypes((int) nc.getTransportTypesInternal());
2459 final MeteredState meteredState;
2460 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2461 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2462 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2463 meteredState = MeteredState.METERED_NO;
2464 } else {
2465 meteredState = MeteredState.METERED_YES;
2466 }
2467 d.setMeteredState(meteredState);
2468 final ValidatedState validatedState;
2469 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2470 validatedState = ValidatedState.VS_PORTAL;
2471 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2472 validatedState = ValidatedState.VS_PARTIAL;
2473 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2474 validatedState = ValidatedState.VS_VALID;
2475 } else {
2476 validatedState = ValidatedState.VS_INVALID;
2477 }
2478 d.setValidatedState(validatedState);
2479 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2480 d.setCapabilities(nc.getCapabilitiesInternal());
2481 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2482 builder.addNetworkDescription(d);
2483 }
2484 return builder.build();
2485 }
2486
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002487 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002488 public boolean isNetworkSupported(int networkType) {
2489 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002490 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002491 }
2492
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002493 /**
2494 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002495 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002496 * @return the ip properties for the active network, or {@code null} if
2497 * none is active
2498 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002499 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002500 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002501 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002502 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002503 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2504 if (nai == null) return null;
2505 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002506 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002507 }
2508
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002509 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002510 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002511 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002512 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002513 final LinkProperties lp = getLinkProperties(nai);
2514 if (lp == null) return null;
2515 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002516 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002517 }
2518
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002519 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002520 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002521 public LinkProperties getLinkProperties(Network network) {
2522 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002523 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2524 if (lp == null) return null;
2525 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002526 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002527 }
2528
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002529 @Nullable
2530 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002531 if (nai == null) {
2532 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002533 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002534 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002535 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002536 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002537 }
2538
lucaslinc582d502022-01-27 09:07:00 +08002539 @Override
2540 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002541 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002542 @NonNull String packageName, @Nullable String callingAttributionTag) {
2543 Objects.requireNonNull(packageName);
2544 Objects.requireNonNull(lp);
2545 enforceNetworkStackOrSettingsPermission();
2546 if (!checkAccessPermission(-1 /* pid */, uid)) {
2547 return null;
2548 }
2549 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2550 }
2551
Qingxi Lib2748102020-01-08 12:51:49 -08002552 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2553 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2554 }
2555
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002556 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002557 if (nai == null) return null;
2558 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002559 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002560 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002561 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002562 }
2563
2564 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002565 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2566 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002567 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002568 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002569 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002570 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002571 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002572 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002573 }
2574
lucaslinc582d502022-01-27 09:07:00 +08002575 @Override
lucaslind2b06132022-03-02 10:56:57 +08002576 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2577 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2578 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002579 Objects.requireNonNull(nc);
2580 Objects.requireNonNull(packageName);
2581 enforceNetworkStackOrSettingsPermission();
2582 if (!checkAccessPermission(-1 /* pid */, uid)) {
2583 return null;
2584 }
2585 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2586 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2587 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2588 callingAttributionTag);
2589 }
2590
lucaslin69e1aa92022-03-22 18:15:09 +08002591 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2592 if (nc.getUnderlyingNetworks() != null
2593 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2594 nc.setUnderlyingNetworks(null);
2595 }
2596 }
2597
Qingxi Libb8da982020-01-17 17:54:27 -08002598 @VisibleForTesting
2599 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002600 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002601 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2602 // this would be expensive (one more permission check every time any NC callback is
2603 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2604 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2605 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002606 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002607 if (!checkSettingsPermission(callerPid, callerUid)) {
2608 newNc.setUids(null);
2609 newNc.setSSID(null);
2610 }
Etan Cohen107ae952018-12-30 17:59:59 -08002611 if (newNc.getNetworkSpecifier() != null) {
2612 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2613 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002614 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2615 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002616 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2617 newNc.setAdministratorUids(new int[0]);
2618 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002619 if (!checkAnyPermissionOf(mContext,
Benedict Wong53de25f2021-03-24 14:01:51 -07002620 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002621 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002622 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002623 }
lucaslin69e1aa92022-03-22 18:15:09 +08002624 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002625
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002626 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002627 }
2628
Roshan Pius98f59ec2021-02-23 08:47:39 -08002629 /**
2630 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002631 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002632 * NetworkCapabilities.
2633 * Note: This wrapper does not support any sort of invalidation and thus must not be
2634 * persistent or long-lived. It may only be used for the time necessary to
2635 * compute the redactions required by one particular NetworkCallback or
2636 * synchronous call.
2637 */
2638 private class RedactionPermissionChecker {
2639 private final int mCallingPid;
2640 private final int mCallingUid;
2641 @NonNull private final String mCallingPackageName;
2642 @Nullable private final String mCallingAttributionTag;
2643
2644 private Boolean mHasLocationPermission = null;
2645 private Boolean mHasLocalMacAddressPermission = null;
2646 private Boolean mHasSettingsPermission = null;
2647
2648 RedactionPermissionChecker(int callingPid, int callingUid,
2649 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2650 mCallingPid = callingPid;
2651 mCallingUid = callingUid;
2652 mCallingPackageName = callingPackageName;
2653 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002654 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002655
2656 private boolean hasLocationPermissionInternal() {
2657 final long token = Binder.clearCallingIdentity();
2658 try {
2659 return mLocationPermissionChecker.checkLocationPermission(
2660 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2661 null /* message */);
2662 } finally {
2663 Binder.restoreCallingIdentity(token);
2664 }
2665 }
2666
2667 /**
2668 * Returns whether the app holds location permission or not (might return cached result
2669 * if the permission was already checked before).
2670 */
2671 public boolean hasLocationPermission() {
2672 if (mHasLocationPermission == null) {
2673 // If there is no cached result, perform the check now.
2674 mHasLocationPermission = hasLocationPermissionInternal();
2675 }
2676 return mHasLocationPermission;
2677 }
2678
2679 /**
2680 * Returns whether the app holds local mac address permission or not (might return cached
2681 * result if the permission was already checked before).
2682 */
2683 public boolean hasLocalMacAddressPermission() {
2684 if (mHasLocalMacAddressPermission == null) {
2685 // If there is no cached result, perform the check now.
2686 mHasLocalMacAddressPermission =
2687 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2688 }
2689 return mHasLocalMacAddressPermission;
2690 }
2691
2692 /**
2693 * Returns whether the app holds settings permission or not (might return cached
2694 * result if the permission was already checked before).
2695 */
2696 public boolean hasSettingsPermission() {
2697 if (mHasSettingsPermission == null) {
2698 // If there is no cached result, perform the check now.
2699 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2700 }
2701 return mHasSettingsPermission;
2702 }
2703 }
2704
2705 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2706 @NetworkCapabilities.NetCapability long redaction) {
2707 return (redactions & redaction) != 0;
2708 }
2709
2710 /**
2711 * Use the provided |applicableRedactions| to check the receiving app's
2712 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2713 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2714 * before being sent to the corresponding app.
2715 */
2716 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2717 @NetworkCapabilities.RedactionType long applicableRedactions,
2718 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2719 boolean includeLocationSensitiveInfo) {
2720 long redactions = applicableRedactions;
2721 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2722 if (includeLocationSensitiveInfo
2723 && redactionPermissionChecker.hasLocationPermission()) {
2724 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2725 }
2726 }
2727 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2728 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2729 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2730 }
2731 }
2732 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2733 if (redactionPermissionChecker.hasSettingsPermission()) {
2734 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2735 }
2736 }
2737 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002738 }
2739
Qingxi Lib2748102020-01-08 12:51:49 -08002740 @VisibleForTesting
2741 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002742 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002743 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002744 int callingPid, int callingUid, @NonNull String callingPkgName,
2745 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002746 if (nc == null) {
2747 return null;
2748 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002749 // Avoid doing location permission check if the transport info has no location sensitive
2750 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002751 final RedactionPermissionChecker redactionPermissionChecker =
2752 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2753 callingAttributionTag);
2754 final long redactions = retrieveRequiredRedactions(
2755 nc.getApplicableRedactions(), redactionPermissionChecker,
2756 includeLocationSensitiveInfo);
2757 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002758 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002759 // TODO : calling UID is redacted because apps should generally not know what UID is
2760 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002761 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002762 newNc.setOwnerUid(INVALID_UID);
2763 return newNc;
2764 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002765 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2766 if (nc.hasTransport(TRANSPORT_VPN)) {
2767 // Owner UIDs already checked above. No need to re-check.
2768 return newNc;
2769 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002770 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2771 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002772 // compatibility for older apps.
2773 if (!includeLocationSensitiveInfo
2774 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002775 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002776 newNc.setOwnerUid(INVALID_UID);
2777 return newNc;
2778 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002779 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002780 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002781 newNc.setOwnerUid(INVALID_UID);
2782 }
Qingxi Lib2748102020-01-08 12:51:49 -08002783 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002784 }
2785
lucaslinc582d502022-01-27 09:07:00 +08002786 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002787 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2788 LinkProperties lp, int callerPid, int callerUid) {
2789 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002790 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2791 // this would be expensive (one more permission check every time any LP callback is
2792 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2793 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2794 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002795
2796 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2797 final boolean needsSanitization =
2798 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2799 if (!needsSanitization) {
2800 return new LinkProperties(lp);
2801 }
2802
2803 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002804 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002805 }
2806
2807 final LinkProperties newLp = new LinkProperties(lp);
2808 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2809 // object gets parceled.
2810 newLp.setCaptivePortalApiUrl(null);
2811 newLp.setCaptivePortalData(null);
2812 return newLp;
2813 }
2814
Roshan Pius08c94fb2020-01-16 12:17:17 -08002815 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2816 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002817 // There is no need to track the effective UID of the request here. If the caller
2818 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002819 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002820 // Unprivileged apps can only pass in null or their own UID.
2821 if (nc.getUids() == null) {
2822 // If the caller passes in null, the callback will also match networks that do not
2823 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2824 // In this case, redact everything in the request immediately. This ensures that the
2825 // app is not able to get any redacted information by filing an unredacted request
2826 // and observing whether the request matches something.
2827 if (nc.getNetworkSpecifier() != null) {
2828 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2829 }
2830 } else {
2831 nc.setSingleUid(callerUid);
2832 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002833 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002834 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002835 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002836
2837 // Clear owner UID; this can never come from an app.
2838 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002839 }
2840
Chalard Jean38354d12018-03-20 19:13:57 +09002841 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002842 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002843 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2844 }
2845 }
2846
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002847 @Override
2848 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2849 enforceAccessPermission();
2850 final int callerUid = Binder.getCallingUid();
2851 final long token = Binder.clearCallingIdentity();
2852 try {
2853 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2854 } finally {
2855 Binder.restoreCallingIdentity(token);
2856 }
2857 }
2858
junyulaiebd15162021-03-03 12:09:05 +08002859 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002860 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002861 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002862 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002863 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002864
Serik Beketayev05130302021-01-15 16:47:25 -08002865 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002866 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002867 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2868 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002869 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002870 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002871 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002872 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2873 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002874 }
2875 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002876 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002877 }
2878
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002879 @Override
junyulaiebd15162021-03-03 12:09:05 +08002880 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002881 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002882 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002883 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002884
2885 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2886 for (Network network : getAllNetworks()) {
2887 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09002888 final boolean includeNetwork = (nai != null) && nai.isCreated();
2889 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002890 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2891 // NetworkCapabilities, which may contain UIDs of apps to which the
2892 // network applies. Should the UIDs be cleared so as not to leak or
2893 // interfere ?
2894 result.add(nai.getNetworkStateSnapshot());
2895 }
2896 }
2897 return result;
2898 }
2899
2900 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002901 public boolean isActiveNetworkMetered() {
2902 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002903
Qingxi Lib2748102020-01-08 12:51:49 -08002904 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002905 if (caps != null) {
2906 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2907 } else {
2908 // Always return the most conservative value
2909 return true;
2910 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002911 }
2912
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002913 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002914 * Ensures that the system cannot call a particular method.
2915 */
2916 private boolean disallowedBecauseSystemCaller() {
2917 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002918 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2919 // for devices launched with Q and above. However, existing devices upgrading to Q and
2920 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002921 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002922 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002923 log("This method exists only for app backwards compatibility"
2924 + " and must not be called by system services.");
2925 return true;
2926 }
2927 return false;
2928 }
2929
paulhub2c28682021-08-18 18:35:54 +08002930 private int getAppUid(final String app, final UserHandle user) {
2931 final PackageManager pm =
2932 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2933 final long token = Binder.clearCallingIdentity();
2934 try {
2935 return pm.getPackageUid(app, 0 /* flags */);
2936 } catch (PackageManager.NameNotFoundException e) {
2937 return -1;
2938 } finally {
2939 Binder.restoreCallingIdentity(token);
2940 }
2941 }
2942
2943 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2944 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2945 if (getAppUid(packageName, user) != callingUid) {
2946 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2947 }
2948 }
2949
Lorenzo Colitti23862912018-09-28 11:31:55 +09002950 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002951 * Ensure that a network route exists to deliver traffic to the specified
2952 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002953 * @param networkType the type of the network over which traffic to the
2954 * specified host is to be routed
2955 * @param hostAddress the IP address of the host to which the route is
2956 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002957 * @return {@code true} on success, {@code false} on failure
2958 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002959 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002960 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2961 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002962 if (disallowedBecauseSystemCaller()) {
2963 return false;
2964 }
paulhub2c28682021-08-18 18:35:54 +08002965 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002966 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002967 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002968 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002969 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002970
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002971 InetAddress addr;
2972 try {
2973 addr = InetAddress.getByAddress(hostAddress);
2974 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002975 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002976 return false;
2977 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002978
The Android Open Source Project28527d22009-03-03 19:31:44 -08002979 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002980 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002981 return false;
2982 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002983
2984 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2985 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002986 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002987 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2988 } else {
2989 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2990 }
2991 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002992 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002993
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002994 DetailedState netState;
2995 synchronized (nai) {
2996 netState = nai.networkInfo.getDetailedState();
2997 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002998
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002999 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003000 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003001 log("requestRouteToHostAddress on down network "
3002 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003003 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003004 }
3005 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003006 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003007
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003008 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003009 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003010 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003011 LinkProperties lp;
3012 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003013 synchronized (nai) {
3014 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003015 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003016 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003017 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003018 if (DBG) {
3019 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3020 }
Wink Saville32506bc2013-06-29 21:10:57 -07003021 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003022 } finally {
3023 Binder.restoreCallingIdentity(token);
3024 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003025 }
3026
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003027 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003028 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003029 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003030 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003031 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003032 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003033 if (bestRoute.getGateway().equals(addr)) {
3034 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003035 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003036 } else {
3037 // if we will connect to this through another route, add a direct route
3038 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003039 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003040 }
3041 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003042 if (DBG) log("Adding legacy route " + bestRoute +
3043 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003044
3045 final String dst = bestRoute.getDestinationLinkAddress().toString();
3046 final String nextHop = bestRoute.hasGateway()
3047 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003048 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003049 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3050 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003051 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003052 return false;
3053 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003054 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003055 }
3056
paulhu7c0a2e62021-01-08 00:51:49 +08003057 class DnsResolverUnsolicitedEventCallback extends
3058 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003059 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003060 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003061 try {
3062 mHandler.sendMessage(mHandler.obtainMessage(
3063 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003064 new PrivateDnsValidationUpdate(event.netId,
3065 InetAddresses.parseNumericAddress(event.ipAddress),
3066 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003067 } catch (IllegalArgumentException e) {
3068 loge("Error parsing ip address in validation event");
3069 }
3070 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003071
3072 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003073 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3074 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003075 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3076 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3077 // event callback for certain nai. e.g. cellular. Register here to pass to
3078 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003079 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003080 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3081 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003082 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003083 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003084 }
3085 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003086
3087 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003088 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3089 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3090 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003091 }
dalyk1720e542018-03-05 12:42:22 -05003092
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003093 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003094 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003095 return this.VERSION;
3096 }
3097
3098 @Override
3099 public String getInterfaceHash() {
3100 return this.HASH;
3101 }
paulhu7c0a2e62021-01-08 00:51:49 +08003102 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003103
3104 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003105 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3106 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003107
paulhu7c0a2e62021-01-08 00:51:49 +08003108 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003109 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003110 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003111 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003112 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003113 }
3114 }
3115
Sudheer Shanka9967d462021-03-18 19:09:25 +00003116 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003117 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003118 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003119 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3120 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003121 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003122 };
3123
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003124 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003125 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003126 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003127 }
3128
Mark Fasheh7c999d82023-05-04 20:23:11 +00003129 static final class UidFrozenStateChangedArgs {
3130 final int[] mUids;
3131 final int[] mFrozenStates;
3132
3133 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3134 mUids = uids;
3135 mFrozenStates = frozenStates;
3136 }
3137 }
3138
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003139 /**
3140 * Check if the cell network is idle.
3141 * @return true if the cell network state is idle
3142 * false if the cell network state is active or unknown
3143 */
3144 private boolean isCellNetworkIdle() {
3145 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3146 if (defaultNai == null
3147 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3148 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3149 // cell network is not the default network, cell network state is unknown.
3150 // TODO(b/279380356): Track cell network state when the cell is not the default network
3151 return false;
3152 }
3153
3154 return !mNetworkActivityTracker.isDefaultNetworkActive();
3155 }
3156
Mark Fasheh7c999d82023-05-04 20:23:11 +00003157 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003158 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003159
3160 for (int i = 0; i < uids.length; i++) {
3161 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003162 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003163 } else {
3164 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003165 }
3166 }
3167
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003168 if (ownerUids.isEmpty()) {
3169 return;
3170 }
3171
3172 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3173 // Delay closing sockets to avoid waking the cell modem up.
3174 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3175 // than waking cell modem up.
3176 mPendingFrozenUids.addAll(ownerUids);
3177 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003178 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003179 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003180 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003181 loge("Exception in socket destroy: " + e);
3182 }
3183 }
3184 }
3185
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003186 private void closePendingFrozenSockets() {
3187 ensureRunningOnConnectivityServiceThread();
3188
3189 try {
3190 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3191 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3192 loge("Failed to close pending frozen app sockets: " + e);
3193 }
3194 mPendingFrozenUids.clear();
3195 }
3196
3197 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3198 mNetworkActivityTracker.handleReportNetworkActivity(params);
3199
3200 if (mDelayDestroyFrozenSockets
3201 && params.isActive
3202 && params.label == TRANSPORT_CELLULAR
3203 && !mPendingFrozenUids.isEmpty()) {
3204 closePendingFrozenSockets();
3205 }
3206 }
3207
3208 /**
3209 * If the cellular network is no longer the default network, close pending frozen sockets.
3210 *
3211 * @param newNetwork new default network
3212 * @param oldNetwork old default network
3213 */
3214 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3215 NetworkAgentInfo oldNetwork) {
3216 final boolean isOldNetworkCellular = oldNetwork != null
3217 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3218 final boolean isNewNetworkCellular = newNetwork != null
3219 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3220
3221 if (isOldNetworkCellular
3222 && !isNewNetworkCellular
3223 && !mPendingFrozenUids.isEmpty()) {
3224 closePendingFrozenSockets();
3225 }
3226 }
3227
3228 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3229 pw.println("CloseFrozenAppSockets:");
3230 pw.increaseIndent();
3231 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3232 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3233 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3234 pw.decreaseIndent();
3235 }
3236
Mark Fasheh7c999d82023-05-04 20:23:11 +00003237 @VisibleForTesting
3238 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003239 @VisibleForTesting
3240 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3241 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003242
Paul Jensen83f5d572014-08-29 09:54:01 -04003243 private void enforceInternetPermission() {
3244 mContext.enforceCallingOrSelfPermission(
3245 android.Manifest.permission.INTERNET,
3246 "ConnectivityService");
3247 }
3248
The Android Open Source Project28527d22009-03-03 19:31:44 -08003249 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003250 mContext.enforceCallingOrSelfPermission(
3251 android.Manifest.permission.ACCESS_NETWORK_STATE,
3252 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003253 }
3254
lucaslinc582d502022-01-27 09:07:00 +08003255 private boolean checkAccessPermission(int pid, int uid) {
3256 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3257 == PERMISSION_GRANTED;
3258 }
3259
paulhua6ee2122021-02-22 15:40:43 +08003260 /**
3261 * Performs a strict and comprehensive check of whether a calling package is allowed to
3262 * change the state of network, as the condition differs for pre-M, M+, and
3263 * privileged/preinstalled apps. The caller is expected to have either the
3264 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3265 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3266 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3267 * permission and cannot be revoked. See http://b/23597341
3268 *
3269 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3270 * of this app will be updated to the current time.
3271 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003272 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003273 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3274 == PackageManager.PERMISSION_GRANTED) {
3275 return;
3276 }
3277
3278 if (callingPkg == null) {
3279 throw new SecurityException("Calling package name is null.");
3280 }
3281
3282 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3283 final int uid = mDeps.getCallingUid();
3284 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3285 callingPkg, callingAttributionTag, null /* message */);
3286
3287 if (mode == AppOpsManager.MODE_ALLOWED) {
3288 return;
3289 }
3290
3291 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3292 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3293 return;
3294 }
3295
3296 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3297 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3298 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003299 }
3300
Charles He9369e612017-05-15 17:07:18 +01003301 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003302 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003303 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003304 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003305 }
3306
Quang Luong98858d62023-02-11 00:25:24 +00003307 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003308 enforceAnyPermissionOf(mContext,
3309 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003310 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003311 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3312 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3313 }
3314
paulhu8e96a752019-08-12 16:25:11 +08003315 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003316 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003317 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003318 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003319 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003320 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003321 }
3322
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003323 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003324 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003325 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003326 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003327 android.Manifest.permission.NETWORK_SETTINGS,
3328 android.Manifest.permission.NETWORK_FACTORY,
3329 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3330 }
3331
3332 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003333 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003334 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003335 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003336 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3337 android.Manifest.permission.NETWORK_FACTORY,
3338 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3339 }
3340
lucaslin69e1aa92022-03-22 18:15:09 +08003341 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3342 return PERMISSION_GRANTED == mContext.checkPermission(
3343 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3344 || PERMISSION_GRANTED == mContext.checkPermission(
3345 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3346 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003347 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003348 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003349 }
3350
Chalard Jean9a396cc2018-02-21 18:43:54 +09003351 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003352 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003353 android.Manifest.permission.NETWORK_SETTINGS,
3354 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003355 }
3356
3357 private boolean checkSettingsPermission(int pid, int uid) {
3358 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003359 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3360 || PERMISSION_GRANTED == mContext.checkPermission(
3361 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003362 }
3363
paulhu8e96a752019-08-12 16:25:11 +08003364 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003365 enforceNetworkStackPermissionOr(mContext,
3366 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003367 }
3368
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003369 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003370 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003371 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003372 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003373 }
3374
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003375 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003376 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003377 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3378 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003379 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003380 }
3381
James Mattis8378aec2021-01-26 14:05:36 -08003382 private void enforceOemNetworkPreferencesPermission() {
3383 mContext.enforceCallingOrSelfPermission(
3384 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3385 "ConnectivityService");
3386 }
3387
James Mattisfa270db2021-05-31 17:11:10 -07003388 private void enforceManageTestNetworksPermission() {
3389 mContext.enforceCallingOrSelfPermission(
3390 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3391 "ConnectivityService");
3392 }
3393
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003394 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003395 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003396 android.Manifest.permission.NETWORK_STACK,
3397 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003398 }
3399
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003400 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003401 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003402 android.Manifest.permission.NETWORK_STACK,
3403 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3404 }
3405
paulhu1a407652019-03-22 16:35:06 +08003406 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003407 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003408 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003409 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3410 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003411 }
3412
Paul Hu8fc2a552022-05-04 18:44:42 +08003413 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3414 boolean checkUidsAllowedList) {
3415 if (PermissionUtils.checkAnyPermissionOf(mContext,
3416 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3417 return true;
3418 }
3419
3420 // fallback to ConnectivityInternalPermission
3421 // TODO: Remove this fallback check after all apps have declared
3422 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3423 if (PermissionUtils.checkAnyPermissionOf(mContext,
3424 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3425 return true;
3426 }
3427
3428 // Check whether uid is in allowed on restricted networks list.
3429 if (checkUidsAllowedList
3430 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3431 return true;
3432 }
3433 return false;
3434 }
3435
3436 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3437 final int callingUid = mDeps.getCallingUid();
3438 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3439 throw new SecurityException("ConnectivityService: user " + callingUid
3440 + " has no permission to access restricted network.");
3441 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003442 }
3443
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003444 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003445 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003446 }
3447
Roshan Pius98f59ec2021-02-23 08:47:39 -08003448 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3449 return PERMISSION_GRANTED == mContext.checkPermission(
3450 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3451 }
3452
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003453 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003454 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003455 }
3456
3457 private void sendInetConditionBroadcast(NetworkInfo info) {
3458 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3459 }
3460
Wink Saville4f0de1e2011-08-04 15:01:58 -07003461 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003462 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003463 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003464 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003465 if (info.isFailover()) {
3466 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3467 info.setFailover(false);
3468 }
3469 if (info.getReason() != null) {
3470 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3471 }
3472 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003473 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3474 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003475 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003476 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003477 return intent;
3478 }
3479
3480 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3481 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3482 }
3483
Michael Groover73f69482023-01-27 11:01:25 -06003484 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3485 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003486 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3487 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003488 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003489 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003490 if (!mSystemReady
3491 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003492 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003493 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003494 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003495 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003496 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003497 }
3498
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003499 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003500 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003501 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003502 final NetworkInfo ni = intent.getParcelableExtra(
3503 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003504 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3505 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003506 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003507 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003508 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003509 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003510 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003511 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003512 } finally {
3513 Binder.restoreCallingIdentity(ident);
3514 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003515 }
3516 }
3517
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003518 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3519 NetworkInfo info) {
3520 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003521 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003522
3523 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3524 try {
3525 // This allows us to discard older broadcasts still waiting to be delivered
3526 // which have the same namespace and key.
3527 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3528 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3529 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003530 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003531 } catch (UnsupportedApiLevelException e) {
3532 Log.wtf(TAG, "Using unsupported API" + e);
3533 }
3534 }
3535
3536 @VisibleForTesting
3537 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3538 final StringBuilder sb = new StringBuilder();
3539 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3540 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3541 sb.append(info.getExtraInfo());
3542 return sb.toString();
3543 }
3544
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003545 /**
Aaron Huang96011892020-06-27 07:18:23 +08003546 * Called by SystemServer through ConnectivityManager when the system is ready.
3547 */
3548 @Override
3549 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003550 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003551 throw new SecurityException("Calling Uid is not system uid.");
3552 }
3553 systemReadyInternal();
3554 }
3555
3556 /**
3557 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003558 */
3559 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003560 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003561 // Load flags after PackageManager is ready to query module version
3562 mFlags.loadFlags(mDeps, mContext);
3563
Aaron Huang9a57acf2020-12-08 10:03:29 +08003564 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3565 // listening network request which is sent by MultipathPolicyTracker won't be added
3566 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3567 // be called after PermissionMonitor#startMonitoring().
3568 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3569 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3570 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003571 final ConditionVariable startMonitoringDone = new ConditionVariable();
3572 mHandler.post(() -> {
3573 mPermissionMonitor.startMonitoring();
3574 startMonitoringDone.open();
3575 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003576 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003577 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003578
Hugo Benichie5220992017-04-26 14:53:28 +09003579 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003580 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003581 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003582 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003583 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003584 }
3585 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003586
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003587 // Create network requests for always-on networks.
3588 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003589
3590 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003591 // Note that updating can be skipped here if the list is empty only because no uid
3592 // rules are applied before system ready. Normally, the empty uid list means to clear
3593 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003594 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3595 updateMobileDataPreferredUids();
3596 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003597
3598 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003599 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003600 mBpfNetMaps.setPullAtomCallback(mContext);
3601 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003602 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3603 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003604 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3605 // have permission problem. While CV#block() is unbounded in time and can in principle block
3606 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3607 // could have blocked forever too.
3608 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003609 }
3610
The Android Open Source Project28527d22009-03-03 19:31:44 -08003611 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003612 * Start listening for default data network activity state changes.
3613 */
3614 @Override
3615 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003616 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003617 }
3618
3619 /**
3620 * Stop listening for default data network activity state changes.
3621 */
3622 @Override
3623 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003624 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003625 }
3626
3627 /**
3628 * Check whether the default network radio is currently active.
3629 */
3630 @Override
3631 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003632 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003633 }
3634
3635 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003636 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003637 * and set it on it's iface.
3638 */
Junyu Lai970963e2022-10-25 15:46:47 +08003639 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003640 final String iface = newLp.getInterfaceName();
3641 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003642 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003643 // Silently ignore unset MTU value.
3644 return;
3645 }
Hansen Kurli04252032022-12-07 11:21:49 +00003646 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3647 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3648 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003649 return;
3650 }
Hansen Kurli04252032022-12-07 11:21:49 +00003651 // Cannot set MTU without interface name
3652 if (TextUtils.isEmpty(iface)) {
3653 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003654 return;
3655 }
sy.yun4aa73922013-09-02 05:24:09 +09003656
Hansen Kurli04252032022-12-07 11:21:49 +00003657 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3658 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003659 return;
3660 }
3661
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003662 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003663 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003664 mNetd.interfaceSetMtu(iface, mtu);
3665 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003666 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003667 }
3668 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003669
Chenbo Feng15416292018-11-08 17:36:21 -08003670 @VisibleForTesting
3671 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003672
Junyu Lai970963e2022-10-25 15:46:47 +08003673 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003674 String[] values = null;
3675 if (tcpBufferSizes != null) {
3676 values = tcpBufferSizes.split(",");
3677 }
3678
3679 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003680 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003681 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3682 values = tcpBufferSizes.split(",");
3683 }
3684
3685 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3686
3687 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003688 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003689
Chenbo Feng15416292018-11-08 17:36:21 -08003690 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3691 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3692 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003693 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003694 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003695 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003696 }
3697 }
3698
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003699 @Override
3700 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003701 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003702 NETWORK_RESTORE_DELAY_PROP_NAME);
3703 if(restoreDefaultNetworkDelayStr != null &&
3704 restoreDefaultNetworkDelayStr.length() != 0) {
3705 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003706 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003707 } catch (NumberFormatException e) {
3708 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003709 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003710 // if the system property isn't set, use the value for the apn type
3711 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3712
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003713 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3714 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003715 }
3716 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003717 }
3718
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003719 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003720 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003721 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003722 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003723 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003724 // Start gathering diagnostic information.
3725 netDiags.add(new NetworkDiagnostics(
3726 nai.network,
3727 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003728 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003729 DIAG_TIME_MS));
3730 }
3731
3732 for (NetworkDiagnostics netDiag : netDiags) {
3733 pw.println();
3734 netDiag.waitForMeasurements();
3735 netDiag.dump(pw);
3736 }
3737 }
3738
The Android Open Source Project28527d22009-03-03 19:31:44 -08003739 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003740 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3741 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003742 if (!checkDumpPermission(mContext, TAG, writer)) return;
3743
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003744 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003745 }
3746
lucaslin99473f62020-12-10 15:10:54 +08003747 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3748 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3749 != PackageManager.PERMISSION_GRANTED) {
3750 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003751 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003752 + " due to missing android.permission.DUMP permission");
3753 return false;
3754 } else {
3755 return true;
3756 }
3757 }
3758
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003759 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003760 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003761
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003762 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003763 dumpNetworkDiagnostics(pw);
3764 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003765 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003766 dumpNetworks(pw);
3767 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003768 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003769 dumpNetworkRequests(pw);
3770 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003771 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3772 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3773 dumpTrafficController(pw, fd, verbose);
3774 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003775 }
Erik Kline9647f382015-06-05 17:47:34 +09003776
Junyu Lai0da479b2022-04-20 15:06:29 +08003777 pw.println("NetworkProviders for:");
3778 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003779 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003780 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003781 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003782 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003783 pw.println();
3784
Chalard Jean5b409c72021-02-04 13:12:59 +09003785 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003786 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003787 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003788 pw.println("none");
3789 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003790 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003791 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003792 pw.println();
3793
James Mattis8b298a02021-06-01 22:34:04 -07003794 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003795 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003796 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003797 pw.decreaseIndent();
3798 pw.println();
3799
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003800 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003801 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003802 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003803 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003804 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003805
junyulaif2c67e42018-08-07 19:50:45 +08003806 pw.println("Status for known UIDs:");
3807 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003808 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003809 for (int i = 0; i < size; i++) {
3810 // Don't crash if the array is modified while dumping in bugreports.
3811 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003812 final int uid = mUidBlockedReasons.keyAt(i);
3813 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3814 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003815 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003816 } catch (ArrayIndexOutOfBoundsException e) {
3817 pw.println(" ArrayIndexOutOfBoundsException");
3818 } catch (ConcurrentModificationException e) {
3819 pw.println(" ConcurrentModificationException");
3820 }
3821 }
3822 pw.println();
3823 pw.decreaseIndent();
3824
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003825 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003826 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003827 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003828 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003829 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003830
Junyu Lai0da479b2022-04-20 15:06:29 +08003831 pw.println("Network Offers:");
3832 pw.increaseIndent();
3833 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3834 pw.println(offerInfo.offer);
3835 }
3836 pw.decreaseIndent();
3837 pw.println();
3838
Robert Greenwalt94e22142014-07-30 16:31:24 -07003839 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003840
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003841 pw.println();
markchien5e866652019-09-30 14:40:57 +08003842 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003843
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003844 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003845 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003846
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003847 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003848 dumpCloseFrozenAppSockets(pw);
3849
3850 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003851
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003852 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003853 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003854 pw.println("mNetworkRequestInfoLogs (most recent first):");
3855 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003856 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003857 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003858
3859 pw.println();
3860 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3861 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003862 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003863 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003864
3865 pw.println();
3866 pw.println("NetTransition WakeLock activity (most recent first):");
3867 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003868 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3869 pw.println("total releases: " + mTotalWakelockReleases);
3870 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3871 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3872 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3873 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3874 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3875 }
James Mattiscb1e0362021-04-06 17:07:42 -07003876 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003877
3878 pw.println();
3879 pw.println("bandwidth update requests (by uid):");
3880 pw.increaseIndent();
3881 synchronized (mBandwidthRequests) {
3882 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3883 pw.println("[" + mBandwidthRequests.keyAt(i)
3884 + "]: " + mBandwidthRequests.valueAt(i));
3885 }
3886 }
3887 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003888 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003889
James Mattiscb1e0362021-04-06 17:07:42 -07003890 pw.println();
3891 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3892 pw.increaseIndent();
3893 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003894 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003895 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003896
3897 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003898
3899 pw.println();
3900 pw.println("Permission Monitor:");
3901 pw.increaseIndent();
3902 mPermissionMonitor.dump(pw);
3903 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003904
3905 pw.println();
3906 pw.println("Legacy network activity:");
3907 pw.increaseIndent();
3908 mNetworkActivityTracker.dump(pw);
3909 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003910 }
3911
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003912 private void dumpNetworks(IndentingPrintWriter pw) {
3913 for (NetworkAgentInfo nai : networksSortedById()) {
3914 pw.println(nai.toString());
3915 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003916 pw.println("Nat464Xlat:");
3917 pw.increaseIndent();
3918 nai.dumpNat464Xlat(pw);
3919 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003920 pw.println(String.format(
3921 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3922 nai.numForegroundNetworkRequests(),
3923 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3924 nai.numBackgroundNetworkRequests(),
3925 nai.numNetworkRequests()));
3926 pw.increaseIndent();
3927 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3928 pw.println(nai.requestAt(i).toString());
3929 }
3930 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003931 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003932 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003933 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003934 pw.decreaseIndent();
3935 pw.decreaseIndent();
3936 }
3937 }
3938
James Mattis8b298a02021-06-01 22:34:04 -07003939 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3940 if (!mProfileNetworkPreferences.isEmpty()) {
3941 pw.println("Profile preferences:");
3942 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09003943 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07003944 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003945 }
James Mattis8b298a02021-06-01 22:34:04 -07003946 if (!mOemNetworkPreferences.isEmpty()) {
3947 pw.println("OEM preferences:");
3948 pw.increaseIndent();
3949 pw.println(mOemNetworkPreferences);
3950 pw.decreaseIndent();
3951 }
3952 if (!mMobileDataPreferredUids.isEmpty()) {
3953 pw.println("Mobile data preferred UIDs:");
3954 pw.increaseIndent();
3955 pw.println(mMobileDataPreferredUids);
3956 pw.decreaseIndent();
3957 }
James Mattis45d81842021-01-10 14:24:24 -08003958
James Mattis8b298a02021-06-01 22:34:04 -07003959 pw.println("Default requests:");
3960 pw.increaseIndent();
3961 dumpPerAppDefaultRequests(pw);
3962 pw.decreaseIndent();
3963 }
3964
3965 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003966 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3967 if (mDefaultRequest == defaultRequest) {
3968 continue;
3969 }
3970
James Mattis8b298a02021-06-01 22:34:04 -07003971 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3972 final String networkOutput;
3973 if (null == satisfier) {
3974 networkOutput = "null";
3975 } else if (mNoServiceNetwork.equals(satisfier)) {
3976 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003977 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003978 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003979 }
James Mattis8b298a02021-06-01 22:34:04 -07003980 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3981 ? "" : " asUid: " + defaultRequest.mAsUid;
3982 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3983 + defaultRequest.mPid + asUidString + "]";
3984 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3985 + " Preference order: " + defaultRequest.mPreferenceOrder
3986 + " Tracked UIDs: " + defaultRequest.getUids();
3987 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003988 }
3989 }
3990
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003991 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003992 NetworkRequestInfo[] infos = null;
3993 while (infos == null) {
3994 try {
3995 infos = requestsSortedById();
3996 } catch (ConcurrentModificationException e) {
3997 // mNetworkRequests should only be accessed from handler thread, except dump().
3998 // As dump() is never called in normal usage, it would be needlessly expensive
3999 // to lock the collection only for its benefit. Instead, retry getting the
4000 // requests if ConcurrentModificationException is thrown during dump().
4001 }
4002 }
4003 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004004 pw.println(nri.toString());
4005 }
4006 }
4007
Ken Chene6d511f2022-01-25 11:10:42 +08004008 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4009 boolean verbose) {
4010 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004011 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004012 } catch (ServiceSpecificException e) {
4013 pw.println(e.getMessage());
4014 } catch (IOException e) {
4015 loge("Dump BPF maps failed, " + e);
4016 }
4017 }
4018
Chalard Jean524f0b12021-10-25 21:11:56 +09004019 private void dumpAllRequestInfoLogsToLogcat() {
4020 try (PrintWriter logPw = new PrintWriter(new Writer() {
4021 @Override
4022 public void write(final char[] cbuf, final int off, final int len) {
4023 // This method is called with 0-length and 1-length arrays for empty strings
4024 // or strings containing only the DEL character.
4025 if (len <= 1) return;
4026 Log.e(TAG, new String(cbuf, off, len));
4027 }
4028 @Override public void flush() {}
4029 @Override public void close() {}
4030 })) {
4031 mNetworkRequestInfoLogs.dump(logPw);
4032 }
4033 }
4034
Hugo Benichia480ba52018-09-03 08:19:02 +09004035 /**
4036 * Return an array of all current NetworkAgentInfos sorted by network id.
4037 */
4038 private NetworkAgentInfo[] networksSortedById() {
4039 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004040 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004041 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004042 return networks;
4043 }
4044
4045 /**
4046 * Return an array of all current NetworkRequest sorted by request id.
4047 */
James Mattis258ea3c2020-11-15 15:04:40 -08004048 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004049 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004050 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004051 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004052 // Sort the array based off the NRI containing the min requestId in its requests.
4053 Arrays.sort(requests,
4054 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4055 Comparator.comparingInt(req -> req.requestId)).requestId
4056 )
4057 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004058 return requests;
4059 }
4060
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004061 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004062 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004063 if (officialNai != null && officialNai.equals(nai)) return true;
4064 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004065 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004066 " - " + nai);
4067 }
4068 return false;
4069 }
4070
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004071 private boolean isDisconnectRequest(Message msg) {
4072 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4073 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4074 return info.getState() == NetworkInfo.State.DISCONNECTED;
4075 }
4076
Robert Greenwalt2034b912009-08-12 16:08:25 -07004077 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004078 private class NetworkStateTrackerHandler extends Handler {
4079 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004080 super(looper);
4081 }
4082
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004083 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004084 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4085 final NetworkAgentInfo nai = arg.first;
4086 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004087 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004088 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004089 }
4090 return;
4091 }
4092
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004093 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004094 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004095 return;
4096 }
4097
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004098 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004099 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09004100 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
4101 final NetworkCapabilities sanitized =
4102 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004103 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004104 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004105 break;
4106 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004107 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004108 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004109 processLinkPropertiesFromAgent(nai, newLp);
4110 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004111 break;
4112 }
4113 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004114 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004115 updateNetworkInfo(nai, info);
4116 break;
4117 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004118 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004119 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004120 break;
4121 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004122 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004123 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004124 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004125 // Note that if the NAI had been connected, this would affect the
4126 // score, and therefore would require re-mixing the score and performing
4127 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004128 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004129 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4130 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004131 // Mark the network as temporarily accepting partial connectivity so that it
4132 // will be validated (and possibly become default) even if it only provides
4133 // partial internet access. Note that if user connects to partial connectivity
4134 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4135 // out of wifi coverage) and if the same wifi is available again, the device
4136 // will auto connect to this wifi even though the wifi has "no internet".
4137 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004138 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004139 break;
4140 }
junyulai011b1f12019-01-03 18:50:15 +08004141 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004142 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004143 break;
4144 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004145 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004146 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004147 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004148
4149 if (isLegacyLockdownNai(nai)
4150 && (underlying == null || underlying.size() != 1)) {
4151 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4152 + " must have exactly one underlying network: " + underlying);
4153 }
4154
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004155 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4156 nai.declaredUnderlyingNetworks = (underlying != null)
4157 ? underlying.toArray(new Network[0]) : null;
4158
4159 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4160 if (DBG) {
4161 log(nai.toShortString() + " changed underlying networks to "
4162 + Arrays.toString(nai.declaredUnderlyingNetworks));
4163 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004164 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004165 notifyIfacesChangedForNetworkStats();
4166 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004167 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004168 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004169 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4170 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4171 nai.teardownDelayMs = msg.arg1;
4172 } else {
4173 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4174 }
Chalard Jean550b5212021-03-05 23:07:53 +09004175 break;
4176 }
4177 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4178 nai.setLingerDuration((int) arg.second);
4179 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004180 }
Tyler Wear72388212021-09-09 14:49:02 -07004181 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4182 DscpPolicy policy = (DscpPolicy) arg.second;
4183 if (mDscpPolicyTracker != null) {
4184 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4185 }
4186 break;
4187 }
4188 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4189 if (mDscpPolicyTracker != null) {
4190 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4191 }
4192 break;
4193 }
4194 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4195 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004196 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004197 }
4198 break;
4199 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004200 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004201 if (!nai.everConnected()) {
4202 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4203 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004204 teardownUnneededNetwork(nai);
4205 break;
4206 }
4207
4208 if (nai.isDestroyed()) {
4209 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4210 + ", ignoring");
4211 break;
4212 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004213
4214 final int timeoutMs = (int) arg.second;
4215 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4216 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4217 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4218 }
4219
4220 // Marking a network awaiting replacement is used to ensure that any requests
4221 // satisfied by the network do not switch to another network until a
4222 // replacement is available or the wait for a replacement times out.
4223 // If the network is inactive (i.e., nascent or lingering), then there are no
4224 // such requests, and there is no point keeping it. Just tear it down.
4225 // Note that setLingerDuration(0) cannot be used to do this because the network
4226 // could be nascent.
4227 nai.clearInactivityState();
4228 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4229 Log.d(TAG, nai.toShortString()
4230 + " marked awaiting replacement is unneeded, tearing down instead");
4231 teardownUnneededNetwork(nai);
4232 break;
4233 }
4234
4235 Log.d(TAG, "Marking " + nai.toShortString()
4236 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4237 destroyNativeNetwork(nai);
4238
4239 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4240 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4241 // consider the fact that the network could already have disconnected or been
4242 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4243 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4244 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4245 mKeepaliveTracker.handleStopAllKeepalives(nai,
4246 SocketKeepalive.ERROR_INVALID_NETWORK);
4247
4248 nai.updateScoreForNetworkAgentUpdate();
4249 // This rematch is almost certainly not going to result in any changes, because
4250 // the destroyed flag is only just above the "current satisfier wins"
4251 // tie-breaker. But technically anything that affects scoring should rematch.
4252 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004253 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004254 break;
4255 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004256 }
4257 }
4258
4259 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004260 final int netId = msg.arg2;
4261 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004262 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004263 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004264 switch (msg.what) {
4265 default:
4266 return false;
lucasline117e2e2019-10-22 18:27:33 +08004267 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004268 if (nai == null) {
4269 break;
4270 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004271 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4272 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004273 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004274 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004275 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004276 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004277 if (probePrivateDnsCompleted) {
4278 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4279 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004280 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004281 }
4282 // Only show the notification when the private DNS is broken and the
4283 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004284 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004285 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4286 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004287 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004288 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4289 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4290 // private DNS is broken, it means this network is being reevaluated.
4291 // Either probing private DNS is not necessary any more or it hasn't been
4292 // done yet. In either case, the networkCapabilities should be updated to
4293 // reflect the new status.
4294 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004295 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004296 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004297 }
4298 break;
4299 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004300 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004301 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4302
Erik Kline31b4a9e2018-01-11 21:07:29 +09004303 if (nai == null) break;
4304
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004305 handleNetworkTested(nai, results.mTestResult,
4306 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004307 break;
4308 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004309 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004310 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004311 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004312 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004313 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004314 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004315 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4316 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004317 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004318 if (nai == null) {
4319 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4320 break;
4321 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004322 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004323 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004324 (PendingIntent) msg.obj,
4325 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004326 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004327 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004328 break;
4329 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004330 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004331 if (nai == null) break;
4332
Erik Kline9a62f012018-03-21 07:18:33 -07004333 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004334 break;
4335 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004336 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004337 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004338 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004339 break;
4340 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004341 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004342 return true;
4343 }
4344
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004345 private void handleNetworkTested(
4346 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004347 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4348 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004349 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004350
4351 // If there is any kind of working networking, then the NAI has been evaluated
4352 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4353 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004354 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004355 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004356 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4357 // any callback that receives onAvailable for that rematch receives an extra caps
4358 // callback. To prevent that, update the score in the agent so the updates below won't
4359 // see an update to both caps and score at the same time.
4360 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004361 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4362
he_won.hwang881307a2022-03-15 21:23:52 +09004363 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4364 // Assume the validation failure is due to a temporary failure after roaming
4365 // and ignore it. NetworkMonitor will continue to retry validation. If it
4366 // continues to fail after the block timeout expires, the network will be
4367 // marked unvalidated. If it succeeds, then validation state will not change.
4368 return;
4369 }
4370
Chalard Jean254bd162022-08-25 13:04:51 +09004371 final boolean wasValidated = nai.isValidated();
4372 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004373 final boolean wasPortal = nai.captivePortalDetected();
4374 nai.setPartialConnectivity(partial);
4375 nai.setCaptivePortalDetected(portal);
4376 nai.updateScoreForNetworkAgentUpdate();
4377 final boolean partialConnectivityChanged = (wasPartial != partial);
4378 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004379
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004380 if (DBG) {
4381 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4382 ? " with redirect to " + redirectUrl
4383 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004384 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004385 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004386 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004387 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004388 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004389 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004390 if (valid) {
4391 handleFreshlyValidatedNetwork(nai);
4392 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4393 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004394 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004395 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004396 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004397 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004398 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004399 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004400 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004401 NotificationType.PRIVATE_DNS_BROKEN);
4402 // If network becomes valid, the hasShownBroken should be reset for
4403 // that network so that the notification will be fired when the private
4404 // DNS is broken again.
4405 nai.networkAgentConfig.hasShownBroken = false;
4406 }
4407 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004408 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004409 } else if (portalChanged) {
4410 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004411 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004412 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4413 nai.onPreventAutomaticReconnect();
4414 teardownUnneededNetwork(nai);
4415 return;
4416 } else {
4417 updateCapabilitiesForNetwork(nai);
4418 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004419 } else if (becameEvaluated) {
4420 // If valid or partial connectivity changed, updateCapabilities* has
4421 // done the rematch.
4422 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004423 }
4424 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004425
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004426 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004427 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004428 nai.onValidationStatusChanged(
4429 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4430 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004431
4432 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004433 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004434 // immediately. Re-notify partial connectivity silently if no internet
4435 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004436 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004437 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004438 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4439 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004440 }
4441
Chalard Jean254bd162022-08-25 13:04:51 +09004442 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004443 handleNetworkUnvalidated(nai);
4444 }
4445 }
4446
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004447 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4448 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4449 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4450 // Do not avoid captive portal when network is wear proxy.
4451 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4452 }
4453
Calvin Ondada1452016-10-11 15:10:46 -07004454 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004455 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4456 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004457 }
4458
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004459 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4460 switch (msg.what) {
4461 default:
4462 return false;
4463 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4464 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4465 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4466 handleLingerComplete(nai);
4467 }
4468 break;
4469 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004470 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4471 handleNetworkAgentRegistered(msg);
4472 break;
4473 }
4474 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4475 handleNetworkAgentDisconnected(msg);
4476 break;
4477 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004478 }
4479 return true;
4480 }
4481
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004482 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004483 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004484 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004485 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004486 maybeHandleNetworkAgentMessage(msg);
4487 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004488 }
4489 }
4490
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004491 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004492 private final int mNetId;
4493 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004494
4495 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004496 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004497 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004498 }
4499
4500 @Override
4501 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4502 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004503 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004504 }
4505
4506 @Override
4507 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004508 // Legacy version of notifyNetworkTestedWithExtras.
4509 // Would only be called if the system has a NetworkStack module older than the
4510 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004511 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004512 }
4513
4514 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004515 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004516 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4517 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004518 final Message msg = mTrackerHandler.obtainMessage(
4519 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004520 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004521 new NetworkTestedResults(
4522 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004523 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004524
4525 // Invoke ConnectivityReport generation for this Network test event.
4526 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4527 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004528
Cody Kestingf1120be2020-08-03 18:01:40 -07004529 // NetworkMonitor reports the network validation result as a bitmask while
4530 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4531 // logical value for ConnectivityDiagnostics.
4532 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4533 p.result);
4534
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004535 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004536 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004537 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4538 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4539
Aaron Huang959d3642021-01-21 15:47:41 +08004540 ConnectivityReportEvent reportEvent =
4541 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4542 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004543 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004544 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004545 }
4546
4547 @Override
4548 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4549 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4550 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004551 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004552 }
4553
4554 @Override
lucasline117e2e2019-10-22 18:27:33 +08004555 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4556 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4557 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004558 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004559 }
4560
4561 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004562 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4563 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4564 EVENT_CAPPORT_DATA_CHANGED,
4565 0, mNetId, data));
4566 }
4567
4568 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004569 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004570 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004571 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004572
4573 final PendingIntent pendingIntent;
4574 // Only the system server can register notifications with package "android"
4575 final long token = Binder.clearCallingIdentity();
4576 try {
paulhu7746e4e2020-06-09 19:07:03 +08004577 pendingIntent = PendingIntent.getBroadcast(
4578 mContext,
4579 0 /* requestCode */,
4580 intent,
4581 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004582 } finally {
4583 Binder.restoreCallingIdentity(token);
4584 }
4585 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4586 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004587 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004588 }
4589
4590 @Override
4591 public void hideProvisioningNotification() {
4592 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004593 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004594 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004595
4596 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004597 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004598 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004599 }
4600
4601 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004602 public int getInterfaceVersion() {
4603 return this.VERSION;
4604 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004605
4606 @Override
4607 public String getInterfaceHash() {
4608 return this.HASH;
4609 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004610 }
4611
Cody Kestingf1120be2020-08-03 18:01:40 -07004612 /**
4613 * Converts the given NetworkMonitor-specific validation result bitmask to a
4614 * ConnectivityDiagnostics-specific validation result int.
4615 */
4616 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4617 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4618 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4619 }
4620 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4621 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4622 }
4623 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4624 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4625 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4626 }
4627
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004628 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004629 log("Data stall detected with methods: " + p.detectionMethod);
4630
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004631 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004632 int detectionMethod = 0;
4633 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4634 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4635 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4636 }
4637 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4638 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4639 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4640 p.tcpMetricsCollectionPeriodMillis);
4641 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004642 }
4643
Cody Kestingf53a0752020-04-15 12:33:28 -07004644 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004645 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004646 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004647
4648 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4649 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4650 // the cost of going through two handlers.
4651 mConnectivityDiagnosticsHandler.sendMessage(msg);
4652 }
4653
Cody Kestingb37958e2020-05-15 10:36:01 -07004654 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4655 return (p.detectionMethod & detectionMethod) != 0;
4656 }
4657
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004658 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4659 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004660 }
4661
Erik Klinea73af002018-06-26 18:53:43 +09004662 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4663 if (nai == null) return;
4664 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4665 // in order to restart a validation pass from within netd.
4666 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4667 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004668 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004669 }
4670 }
4671
Erik Kline31b4a9e2018-01-11 21:07:29 +09004672 private void handlePrivateDnsSettingsChanged() {
4673 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4674
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004675 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004676 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004677 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004678 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4679 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004680 }
4681 }
4682
Erik Kline9a62f012018-03-21 07:18:33 -07004683 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4684 // Private DNS only ever applies to networks that might provide
4685 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004686 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004687
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004688 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004689 // schedule DNS resolutions. If a DNS resolution is required the
4690 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004691 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004692
4693 // With Private DNS bypass support, we can proceed to update the
4694 // Private DNS config immediately, even if we're in strict mode
4695 // and have not yet resolved the provider name into a set of IPs.
4696 updatePrivateDns(nai, cfg);
4697 }
4698
4699 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4700 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004701 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004702 }
4703
dalyk1720e542018-03-05 12:42:22 -05004704 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4705 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4706 if (nai == null) {
4707 return;
4708 }
4709 mDnsManager.updatePrivateDnsValidation(update);
4710 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4711 }
4712
paulhu7c0a2e62021-01-08 00:51:49 +08004713 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004714 int prefixLength) {
4715 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4716 if (nai == null) return;
4717
paulhu7c0a2e62021-01-08 00:51:49 +08004718 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4719 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004720
4721 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004722 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004723 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004724 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004725 prefixLength);
4726 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004727 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004728 return;
4729 }
4730 }
4731
Lorenzo Colittid523d142020-04-01 20:16:30 +09004732 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004733 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4734 }
4735
Hai Shalome58bdc62021-01-11 18:45:34 -08004736 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004737 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004738 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004739 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4740 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4741 }
4742
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004743 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004744 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004745 * @param nai the agent info to update
4746 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004747 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004748 */
junyulai2b6f0c22021-02-03 20:15:30 +08004749 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4750 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4751 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004752 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004753 // one lingered request, set inactive.
4754 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004755 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004756 if (DBG) log("Unsetting inactive " + nai.toShortString());
4757 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004758 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004759 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004760 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004761 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4762 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004763 }
junyulai2b6f0c22021-02-03 20:15:30 +08004764 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004765 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004766 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004767 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004768 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004769 }
4770
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004771 private void handleNetworkAgentRegistered(Message msg) {
4772 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4773 if (!mNetworkAgentInfos.contains(nai)) {
4774 return;
4775 }
4776
4777 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4778 if (VDBG) log("NetworkAgent registered");
4779 } else {
4780 loge("Error connecting NetworkAgent");
4781 mNetworkAgentInfos.remove(nai);
4782 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004783 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004784 synchronized (mNetworkForNetId) {
4785 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004786 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004787 mNetIdManager.releaseNetId(nai.network.getNetId());
4788 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004789 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004790 }
4791 }
4792 }
Paul Jensend5f53392014-11-25 15:26:53 -05004793
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004794 @VisibleForTesting
4795 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09004796 // The feature of creating the networks immediately was slated for U, but race conditions
4797 // detected late required this was flagged off.
4798 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
4799 // in NetworkAgentTest.
4800 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004801 }
4802
4803 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4804 @NonNull NetworkInfo.State state) {
4805 if (nai.isCreated()) return false;
4806 if (state == NetworkInfo.State.CONNECTED) return true;
4807 if (state != NetworkInfo.State.CONNECTING) {
4808 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09004809 if (shouldCreateNetworksImmediately()) {
4810 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4811 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004812 return false;
4813 }
4814 return nai.isVPN() || shouldCreateNetworksImmediately();
4815 }
4816
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004817 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004818 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004819 }
4820
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004821 @VisibleForTesting
4822 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004823 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09004824 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004825
4826 // If the network never roamed, return false. The check below is not sufficient if time
4827 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4828 if (nai.lastRoamTime == 0) return false;
4829
he_won.hwang881307a2022-03-15 21:23:52 +09004830 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4831 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004832 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004833 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004834 final long currentTimeMs = SystemClock.elapsedRealtime();
4835 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004836 if (timeSinceLastRoam <= blockTimeOut) {
4837 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4838 return true;
4839 }
4840 }
4841 return false;
4842 }
4843
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004844 private void handleNetworkAgentDisconnected(Message msg) {
4845 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004846 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004847 }
4848
Chalard Jeand9fffc32018-05-11 20:19:20 +09004849 // Destroys a network, remove references to it from the internal state managed by
4850 // ConnectivityService, free its interfaces and clean up.
4851 // Must be called on the Handler thread.
4852 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004853 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004854
4855 if (!mNetworkAgentInfos.contains(nai)) return;
4856
Chalard Jeand9fffc32018-05-11 20:19:20 +09004857 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004858 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004859 }
lucaslinb25c9a62019-02-12 15:30:13 +08004860 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004861 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004862 // A network agent has disconnected.
4863 // TODO - if we move the logic to the network agent (have them disconnect
4864 // because they lost all their requests or because their score isn't good)
4865 // then they would disconnect organically, report their new state and then
4866 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08004867 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004868 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4869 null, null);
4870 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004871 final boolean wasDefault = isDefaultNetwork(nai);
4872 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004873 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004874 }
4875 notifyIfacesChangedForNetworkStats();
4876 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4877 // by other networks that are already connected. Perhaps that can be done by
4878 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4879 // of rematchAllNetworksAndRequests
4880 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004881 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004882
4883 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004884 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4885 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08004886 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004887 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004888 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004889 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004890 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004891 synchronized (mNetworkForNetId) {
4892 // Remove the NetworkAgent, but don't mark the netId as
4893 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004894 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004895 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004896 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08004897 // Update allowed network lists in netd. This should be called after removing nai
4898 // from mNetworkAgentInfos.
4899 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004900 // Remove all previously satisfied requests.
4901 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004902 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004903 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004904 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004905 if (currentNetwork != null
4906 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004907 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004908 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4909 // rematch not to keep disconnected agents instead of setting it here ; this
4910 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004911 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004912 for (final NetworkOfferInfo noi : mNetworkOffers) {
4913 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004914 }
James Mattise3ef1912020-12-20 11:09:58 -08004915
Chalard Jean5b409c72021-02-04 13:12:59 +09004916 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004917 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004918 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004919 // network, because while incorrect this is the closest to the old (also
4920 // incorrect) behavior.
4921 mNetworkActivityTracker.updateDataActivityTracking(
4922 null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004923 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004924 ensureNetworkTransitionWakelock(nai.toShortString());
4925 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004926 }
4927 }
junyulai2b6f0c22021-02-03 20:15:30 +08004928 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004929 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004930 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004931 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004932 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004933 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004934 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004935
Aaron Huang9fe47be2021-06-08 13:11:45 +08004936 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
4937 // The obvious place to do this would be in makeDefault(), however makeDefault() is
4938 // not called by the rematch in this case. This is because the code above unset
4939 // this network from the default request's satisfier, and that is what the rematch
4940 // is using as its source data to know what the old satisfier was. So as far as the
4941 // rematch above is concerned, the old default network was null.
4942 // Therefore if there is no new default, the default network was null and is still
4943 // null, thus there was no change so makeDefault() is not called. So if the old
4944 // network had a proxy and there is no new default, the proxy tracker should be told
4945 // that there is no longer a default proxy.
4946 // Strictly speaking this is not essential because having a proxy setting when
4947 // there is no network is harmless, but it's still counter-intuitive so reset to null.
4948 mProxyTracker.setDefaultProxy(null);
4949 }
4950
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004951 // Immediate teardown.
4952 if (nai.teardownDelayMs == 0) {
4953 destroyNetwork(nai);
4954 return;
4955 }
4956
4957 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004958 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304959 try {
4960 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4961 } catch (RemoteException e) {
4962 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4963 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004964 }
4965 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4966 }
4967
4968 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004969 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004970 // Tell netd to clean up the configuration for this network
4971 // (routing rules, DNS, etc).
4972 // This may be slow as it requires a lot of netd shelling out to ip and
4973 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004974 // after we've rematched networks with requests (which might change the default
4975 // network or service a new request from an app), so network traffic isn't interrupted
4976 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004977 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004978 }
Chalard Jeandf29a852023-05-29 17:02:43 +09004979 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004980 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4981 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4982 // false if the network was never created.
4983 // TODO: delete when S is no longer supported.
4984 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004985 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004986 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004987 }
4988
Ken Chen6df7a902021-04-09 15:08:42 +08004989 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004990 try {
4991 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004992 final NativeNetworkConfig config;
4993 if (nai.isVPN()) {
4994 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004995 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004996 return false;
4997 }
4998 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4999 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005000 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005001 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005002 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08005003 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005004 getNetworkPermission(nai.networkCapabilities),
5005 false /* secure */,
5006 VpnManager.TYPE_VPN_NONE,
5007 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005008 }
Ken Chen6df7a902021-04-09 15:08:42 +08005009 mNetd.networkCreate(config);
5010 mDnsResolver.createNetworkCache(nai.network.getNetId());
5011 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
5012 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08005013 return true;
5014 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005015 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005016 return false;
5017 }
5018 }
5019
Ken Chen6df7a902021-04-09 15:08:42 +08005020 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005021 if (mDscpPolicyTracker != null) {
5022 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5023 }
Luke Huangfdd11f82019-04-09 18:41:49 +08005024 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005025 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005026 } catch (RemoteException | ServiceSpecificException e) {
5027 loge("Exception destroying network(networkDestroy): " + e);
5028 }
5029 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005030 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005031 } catch (RemoteException | ServiceSpecificException e) {
5032 loge("Exception destroying network: " + e);
5033 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005034 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5035 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5036 // gets created, could add data to DnsManager data structures that will never get deleted.
5037 mDnsManager.removeNetwork(nai.network);
5038
5039 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005040 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005041 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5042 }
5043
Chalard Jean254bd162022-08-25 13:04:51 +09005044 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005045 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005046 }
5047
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005048 // If this method proves to be too slow then we can maintain a separate
5049 // pendingIntent => NetworkRequestInfo map.
5050 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5051 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005052 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5053 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5054 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005055 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005056 return entry.getValue();
5057 }
5058 }
5059 return null;
5060 }
5061
Chalard Jean524f0b12021-10-25 21:11:56 +09005062 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005063 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005064 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5065 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5066 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5067 // bug is fixed.
5068 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005069 throw new IllegalStateException("This NRI is already registered. New : " + nri
5070 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005071 }
5072 }
5073 }
5074 }
5075
Chalard Jeanac9ace02022-01-26 16:54:05 +09005076 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5077 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005078 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09005079 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
5080 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005081 }
5082 return false;
5083 }
5084
James Mattisf7027322020-12-13 16:28:14 -08005085 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005086 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005087 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5088 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5089 final NetworkRequestInfo existingRequest =
5090 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005091 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005092 if (DBG) {
5093 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5094 + nri.mRequests.get(0) + " because their intents matched.");
5095 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005096 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005097 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005098 }
Erik Kline05f2b402015-04-30 12:58:40 +09005099 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005100 }
5101
James Mattisf7027322020-12-13 16:28:14 -08005102 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005103 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005104 }
5105
James Mattis3ce3d3c2021-02-09 18:18:28 -08005106 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005107 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005108 for (final NetworkRequestInfo nri : nris) {
5109 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005110 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005111 for (final NetworkRequest req : nri.mRequests) {
5112 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005113 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005114 if (req.isListen()) {
5115 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5116 if (req.networkCapabilities.hasSignalStrength()
5117 && network.satisfiesImmutableCapabilitiesOf(req)) {
5118 updateSignalStrengthThresholds(network, "REGISTER", req);
5119 }
James Mattisf7027322020-12-13 16:28:14 -08005120 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005121 }
5122 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005123
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005124 // If this NRI has a satisfier already, it is replacing an older request that
5125 // has been removed. Track it.
5126 final NetworkRequest activeRequest = nri.getActiveRequest();
5127 if (null != activeRequest) {
5128 // If there is an active request, then for sure there is a satisfier.
5129 nri.getSatisfier().addRequest(activeRequest);
5130 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005131 }
James Mattisf7027322020-12-13 16:28:14 -08005132
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005133 if (mFlags.noRematchAllRequestsOnRegister()) {
5134 rematchNetworksAndRequests(nris);
5135 } else {
5136 rematchAllNetworksAndRequests();
5137 }
James Mattis45d81842021-01-10 14:24:24 -08005138
Chalard Jean0354d8c2021-01-12 10:58:56 +09005139 // Requests that have not been matched to a network will not have been sent to the
5140 // providers, because the old satisfier and the new satisfier are the same (null in this
5141 // case). Send these requests to the providers.
5142 for (final NetworkRequestInfo nri : nris) {
5143 for (final NetworkOfferInfo noi : mNetworkOffers) {
5144 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005145 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005146 }
5147 }
5148
James Mattisf7027322020-12-13 16:28:14 -08005149 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5150 final int callingUid) {
5151 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005152 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005153 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5154 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5155 handleReleaseNetworkRequest(
5156 nri.mRequests.get(0),
5157 callingUid,
5158 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005159 }
5160 }
5161
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005162 // Determines whether the network is the best (or could become the best, if it validated), for
5163 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5164 // on the value of reason:
5165 //
5166 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5167 // then it should be torn down.
5168 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5169 // then it should be lingered.
5170 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005171 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005172
Chalard Jean254bd162022-08-25 13:04:51 +09005173 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005174 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5175 return false;
5176 }
5177
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005178 final int numRequests;
5179 switch (reason) {
5180 case TEARDOWN:
5181 numRequests = nai.numRequestNetworkRequests();
5182 break;
5183 case LINGER:
5184 numRequests = nai.numForegroundNetworkRequests();
5185 break;
5186 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005187 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005188 return true;
5189 }
5190
Chalard Jean947acd42021-03-08 22:29:27 +09005191 if (numRequests > 0) return false;
5192
Paul Jensende49eb12015-06-25 15:30:08 -04005193 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005194 if (reason == UnneededFor.LINGER
5195 && !nri.isMultilayerRequest()
5196 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005197 // Background requests don't affect lingering.
5198 continue;
5199 }
5200
James Mattis3d229892020-11-16 16:46:28 -08005201 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005202 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005203 }
5204 }
Paul Jensende49eb12015-06-25 15:30:08 -04005205 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005206 }
5207
James Mattis3d229892020-11-16 16:46:28 -08005208 private boolean isNetworkPotentialSatisfier(
5209 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
5210 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005211 // request, return immediately. For multilayer requests, check to see if any of the
5212 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005213 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5214 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005215 return false;
5216 }
5217 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005218 // This multilayer listen request is satisfied therefore no further requests need to be
5219 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005220 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005221 return false;
5222 }
James Mattis3d229892020-11-16 16:46:28 -08005223 // As non-multilayer listen requests have already returned, the below would only happen
5224 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005225 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005226 continue;
5227 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09005228 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08005229 // there is hope for it to become one if it validated, then it is needed.
5230 if (candidate.satisfies(req)) {
5231 // As soon as a network is found that satisfies a request, return. Specifically for
5232 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5233 // is important so as to not evaluate lower priority requests further in
5234 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005235 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5236 ? nri.getSatisfier() : null;
5237 // Note that this catches two important cases:
5238 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5239 // is currently satisfying the request. This is desirable when
5240 // cellular ends up validating but WiFi does not.
5241 // 2. Unvalidated WiFi will not be reaped when validated cellular
5242 // is currently satisfying the request. This is desirable when
5243 // WiFi ends up validating and out scoring cellular.
5244 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005245 }
5246 }
5247
5248 return false;
5249 }
5250
Erik Kline0c04b742016-07-07 16:50:58 +09005251 private NetworkRequestInfo getNriForAppRequest(
5252 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005253 // Looking up the app passed param request in mRequests isn't possible since it may return
5254 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5255 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005256 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5257 // to avoid potential race conditions when validating a package->uid mapping when sending
5258 // the callback on the very low-chance that an application shuts down prior to the callback
5259 // being sent.
5260 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5261 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005262
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005263 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005264 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005265 log(String.format("UID %d attempted to %s for unowned request %s",
5266 callingUid, requestedOperation, nri));
5267 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005268 }
Erik Kline0c04b742016-07-07 16:50:58 +09005269 }
5270
5271 return nri;
5272 }
5273
James Mattisf7027322020-12-13 16:28:14 -08005274 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5275 final String callingMethod) {
5276 if (nri.isMultilayerRequest()) {
5277 throw new IllegalStateException(
5278 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005279 }
5280 }
5281
James Mattisf7027322020-12-13 16:28:14 -08005282 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005283 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005284 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5285 // single NetworkRequest and thus does not apply to multilayer requests.
5286 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5287 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005288 return;
5289 }
James Mattis2516da32021-01-31 17:06:19 -08005290 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005291 return;
5292 }
James Mattisf7027322020-12-13 16:28:14 -08005293 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5294 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005295 }
5296 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005297 callCallbackForRequest(
5298 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005299 }
5300
James Mattisf7027322020-12-13 16:28:14 -08005301 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5302 final int callingUid,
5303 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005304 final NetworkRequestInfo nri =
5305 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5306 if (nri == null) {
5307 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005308 }
James Mattisf7027322020-12-13 16:28:14 -08005309 if (VDBG || (DBG && request.isRequest())) {
5310 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005311 }
5312 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005313 if (callOnUnavailable) {
5314 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5315 }
Erik Kline155a59a2015-11-25 12:49:38 +09005316 }
Erik Kline0c04b742016-07-07 16:50:58 +09005317
James Mattisa076c532020-12-02 14:12:41 -08005318 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005319 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005320 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005321 if (null == mNetworkRequests.remove(req)) {
5322 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5323 continue;
5324 }
James Mattisa076c532020-12-02 14:12:41 -08005325 if (req.isListen()) {
5326 removeListenRequestFromNetworks(req);
5327 }
5328 }
James Mattis8f036802021-06-20 16:26:01 -07005329 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005330 if (mDefaultNetworkRequests.remove(nri)) {
5331 // If this request was one of the defaults, then the UID rules need to be updated
5332 // WARNING : if the app(s) for which this network request is the default are doing
5333 // traffic, this will kill their connected sockets, even if an equivalent request
5334 // is going to be reinstated right away ; unconnected traffic will go on the default
5335 // until the new default is set, which will happen very soon.
5336 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5337 // remove ranges for those requests that won't have a replacement
5338 final NetworkAgentInfo satisfier = nri.getSatisfier();
5339 if (null != satisfier) {
5340 try {
paulhu0e79d952021-06-09 16:11:35 +08005341 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5342 satisfier.network.getNetId(),
5343 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005344 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005345 } catch (RemoteException e) {
5346 loge("Exception setting network preference default network", e);
5347 }
5348 }
5349 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005350
Junyu Lai00d92df2022-07-05 11:01:52 +08005351 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005352 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005353 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005354
5355 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005356 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005357 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005358 }
5359 }
5360
Chalard Jean0354d8c2021-01-12 10:58:56 +09005361 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5362 // needed for this offer.
5363 for (final NetworkOfferInfo noi : mNetworkOffers) {
5364 for (final NetworkRequest req : nri.mRequests) {
5365 if (req.isRequest() && noi.offer.neededFor(req)) {
5366 noi.offer.onNetworkUnneeded(req);
5367 }
5368 }
5369 }
James Mattisa076c532020-12-02 14:12:41 -08005370 }
5371
James Mattis3ce3d3c2021-02-09 18:18:28 -08005372 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5373 for (final NetworkRequestInfo nri : nris) {
5374 if (mDefaultRequest == nri) {
5375 // Make sure we never remove the default request.
5376 continue;
5377 }
5378 handleRemoveNetworkRequest(nri);
5379 }
5380 }
5381
James Mattisa076c532020-12-02 14:12:41 -08005382 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5383 // listens don't have a singular affected Network. Check all networks to see
5384 // if this listen request applies and remove it.
5385 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5386 nai.removeRequest(req.requestId);
5387 if (req.networkCapabilities.hasSignalStrength()
5388 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5389 updateSignalStrengthThresholds(nai, "RELEASE", req);
5390 }
5391 }
5392 }
5393
5394 /**
5395 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5396 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5397 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5398 */
5399 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5400 boolean wasKept = false;
5401 final NetworkAgentInfo nai = nri.getSatisfier();
5402 if (nai != null) {
5403 final int requestLegacyType = nri.getActiveRequest().legacyType;
5404 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5405 nai.removeRequest(nri.getActiveRequest().requestId);
5406 if (VDBG || DDBG) {
5407 log(" Removing from current network " + nai.toShortString()
5408 + ", leaving " + nai.numNetworkRequests() + " requests.");
5409 }
5410 // If there are still lingered requests on this network, don't tear it down,
5411 // but resume lingering instead.
5412 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005413 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005414 notifyNetworkLosing(nai, now);
5415 }
5416 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5417 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5418 teardownUnneededNetwork(nai);
5419 } else {
5420 wasKept = true;
5421 }
James Mattisa076c532020-12-02 14:12:41 -08005422 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5423 // Went from foreground to background.
5424 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005425 }
5426
Erik Kline0c04b742016-07-07 16:50:58 +09005427 // Maintain the illusion. When this request arrived, we might have pretended
5428 // that a network connected to serve it, even though the network was already
5429 // connected. Now that this request has gone away, we might have to pretend
5430 // that the network disconnected. LegacyTypeTracker will generate that
5431 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005432 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005433 boolean doRemove = true;
5434 if (wasKept) {
5435 // check if any of the remaining requests for this network are for the
5436 // same legacy type - if so, don't remove the nai
5437 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5438 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005439 if (otherRequest.legacyType == requestLegacyType
5440 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005441 if (DBG) log(" still have other legacy request - leaving");
5442 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005443 }
5444 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005445 }
5446
Erik Kline0c04b742016-07-07 16:50:58 +09005447 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005448 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005449 }
5450 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005451 }
5452 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005453
Junyu Lai00d92df2022-07-05 11:01:52 +08005454 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005455 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005456 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5457 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5458 }
5459
Lorenzo Colittid6459092016-07-04 12:55:44 +09005460 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005461 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005462 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005463 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005464 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005465 }
5466
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005467 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005468 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5469 enforceNetworkStackSettingsOrSetup();
5470 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5471 encodeBool(accept), encodeBool(always), network));
5472 }
5473
5474 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005475 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005476 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005477 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5478 }
5479
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005480 @Override
5481 public void setTestAllowBadWifiUntil(long timeMs) {
5482 enforceSettingsPermission();
5483 if (!Build.isDebuggable()) {
5484 throw new IllegalStateException("Does not support in non-debuggable build");
5485 }
5486
5487 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5488 throw new IllegalArgumentException("It should not exceed "
5489 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5490 }
5491
5492 mHandler.sendMessage(
5493 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5494 }
5495
chiachangwange0192a72023-02-06 13:25:01 +00005496 @Override
5497 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5498 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005499
5500 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5501 throw new IllegalArgumentException("Argument should not exceed "
5502 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5503 }
5504
5505 mHandler.sendMessage(
5506 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5507 }
5508
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005509 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5510 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5511 " accept=" + accept + " always=" + always);
5512
5513 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5514 if (nai == null) {
5515 // Nothing to do.
5516 return;
5517 }
5518
Chalard Jean254bd162022-08-25 13:04:51 +09005519 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005520 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005521 return;
5522 }
5523
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005524 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005525 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005526 }
5527
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005528 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5529 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005530 // If network becomes partial connectivity and user already accepted to use this
5531 // network, we should respect the user's option and don't need to popup the
5532 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005533 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005534 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005535 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005536 }
5537
5538 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005539 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005540 }
5541
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005542 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005543 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005544 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005545 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005546 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005547 }
5548
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005549 }
5550
lucaslin2240ef62019-03-12 13:08:03 +08005551 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5552 boolean always) {
5553 if (DBG) {
5554 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5555 + " always=" + always);
5556 }
5557
5558 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5559 if (nai == null) {
5560 // Nothing to do.
5561 return;
5562 }
5563
Chalard Jean254bd162022-08-25 13:04:51 +09005564 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005565 // The network validated while the dialog box was up. Take no action.
5566 return;
5567 }
5568
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005569 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5570 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005571 }
5572
5573 // TODO: Use the current design or save the user choice into IpMemoryStore.
5574 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005575 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005576 }
5577
5578 if (!accept) {
5579 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005580 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005581 // Tear down the network.
5582 teardownUnneededNetwork(nai);
5583 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005584 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5585 // result in a partial connectivity result which will be processed by
5586 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005587 //
5588 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5589 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005590 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005591 }
5592 }
5593
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005594 private void handleSetAvoidUnvalidated(Network network) {
5595 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005596 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005597 // Nothing to do. The network either disconnected or revalidated.
5598 return;
5599 }
Chalard Jean254bd162022-08-25 13:04:51 +09005600 if (0L == nai.getAvoidUnvalidated()) {
5601 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005602 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005603 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005604 }
5605 }
5606
Chalard Jean5fb43c72022-09-08 19:03:14 +09005607 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005608 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005609 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005610 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005611 }
5612
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005613 @Override
5614 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005615 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005616 mHandler.post(() -> {
5617 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5618 if (nai == null) return;
5619 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005620 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005621 });
5622 }
5623
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005624 /**
5625 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5626 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005627 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005628 * @param appExtras Bundle to use as intent extras for the captive portal application.
5629 * Must be treated as opaque to avoid preventing the captive portal app to
5630 * update its arguments.
5631 */
5632 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005633 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005634 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5635 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005636
5637 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5638 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005639 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5640 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005641 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5642
lucaslin75ff7022020-12-17 04:14:35 +08005643 final long token = Binder.clearCallingIdentity();
5644 try {
5645 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5646 } finally {
5647 Binder.restoreCallingIdentity(token);
5648 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005649 }
5650
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005651 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5652 private final Network mNetwork;
5653
5654 private CaptivePortalImpl(Network network) {
5655 mNetwork = network;
5656 }
5657
5658 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005659 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005660 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5661 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005662 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5663 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5664 // Since the network will be disconnected, skip notifying NetworkMonitor
5665 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005666 }
5667
Chiachang Wang938bfba2020-01-09 13:50:55 +08005668 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005669 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005670 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005671 }
5672
5673 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005674 public void appRequest(final int request) {
5675 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5676 if (nm == null) return;
5677
5678 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005679 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005680 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005681 }
5682 }
5683
5684 @Nullable
5685 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5686 // getNetworkAgentInfoForNetwork is thread-safe
5687 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5688 if (nai == null) return null;
5689
5690 // nai.networkMonitor() is thread-safe
5691 return nai.networkMonitor();
5692 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005693 }
5694
Hugo Benichic9048bc2016-09-14 23:23:08 +00005695 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005696 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005697 }
5698
Chalard Jean020b93a2022-09-01 13:20:14 +09005699 private boolean activelyPreferBadWifi() {
5700 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5701 }
5702
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005703 /**
5704 * Return whether the device should maintain continuous, working connectivity by switching away
5705 * from WiFi networks having no connectivity.
5706 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5707 */
5708 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005709 if (!checkNetworkStackPermission()) {
5710 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5711 }
5712 return avoidBadWifi();
5713 }
5714
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005715 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005716 ensureRunningOnConnectivityServiceThread();
5717 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005718 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005719 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005720 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005721 if (avoidBadWifi) {
5722 // If the device is now avoiding bad wifi, remove notifications that might have
5723 // been put up when the device didn't.
5724 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5725 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005726 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005727 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5728 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5729 for (final NetworkOfferInfo noi : offersToUpdate) {
5730 updateOfferScore(noi.offer);
5731 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005732 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005733 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005734 }
5735
Erik Kline95ecfee2016-10-02 18:02:14 +09005736 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005737 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005738 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005739 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005740 if (!configRestrict) {
5741 pw.println("Bad Wi-Fi avoidance: unrestricted");
5742 return;
5743 }
5744
5745 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5746 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005747 pw.println("Config restrict: " + configRestrict);
5748 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005749
Chalard Jeane0fdea32022-09-14 21:44:22 +09005750 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005751 String description;
5752 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005753 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005754 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005755 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005756 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005757 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005758 description = "avoid";
5759 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005760 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005761 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005762 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005763
5764 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5765 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005766 if (null == configValue) {
5767 description = "unset";
5768 } else if (configValue) {
5769 description = "force true";
5770 } else {
5771 description = "force false";
5772 }
5773 pw.println("Actively prefer bad wifi conf: " + description);
5774 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005775 pw.println("Network overrides:");
5776 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005777 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005778 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005779 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005780 }
5781 }
5782 pw.decreaseIndent();
5783 pw.decreaseIndent();
5784 }
5785
paulhu7746e4e2020-06-09 19:07:03 +08005786 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5787 // unify the method.
5788 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5789 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5790 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5791 return settingsComponent != null
5792 ? settingsComponent.getPackageName() : "com.android.settings";
5793 }
5794
lucaslinb1e8e382019-01-24 15:55:30 +08005795 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005796 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005797 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005798 switch (type) {
5799 case NO_INTERNET:
5800 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005801 // High priority because it is only displayed for explicitly selected networks.
5802 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005803 break;
lucasline117e2e2019-10-22 18:27:33 +08005804 case PRIVATE_DNS_BROKEN:
5805 action = Settings.ACTION_WIRELESS_SETTINGS;
5806 // High priority because we should let user know why there is no internet.
5807 highPriority = true;
5808 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005809 case LOST_INTERNET:
5810 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005811 // High priority because it could help the user avoid unexpected data usage.
5812 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005813 break;
lucaslin2240ef62019-03-12 13:08:03 +08005814 case PARTIAL_CONNECTIVITY:
5815 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005816 // Don't bother the user with a high-priority notification if the network was not
5817 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005818 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005819 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005820 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005821 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005822 return;
5823 }
5824
5825 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005826 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005827 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005828 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005829 // Some OEMs have their own Settings package. Thus, need to get the current using
5830 // Settings package name instead of just use default name "com.android.settings".
5831 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5832 intent.setClassName(settingsPkgName,
5833 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005834 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005835
paulhu2af50222020-10-11 22:52:27 +08005836 PendingIntent pendingIntent = PendingIntent.getActivity(
5837 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005838 0 /* requestCode */,
5839 intent,
paulhu2af50222020-10-11 22:52:27 +08005840 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005841
Serik Beketayevec8ad212020-12-07 22:43:07 -08005842 mNotifier.showNotification(
5843 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005844 }
5845
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005846 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5847 // Don't prompt if the network is validated, and don't prompt on captive portals
5848 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005849 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005850 return false;
5851 }
5852
5853 // If a network has partial connectivity, always prompt unless the user has already accepted
5854 // partial connectivity and selected don't ask again. This ensures that if the device
5855 // automatically connects to a network that has partial Internet access, the user will
5856 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005857 // because we have prompted them.
5858 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005859 return true;
5860 }
5861
5862 // If a network has no Internet access, only prompt if the network was explicitly selected
5863 // and if the user has not already told us to use the network regardless of whether it
5864 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005865 if (nai.networkAgentConfig.explicitlySelected
5866 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005867 return true;
5868 }
5869
5870 return false;
5871 }
5872
Chalard Jean5fb43c72022-09-08 19:03:14 +09005873 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5874 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005875
Chalard Jean5fb43c72022-09-08 19:03:14 +09005876 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5877 if (null == nai) return;
5878
5879 if (nai.setEvaluated()) {
5880 // If setEvaluated() returned true, the network never had any form of connectivity.
5881 // This may have an impact on request matching if bad WiFi avoidance is off and the
5882 // network was found not to have Internet access.
5883 nai.updateScoreForNetworkAgentUpdate();
5884 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005885
5886 // Also, if this is WiFi and it should be preferred actively, now is the time to
5887 // prompt the user that they walked past and connected to a bad WiFi.
5888 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5889 && !avoidBadWifi()
5890 && activelyPreferBadWifi()) {
5891 // The notification will be removed if the network validates or disconnects.
5892 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5893 return;
5894 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005895 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005896
Chalard Jean5fb43c72022-09-08 19:03:14 +09005897 if (!shouldPromptUnvalidated(nai)) return;
5898
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005899 // Stop automatically reconnecting to this network in the future. Automatically connecting
5900 // to a network that provides no or limited connectivity is not useful, because the user
5901 // cannot use that network except through the notification shown by this method, and the
5902 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005903 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005904
Chalard Jean254bd162022-08-25 13:04:51 +09005905 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005906 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005907 } else {
5908 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5909 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005910 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005911
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005912 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5913 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005914 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005915
lucaslin2240ef62019-03-12 13:08:03 +08005916 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5917 return;
5918 }
5919
5920 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005921 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005922 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005923 }
5924
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005925 @Override
5926 public int getMultipathPreference(Network network) {
5927 enforceAccessPermission();
5928
5929 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005930 if (nai != null && nai.networkCapabilities
5931 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005932 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5933 }
5934
Aaron Huang9a57acf2020-12-08 10:03:29 +08005935 final NetworkPolicyManager netPolicyManager =
5936 mContext.getSystemService(NetworkPolicyManager.class);
5937
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005938 final long token = Binder.clearCallingIdentity();
5939 final int networkPreference;
5940 try {
5941 networkPreference = netPolicyManager.getMultipathPreference(network);
5942 } finally {
5943 Binder.restoreCallingIdentity(token);
5944 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005945 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005946 return networkPreference;
5947 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005948 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5949 }
5950
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005951 @Override
5952 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005953 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005954 }
5955
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005956 private class InternalHandler extends Handler {
5957 public InternalHandler(Looper looper) {
5958 super(looper);
5959 }
5960
5961 @Override
5962 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005963 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005964 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005965 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005966 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005967 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005968 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005969 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005970 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005971 break;
5972 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08005973 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005974 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08005975 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005976 break;
5977 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005978 case EVENT_REGISTER_NETWORK_PROVIDER: {
5979 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005980 break;
5981 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005982 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5983 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005984 break;
5985 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005986 case EVENT_REGISTER_NETWORK_OFFER: {
5987 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5988 break;
5989 }
5990 case EVENT_UNREGISTER_NETWORK_OFFER: {
5991 final NetworkOfferInfo offer =
5992 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5993 if (null != offer) {
5994 handleUnregisterNetworkOffer(offer);
5995 }
5996 break;
5997 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005998 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005999 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6000 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6001 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006002 break;
6003 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006004 case EVENT_REGISTER_NETWORK_REQUEST:
6005 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006006 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006007 break;
6008 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006009 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6010 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006011 handleRegisterNetworkRequestWithIntent(msg);
6012 break;
6013 }
Erik Kline155a59a2015-11-25 12:49:38 +09006014 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6015 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6016 handleTimedOutNetworkRequest(nri);
6017 break;
6018 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006019 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6020 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6021 break;
6022 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006023 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006024 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6025 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006026 break;
6027 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006028 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006029 Network network = (Network) msg.obj;
6030 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006031 break;
6032 }
lucaslin2240ef62019-03-12 13:08:03 +08006033 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6034 Network network = (Network) msg.obj;
6035 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6036 toBool(msg.arg2));
6037 break;
6038 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006039 case EVENT_SET_AVOID_UNVALIDATED: {
6040 handleSetAvoidUnvalidated((Network) msg.obj);
6041 break;
6042 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006043 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6044 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006045 break;
6046 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006047 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6048 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006049 break;
6050 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006051 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6052 // handler thread.
6053 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006054 mKeepaliveTracker.handleStartKeepalive(msg);
6055 break;
6056 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006057 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006058 final AutomaticOnOffKeepalive ki =
6059 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6060 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006061
chiachangwang676c84e2023-02-14 09:22:05 +00006062 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006063 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006064 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006065 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006066 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6067 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006068 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6069 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006070 }
6071 }
6072
6073 // If the network no longer exists, then the keepalive should have been
6074 // cleaned up already. There is no point trying to resume keepalives.
6075 if (!networkFound) return;
6076
chiachangwang676c84e2023-02-14 09:22:05 +00006077 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006078 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang676c84e2023-02-14 09:22:05 +00006079 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006080 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006081 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006082 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006083 }
6084 break;
6085 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006086 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006087 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006088 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6089 (IBinder) msg.obj);
6090 if (ki == null) {
6091 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006092 return;
6093 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006094 final int reason = msg.arg2;
6095 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006096 break;
6097 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006098 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6099 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6100 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006101 break;
6102 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006103 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6104 handlePrivateDnsSettingsChanged();
6105 break;
dalyk1720e542018-03-05 12:42:22 -05006106 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6107 handlePrivateDnsValidationUpdate(
6108 (PrivateDnsValidationUpdate) msg.obj);
6109 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006110 case EVENT_UID_BLOCKED_REASON_CHANGED:
6111 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006112 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006113 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6114 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6115 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006116 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006117 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6118 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006119 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006120 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006121 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006122 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006123 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6124 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006125 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006126 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006127 }
lucaslin1193a5d2021-01-21 02:04:15 +08006128 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006129 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006130 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006131 break;
paulhu51f77dc2021-06-07 02:34:20 +00006132 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6133 handleMobileDataPreferredUidsChanged();
6134 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006135 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6136 final long timeMs = ((Long) msg.obj).longValue();
6137 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6138 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006139 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6140 handleIngressRateLimitChanged();
6141 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006142 case EVENT_USER_DOES_NOT_WANT:
6143 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6144 if (nai == null) break;
6145 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006146 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006147 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006148 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6149 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6150 break;
chiachangwange0192a72023-02-06 13:25:01 +00006151 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6152 final long time = ((Long) msg.obj).longValue();
6153 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6154 break;
6155 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006156 case EVENT_UID_FROZEN_STATE_CHANGED:
6157 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6158 handleFrozenUids(args.mUids, args.mFrozenStates);
6159 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006160 }
6161 }
6162 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006163
Lorenzo Colittid6459092016-07-04 12:55:44 +09006164 @Override
markchien5776f962019-12-16 20:15:20 +08006165 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006166 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006167 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006168 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6169 Context.TETHERING_SERVICE);
6170 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006171 }
6172
Lorenzo Colittid6459092016-07-04 12:55:44 +09006173 @Override
markchien5776f962019-12-16 20:15:20 +08006174 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006175 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006176 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006177 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6178 Context.TETHERING_SERVICE);
6179 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006180 }
6181
Lorenzo Colittid6459092016-07-04 12:55:44 +09006182 @Override
markchien5776f962019-12-16 20:15:20 +08006183 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006184 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006185 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006186 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6187 Context.TETHERING_SERVICE);
6188 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006189 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006190
markchien5776f962019-12-16 20:15:20 +08006191
Lorenzo Colittid6459092016-07-04 12:55:44 +09006192 @Override
markchien5776f962019-12-16 20:15:20 +08006193 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006194 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006195 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006196 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6197 Context.TETHERING_SERVICE);
6198
6199 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006200 }
6201
Lorenzo Colittid6459092016-07-04 12:55:44 +09006202 @Override
markchien5776f962019-12-16 20:15:20 +08006203 @Deprecated
6204 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006205 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006206 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6207 Context.TETHERING_SERVICE);
6208
6209 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006210 }
6211
Udam Saini8f7d6a72017-06-07 12:06:28 -07006212 @Override
markchien5776f962019-12-16 20:15:20 +08006213 @Deprecated
6214 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006215 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006216 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6217 Context.TETHERING_SERVICE);
6218 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006219 }
6220
Robert Greenwalte0b00512014-07-02 09:59:16 -07006221 // Called when we lose the default network and have no replacement yet.
6222 // This will automatically be cleared after X seconds or a new default network
6223 // becomes CONNECTED, whichever happens first. The timer is started by the
6224 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006225 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006226 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006227 if (mNetTransitionWakeLock.isHeld()) {
6228 return;
6229 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006230 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006231 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6232 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006233 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006234 mWakelockLogs.log("ACQUIRE for " + forWhom);
6235 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006236 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006237 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006238 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006239 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006240
Hugo Benichi471b62a2017-03-30 23:18:10 +09006241 // Called when we gain a new default network to release the network transition wakelock in a
6242 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6243 // message is cancelled.
6244 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006245 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006246 if (!mNetTransitionWakeLock.isHeld()) {
6247 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006248 }
6249 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006250 // Cancel self timeout on wakelock hold.
6251 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6252 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6253 mHandler.sendMessageDelayed(msg, 1000);
6254 }
6255
6256 // Called when either message of ensureNetworkTransitionWakelock or
6257 // scheduleReleaseNetworkTransitionWakelock is processed.
6258 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6259 String event = eventName(eventId);
6260 synchronized (this) {
6261 if (!mNetTransitionWakeLock.isHeld()) {
6262 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006263 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006264 return;
6265 }
6266 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006267 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6268 mTotalWakelockDurationMs += lockDuration;
6269 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6270 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006271 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006272 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006273 }
6274
Robert Greenwalt986c7412010-09-08 15:24:47 -07006275 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006276 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006277 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006278 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006279 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006280 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006281 }
6282
Lorenzo Colittid6459092016-07-04 12:55:44 +09006283 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006284 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006285 enforceAccessPermission();
6286 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006287 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006288 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006289
6290 final NetworkAgentInfo nai;
6291 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006292 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006293 } else {
6294 nai = getNetworkAgentInfoForNetwork(network);
6295 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006296
6297 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006298 mHandler.obtainMessage(
6299 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006300 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006301
Hugo Benichid6b510a2017-04-06 17:22:18 +09006302 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006303 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006304 if (nai == null
6305 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006306 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006307 return;
6308 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006309 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006310 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006311 mConnectivityDiagnosticsHandler.sendMessage(
6312 mConnectivityDiagnosticsHandler.obtainMessage(
6313 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6314 new ReportedNetworkConnectivityInfo(
6315 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006316 return;
6317 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006318 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006319 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006320 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006321 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006322 // Validating a network that has not yet connected could result in a call to
6323 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006324 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006325 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006326 }
paulhu7aeba372020-12-30 00:42:19 +08006327 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6328 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006329 return;
6330 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006331
6332 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6333 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6334 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6335 // completed.
6336 mConnectivityDiagnosticsHandler.sendMessage(
6337 mConnectivityDiagnosticsHandler.obtainMessage(
6338 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6339 new ReportedNetworkConnectivityInfo(
6340 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006341 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006342 }
6343
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006344 // TODO: call into netd.
6345 private boolean queryUserAccess(int uid, Network network) {
6346 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6347 if (nai == null) return false;
6348
6349 // Any UID can use its default network.
6350 if (nai == getDefaultNetworkForUid(uid)) return true;
6351
6352 // Privileged apps can use any network.
6353 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6354 return true;
6355 }
6356
6357 // An unprivileged UID can use a VPN iff the VPN applies to it.
6358 if (nai.isVPN()) {
6359 return nai.networkCapabilities.appliesToUid(uid);
6360 }
6361
6362 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6363 // sockets, i.e., if it is the owner.
6364 final NetworkAgentInfo vpn = getVpnForUid(uid);
6365 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6366 && uid != vpn.networkCapabilities.getOwnerUid()) {
6367 return false;
6368 }
6369
6370 // The UID's permission must be at least sufficient for the network. Since the restricted
6371 // permission was already checked above, that just leaves background networks.
6372 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6373 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6374 }
6375
6376 // Unrestricted network. Anyone gets to use it.
6377 return true;
6378 }
6379
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006380 /**
6381 * Returns information about the proxy a certain network is using. If given a null network, it
6382 * it will return the proxy for the bound network for the caller app or the default proxy if
6383 * none.
6384 *
6385 * @param network the network we want to get the proxy information for.
6386 * @return Proxy information if a network has a proxy configured, or otherwise null.
6387 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006388 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006389 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006390 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006391 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006392 if (network == null) {
6393 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006394 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006395 true);
6396 if (activeNetwork == null) {
6397 return null;
6398 }
6399 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006400 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006401 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6402 // caller may not have.
6403 return getLinkPropertiesProxyInfo(network);
6404 }
6405 // No proxy info available if the calling UID does not have network access.
6406 return null;
6407 }
6408
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006409
6410 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006411 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6412 if (nai == null) return null;
6413 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006414 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6415 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006416 }
6417 }
6418
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006419 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006420 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006421 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006422 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006423 }
6424
Chalard Jean777e2e52018-06-07 18:02:37 +09006425 @Override
6426 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006427 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006428 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006429 }
6430
Aaron Huang9fe47be2021-06-08 13:11:45 +08006431 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006432 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006433 final NetworkAgentInfo nai = getDefaultNetwork();
6434 // TODO : this method should check that net == nai.network, unfortunately at this point
6435 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6436 // is only ever installed on the default network so in practice this is okay.
6437 if (null == nai) return;
6438 // PAC proxies only work on the default network. Therefore, only the default network
6439 // should have its link properties fixed up for PAC proxies.
6440 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6441 if (nai.everConnected()) {
6442 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6443 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006444 }
6445
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006446 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6447 // when any network changes proxy.
6448 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6449 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006450 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6451 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006452 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6453
Chalard Jean7d97afc2018-06-07 17:41:29 +09006454 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006455 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006456 }
6457 }
6458
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006459 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006460 final private HashMap<Uri, Integer> mUriEventMap;
6461 final private Context mContext;
6462 final private Handler mHandler;
6463
6464 SettingsObserver(Context context, Handler handler) {
6465 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006466 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006467 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006468 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006469 }
6470
Erik Kline05f2b402015-04-30 12:58:40 +09006471 void observe(Uri uri, int what) {
6472 mUriEventMap.put(uri, what);
6473 final ContentResolver resolver = mContext.getContentResolver();
6474 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006475 }
6476
6477 @Override
6478 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006479 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006480 }
6481
6482 @Override
6483 public void onChange(boolean selfChange, Uri uri) {
6484 final Integer what = mUriEventMap.get(uri);
6485 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006486 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006487 } else {
6488 loge("No matching event to send for URI=" + uri);
6489 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006490 }
6491 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006492
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006493 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006494 Log.d(TAG, s);
6495 }
6496
6497 private static void logw(String s) {
6498 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006499 }
6500
Daniel Brightf9e945b2020-06-15 16:10:01 -07006501 private static void logwtf(String s) {
6502 Log.wtf(TAG, s);
6503 }
6504
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006505 private static void logwtf(String s, Throwable t) {
6506 Log.wtf(TAG, s, t);
6507 }
6508
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006509 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006510 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006511 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006512
Hugo Benichi39621362017-02-11 17:04:43 +09006513 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006514 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006515 }
6516
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006517 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006518 * Return the information of all ongoing VPNs.
6519 *
6520 * <p>This method is used to update NetworkStatsService.
6521 *
6522 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006523 */
junyulai2050bed2021-01-23 09:46:34 +08006524 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006525 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006526 if (mLockdownEnabled) {
6527 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006528 }
junyulai2050bed2021-01-23 09:46:34 +08006529 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006530 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006531 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006532 if (info != null) {
6533 infoList.add(info);
6534 }
6535 }
junyulai2050bed2021-01-23 09:46:34 +08006536 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006537 }
6538
6539 /**
6540 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006541 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006542 */
junyulai2050bed2021-01-23 09:46:34 +08006543 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006544 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006545 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6546 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006547 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6548 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6549 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006550 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6551 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006552 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006553 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006554 }
6555 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006556
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006557 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006558
6559 List<String> interfaces = new ArrayList<>();
6560 for (Network network : underlyingNetworks) {
6561 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6562 if (underlyingNai == null) continue;
6563 LinkProperties lp = underlyingNai.linkProperties;
6564 for (String iface : lp.getAllInterfaceNames()) {
6565 if (!TextUtils.isEmpty(iface)) {
6566 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006567 }
6568 }
Benedict Wong34857f82019-06-12 17:46:15 +00006569 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006570
6571 if (interfaces.isEmpty()) return null;
6572
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006573 // Must be non-null or NetworkStatsService will crash.
6574 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6575 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006576 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006577 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006578
junyulai2050bed2021-01-23 09:46:34 +08006579 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6580 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006581 }
6582
James Mattisd31bdfa2020-12-23 16:37:26 -08006583 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006584 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6585 Network[] underlyingNetworks) {
6586 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006587 if (underlyingNetworks == null && defaultNetwork != null) {
6588 // null underlying networks means to track the default.
6589 underlyingNetworks = new Network[] { defaultNetwork };
6590 }
6591 return underlyingNetworks;
6592 }
6593
6594 // Returns true iff |network| is an underlying network of |nai|.
6595 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6596 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6597 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006598 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006599 final Network[] underlying = underlyingNetworksOrDefault(
6600 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006601 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006602 }
6603
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006604 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006605 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006606 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006607 * When underlying networks change, such networks may have to update capabilities to reflect
6608 * things like the metered bit, their transports, and so on. The capabilities are calculated
6609 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006610 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006611 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006612 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006613 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006614 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006615 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006616 }
6617 }
6618 }
6619
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006620 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6621 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6622 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6623 // a VPN is not up.
6624 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6625 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6626 for (UidRange range : blockedUidRanges) {
6627 if (range.contains(uid)) return true;
6628 }
6629 return false;
6630 }
6631
6632 @Override
6633 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006634 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006635 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6636 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6637 }
6638
6639 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6640 if (DBG) {
6641 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6642 + Arrays.toString(ranges));
6643 }
6644 // Cannot use a Set since the list of UID ranges might contain duplicates.
6645 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6646 for (int i = 0; i < ranges.length; i++) {
6647 if (requireVpn) {
6648 newVpnBlockedUidRanges.add(ranges[i]);
6649 } else {
6650 newVpnBlockedUidRanges.remove(ranges[i]);
6651 }
6652 }
6653
6654 try {
6655 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6656 } catch (RemoteException | ServiceSpecificException e) {
6657 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6658 + Arrays.toString(ranges) + "): netd command failed: " + e);
6659 }
6660
Chalard Jeandf29a852023-05-29 17:02:43 +09006661 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006662 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6663 }
6664
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006665 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6666 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006667 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6668 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006669 }
6670
6671 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6672 }
6673
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006674 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006675 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006676 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006677 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006678 }
6679
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006680 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6681 return mLockdownEnabled
6682 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6683 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006684 }
6685
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006686 private NetworkAgentInfo getLegacyLockdownNai() {
6687 if (!mLockdownEnabled) {
6688 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006689 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006690 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006691 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6692 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006693
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006694 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006695 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6696 // a local variable. There is no need to make a copy because its contents cannot change.
6697 final Network[] underlying = nai.declaredUnderlyingNetworks;
6698 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006699 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006700 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006701
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006702 // The legacy lockdown VPN always uses the default network.
6703 // If the VPN's underlying network is no longer the current default network, it means that
6704 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006705 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6706 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006707 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006708 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006709 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006710 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006711
6712 return nai;
6713 };
6714
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006715 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6716 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6717 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006718 private DetailedState getLegacyLockdownState(DetailedState origState) {
6719 if (origState != DetailedState.CONNECTED) {
6720 return origState;
6721 }
6722 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6723 ? DetailedState.CONNECTING
6724 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006725 }
6726
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006727 private void filterForLegacyLockdown(NetworkInfo ni) {
6728 if (!mLockdownEnabled || !ni.isConnected()) return;
6729 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6730 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6731 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6732 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6733 // network, this time with a state of CONNECTED.
6734 //
6735 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6736 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6737 // is not too far off the truth, since an always-on VPN, when not connected, is always
6738 // trying to reconnect.
6739 if (getLegacyLockdownNai() == null) {
6740 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6741 }
6742 }
6743
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006744 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006745 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006746 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006747 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006748 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6749 return;
6750 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006751 final long ident = Binder.clearCallingIdentity();
6752 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006753 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006754 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006755 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006756 } finally {
6757 Binder.restoreCallingIdentity(ident);
6758 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006759 }
Wink Savillecb117d32013-08-29 14:57:08 -07006760
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006761 @Override
6762 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006763 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006764 final long ident = Binder.clearCallingIdentity();
6765 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006766 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006767 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006768 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6769 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006770 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006771 } finally {
6772 Binder.restoreCallingIdentity(ident);
6773 }
6774 }
6775
James Mattis02220e22021-03-13 19:27:21 -08006776 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006777 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6778 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6779 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006780 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006781 }
6782
James Mattis02220e22021-03-13 19:27:21 -08006783 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006784 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006785 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006786 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6787 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006788 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006789 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6790 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6791 }
junyulaid91e7052020-08-28 13:44:33 +08006792 }
6793
James Mattis02220e22021-03-13 19:27:21 -08006794 private void onPackageChanged(@NonNull final String packageName) {
6795 // This is necessary in case a package is added or removed, but also when it's replaced to
6796 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6797 // as one in the preferences, then it should follow the same routing as that other package,
6798 // which means updating the rules is never to be needed in this case (whether it joins or
6799 // leaves a UID with a preference).
6800 if (isMappedInOemNetworkPreference(packageName)) {
6801 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6802 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006803
6804 // Invalidates cache entry when the package is updated.
6805 synchronized (mSelfCertifiedCapabilityCache) {
6806 mSelfCertifiedCapabilityCache.remove(packageName);
6807 }
James Mattis02220e22021-03-13 19:27:21 -08006808 }
6809
6810 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006811 @Override
6812 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006813 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006814 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006815 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006816
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006817 // User should be filled for below intents, check the existence.
6818 if (user == null) {
6819 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6820 return;
6821 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006822
Lorenzo Colitticd675292021-02-04 17:32:07 +09006823 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006824 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006825 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006826 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006827 } else {
junyulaid91e7052020-08-28 13:44:33 +08006828 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006829 }
6830 }
6831 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006832
James Mattis02220e22021-03-13 19:27:21 -08006833 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6834 @Override
6835 public void onReceive(Context context, Intent intent) {
6836 ensureRunningOnConnectivityServiceThread();
6837 switch (intent.getAction()) {
6838 case Intent.ACTION_PACKAGE_ADDED:
6839 case Intent.ACTION_PACKAGE_REMOVED:
6840 case Intent.ACTION_PACKAGE_REPLACED:
6841 onPackageChanged(intent.getData().getSchemeSpecificPart());
6842 break;
6843 default:
6844 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6845 }
6846 }
6847 };
6848
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006849 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006850 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006851
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006852 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006853 public final String name;
6854 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006855 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006856 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006857
lifraf3a3492021-03-10 13:58:14 +08006858 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6859 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006860 this.name = name;
6861 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006862 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006863 mDeathRecipient = deathRecipient;
6864
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006865 if (mDeathRecipient == null) {
6866 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006867 }
6868 }
6869
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006870 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006871 try {
6872 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6873 } catch (RemoteException e) {
6874 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006875 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006876 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006877 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006878
James Mattis4fce5d12020-11-12 15:53:42 -08006879 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6880 for (int i = 0; i < requests.size(); i++) {
6881 ensureNetworkRequestHasType(requests.get(i));
6882 }
6883 }
6884
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006885 private void ensureNetworkRequestHasType(NetworkRequest request) {
6886 if (request.type == NetworkRequest.Type.NONE) {
6887 throw new IllegalArgumentException(
6888 "All NetworkRequests in ConnectivityService must have a type");
6889 }
6890 }
6891
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006892 /**
6893 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006894 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006895 */
James Mattis258ea3c2020-11-15 15:04:40 -08006896 @VisibleForTesting
6897 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006898 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6899 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006900 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006901
James Mattisa076c532020-12-02 14:12:41 -08006902 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6903 void setSatisfier(
6904 @Nullable final NetworkAgentInfo satisfier,
6905 @Nullable final NetworkRequest activeRequest) {
6906 mSatisfier = satisfier;
6907 mActiveRequest = activeRequest;
6908 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006909
James Mattisd31bdfa2020-12-23 16:37:26 -08006910 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006911 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006912 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006913 private NetworkAgentInfo mSatisfier;
6914 NetworkAgentInfo getSatisfier() {
6915 return mSatisfier;
6916 }
6917
6918 // The request in mRequests assigned to a network agent. This is null if none of the
6919 // requests in mRequests can be satisfied. This member has the constraint of only being
6920 // accessible on the handler thread.
6921 @Nullable
6922 private NetworkRequest mActiveRequest;
6923 NetworkRequest getActiveRequest() {
6924 return mActiveRequest;
6925 }
6926
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006927 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006928 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006929 @Nullable
6930 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006931
6932 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006933 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006934 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006935 final int mPid;
6936 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006937 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006938 @Nullable
6939 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006940
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006941 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006942 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006943
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006944 // Effective UID of this request. This is different from mUid when a privileged process
6945 // files a request on behalf of another UID. This UID is used to determine blocked status,
6946 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6947 // maximum limit of registered callbacks per UID.
6948 final int mAsUid;
6949
paulhu48291862021-07-14 14:53:57 +08006950 // Preference order of this request.
6951 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006952
James Mattis3ce3d3c2021-02-09 18:18:28 -08006953 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6954 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6955 // maintained for keying off of. This is only a concern when the original nri
6956 // mNetworkRequests changes which happens currently for apps that register callbacks to
6957 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6958 // that match the per-app default nri that currently tracks the calling app's uid so that
6959 // callbacks are fired at the appropriate time. When the callbacks fire,
6960 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6961 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6962 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6963 @NonNull
6964 private final NetworkRequest mNetworkRequestForCallback;
6965 NetworkRequest getNetworkRequestForCallback() {
6966 return mNetworkRequestForCallback;
6967 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006968
James Mattisd31bdfa2020-12-23 16:37:26 -08006969 /**
6970 * Get the list of UIDs this nri applies to.
6971 */
6972 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006973 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006974 // networkCapabilities.getUids() returns a defensive copy.
6975 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006976 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6977 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006978 }
6979
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006980 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6981 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006982 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006983 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006984 }
6985
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006986 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006987 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006988 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006989 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006990 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006991 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006992 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006993 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006994 mBinder = null;
6995 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006996 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006997 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006998 mPerUidCounter = getRequestCounter(this);
6999 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007000 /**
7001 * Location sensitive data not included in pending intent. Only included in
7002 * {@link NetworkCallback}.
7003 */
7004 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007005 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007006 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007007 }
7008
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007009 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007010 @Nullable final IBinder binder,
7011 @NetworkCallback.Flag int callbackFlags,
7012 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007013 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7014 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007015 }
7016
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007017 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007018 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007019 @Nullable final IBinder binder,
7020 @NetworkCallback.Flag int callbackFlags,
7021 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007022 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007023 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007024 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007025 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007026 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007027 mBinder = binder;
7028 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007029 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007030 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007031 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007032 mPerUidCounter = getRequestCounter(this);
7033 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007034 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007035 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007036 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007037 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007038 }
7039
James Mattis3ce3d3c2021-02-09 18:18:28 -08007040 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7041 @NonNull final List<NetworkRequest> r) {
7042 super();
7043 ensureAllNetworkRequestsHaveType(r);
7044 mRequests = initializeRequests(r);
7045 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007046 final NetworkAgentInfo satisfier = nri.getSatisfier();
7047 if (null != satisfier) {
7048 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7049 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007050 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007051 // As this code creates a new NRI with a new set of requests, figure out which of
7052 // the list of requests should be the active request. It is always the first
7053 // request of the list that can be satisfied by the satisfier since the order of
7054 // requests is a priority order.
7055 // Note even in the presence of a satisfier there may not be an active request,
7056 // when the satisfier is the no-service network.
7057 NetworkRequest activeRequest = null;
7058 for (final NetworkRequest candidate : r) {
7059 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7060 activeRequest = candidate;
7061 break;
7062 }
7063 }
7064 setSatisfier(satisfier, activeRequest);
7065 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007066 mMessenger = nri.mMessenger;
7067 mBinder = nri.mBinder;
7068 mPid = nri.mPid;
7069 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007070 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007071 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007072 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007073 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007074 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007075 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007076 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007077 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007078 }
7079
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007080 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007081 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007082 }
7083
paulhue9913722021-05-26 15:19:20 +08007084 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007085 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007086 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007087 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007088 }
7089
James Mattis2516da32021-01-31 17:06:19 -08007090 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7091 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7092 // false.
7093 boolean isBeingSatisfied() {
7094 return (null != mSatisfier && null != mActiveRequest);
7095 }
7096
James Mattis3d229892020-11-16 16:46:28 -08007097 boolean isMultilayerRequest() {
7098 return mRequests.size() > 1;
7099 }
7100
James Mattis45d81842021-01-10 14:24:24 -08007101 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7102 // Creating a defensive copy to prevent the sender from modifying the list being
7103 // reflected in the return value of this method.
7104 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007105 return Collections.unmodifiableList(tempRequests);
7106 }
7107
James Mattisb1392002021-03-31 13:57:52 -07007108 void linkDeathRecipient() {
7109 if (null != mBinder) {
7110 try {
7111 mBinder.linkToDeath(this, 0);
7112 } catch (RemoteException e) {
7113 binderDied();
7114 }
7115 }
7116 }
7117
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007118 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007119 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007120 try {
7121 mBinder.unlinkToDeath(this, 0);
7122 } catch (NoSuchElementException e) {
7123 // Temporary workaround for b/194394697 pending analysis of additional logs
7124 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7125 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007126 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007127 }
7128
paulhu48291862021-07-14 14:53:57 +08007129 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7130 // Compare two preference orders.
7131 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007132 }
7133
paulhu48291862021-07-14 14:53:57 +08007134 int getPreferenceOrderForNetd() {
7135 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7136 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7137 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007138 }
paulhu48291862021-07-14 14:53:57 +08007139 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007140 }
7141
James Mattis4fce5d12020-11-12 15:53:42 -08007142 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007143 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007144 // As an immutable collection, mRequests cannot change by the time the
7145 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7146 // is acceptable. Use handleReleaseNetworkRequest and not directly
7147 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7148 // the app already unregistered the request.
7149 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7150 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007151 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007152
James Mattis4fce5d12020-11-12 15:53:42 -08007153 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007154 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007155 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7156 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007157 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007158 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007159 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007160 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007161 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007162 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007163 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007164 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007165 }
7166
Junyu Lai00d92df2022-07-05 11:01:52 +08007167 // Keep backward compatibility since the ServiceSpecificException is used by
7168 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7169 public static class RequestInfoPerUidCounter extends PerUidCounter {
7170 RequestInfoPerUidCounter(int maxCountPerUid) {
7171 super(maxCountPerUid);
7172 }
7173
7174 @Override
7175 public synchronized void incrementCountOrThrow(int uid) {
7176 try {
7177 super.incrementCountOrThrow(uid);
7178 } catch (IllegalStateException e) {
7179 throw new ServiceSpecificException(
7180 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7181 "Uid " + uid + " exceeded its allotted requests limit");
7182 }
7183 }
7184
7185 @Override
7186 public synchronized void decrementCountOrThrow(int uid) {
7187 throw new UnsupportedOperationException("Use decrementCount instead.");
7188 }
7189
7190 public synchronized void decrementCount(int uid) {
7191 try {
7192 super.decrementCountOrThrow(uid);
7193 } catch (IllegalStateException e) {
7194 logwtf("Exception when decrement per uid request count: ", e);
7195 }
7196 }
7197 }
7198
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007199 // This checks that the passed capabilities either do not request a
7200 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007201 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007202 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007203 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007204 throw new SecurityException("Insufficient permissions to request a specific SSID");
7205 }
paulhu1a407652019-03-22 16:35:06 +08007206
7207 if (nc.hasSignalStrength()
7208 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7209 throw new SecurityException(
7210 "Insufficient permissions to request a specific signal strength");
7211 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007212 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007213
junyulai2217bec2021-04-14 23:33:31 +08007214 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007215 enforceNetworkFactoryPermission();
7216 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007217 }
7218
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007219 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007220 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007221 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007222 // mNetworkRequests may contain the same value multiple times in case of
7223 // multilayer requests. It won't matter in this case because the thresholds
7224 // will then be the same and be deduplicated as they enter the `thresholds` set.
7225 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007226 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7227 for (final NetworkRequest req : nri.mRequests) {
7228 if (req.networkCapabilities.hasSignalStrength()
7229 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7230 thresholds.add(req.networkCapabilities.getSignalStrength());
7231 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007232 }
7233 }
7234 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007235 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007236 }
7237
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007238 private void updateSignalStrengthThresholds(
7239 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007240 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007241
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007242 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007243 String detail;
7244 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7245 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7246 } else {
7247 detail = reason;
7248 }
7249 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007250 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007251 }
7252
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007253 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007254 }
7255
Chalard Jeandd421992021-12-16 23:16:02 +09007256 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007257 if (nc == null) {
7258 return;
7259 }
7260 NetworkSpecifier ns = nc.getNetworkSpecifier();
7261 if (ns == null) {
7262 return;
7263 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007264 if (ns instanceof MatchAllNetworkSpecifier) {
7265 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7266 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007267 }
7268
Chalard Jeandd421992021-12-16 23:16:02 +09007269 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007270 ensureValidNetworkSpecifier(nc);
7271 if (nc.isPrivateDnsBroken()) {
7272 throw new IllegalArgumentException("Can't request broken private DNS");
7273 }
Chalard Jeande665262022-02-25 16:12:12 +09007274 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007275 throw new IllegalArgumentException("Can't request access UIDs");
7276 }
lucasline117e2e2019-10-22 18:27:33 +08007277 }
7278
Chalard Jeandd421992021-12-16 23:16:02 +09007279 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7280 ensureListenableCapabilities(nc);
7281 final String badCapability = nc.describeFirstNonRequestableCapability();
7282 if (badCapability != null) {
7283 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7284 }
7285 }
7286
Chiachang Wang3bc52762021-11-25 14:17:57 +08007287 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7288 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007289 private boolean isTargetSdkAtleast(int version, int callingUid,
7290 @NonNull String callingPackageName) {
7291 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007292 final PackageManager pm =
7293 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007294 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007295 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007296 if (callingVersion < version) return false;
7297 } catch (PackageManager.NameNotFoundException e) { }
7298 return true;
7299 }
7300
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007301 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007302 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007303 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007304 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007305 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007306 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007307 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7308 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007309 throw new SecurityException("Insufficient permissions to specify legacy type");
7310 }
markchienfac84a22020-03-18 21:16:15 +08007311 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007312 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007313 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007314 // Privileged callers can track the default network of another UID by passing in a UID.
7315 if (asUid != Process.INVALID_UID) {
7316 enforceSettingsPermission();
7317 } else {
7318 asUid = callingUid;
7319 }
junyulaiad010792021-01-11 16:53:38 +08007320 final NetworkRequest.Type reqType;
7321 try {
7322 reqType = NetworkRequest.Type.values()[reqTypeInt];
7323 } catch (ArrayIndexOutOfBoundsException e) {
7324 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7325 }
7326 switch (reqType) {
7327 case TRACK_DEFAULT:
7328 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007329 // is unused and will be replaced by ones appropriate for the UID (usually, the
7330 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007331 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007332 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007333 enforceAccessPermission();
7334 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007335 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007336 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007337 networkCapabilities = new NetworkCapabilities(defaultNc);
7338 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007339 case BACKGROUND_REQUEST:
7340 enforceNetworkStackOrSettingsPermission();
7341 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007342 case REQUEST:
7343 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7344 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007345 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007346 // TODO: this is incorrect. We mark the request as metered or not depending on
7347 // the state of the app when the request is filed, but we never change the
7348 // request if the app changes network state. http://b/29964605
7349 enforceMeteredApnPolicy(networkCapabilities);
7350 break;
junyulai1b1c8742021-03-12 20:05:08 +08007351 case LISTEN_FOR_BEST:
7352 enforceAccessPermission();
7353 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7354 break;
junyulaiad010792021-01-11 16:53:38 +08007355 default:
7356 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007357 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007358 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007359 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007360 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007361
junyulai1b1c8742021-03-12 20:05:08 +08007362 // Enforce FOREGROUND if the caller does not have permission to use background network.
7363 if (reqType == LISTEN_FOR_BEST) {
7364 restrictBackgroundRequestForCaller(networkCapabilities);
7365 }
7366
7367 // Set the UID range for this request to the single UID of the requester, unless the
7368 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007369 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7370 // are no visible methods to set the UIDs, an app could use reflection to try and get
7371 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007372 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007373 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7374 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007375
Etan Cohen85000162017-02-05 10:42:27 -08007376 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007377 throw new IllegalArgumentException("Bad timeout specified");
7378 }
Etan Cohen9786d922015-11-18 10:56:15 -08007379
James Mattis3ce3d3c2021-02-09 18:18:28 -08007380 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007381 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007382 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007383 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007384 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007385 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007386
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007387 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7388 // copied from the default request above. (This is necessary to ensure, for example, that
7389 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7390 // changes don't alter request matching.
7391 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7392 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007393 throw new IllegalStateException(
7394 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007395 + networkCapabilities + " vs. " + defaultNc);
7396 }
7397
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007398 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007399 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007400 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007401 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007402 }
7403 return networkRequest;
7404 }
7405
James Mattis3ce3d3c2021-02-09 18:18:28 -08007406 /**
7407 * Return the nri to be used when registering a network request. Specifically, this is used with
7408 * requests registered to track the default request. If there is currently a per-app default
7409 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7410 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007411 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7412 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007413 * @param nr the network request for the nri.
7414 * @param msgr the messenger for the nri.
7415 * @param binder the binder for the nri.
7416 * @param callingAttributionTag the calling attribution tag for the nri.
7417 * @return the nri to register.
7418 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007419 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007420 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007421 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007422 @Nullable String callingAttributionTag) {
7423 final List<NetworkRequest> requests;
7424 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7425 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007426 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007427 } else {
7428 requests = Collections.singletonList(nr);
7429 }
Roshan Pius951c0032020-12-22 15:10:42 -08007430 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007431 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007432 }
7433
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007434 private boolean shouldCheckCapabilitiesDeclaration(
7435 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7436 @NonNull final String callingPackageName) {
7437 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7438 // Only run the check if the change is enabled.
7439 if (!mDeps.isChangeEnabled(
7440 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7441 callingPackageName, user)) {
7442 return false;
7443 }
7444
7445 return networkCapabilities.hasCapability(
7446 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7447 || networkCapabilities.hasCapability(
7448 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7449 }
7450
7451 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
7452 @NonNull final NetworkCapabilities networkCapabilities) {
7453 // This check is added to fix the linter error for "current min is 30", which is not going
7454 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007455 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007456 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7457 return;
7458 }
7459 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007460 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007461 try {
7462 synchronized (mSelfCertifiedCapabilityCache) {
7463 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7464 callerPackageName);
7465 if (applicationNetworkCapabilities == null) {
7466 final PackageManager packageManager = mContext.getPackageManager();
7467 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7468 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7469 callerPackageName
7470 );
7471 final XmlResourceParser parser = packageManager
7472 .getResourcesForApplication(callerPackageName)
7473 .getXml(networkSliceProperty.getResourceId());
7474 applicationNetworkCapabilities =
7475 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7476 mSelfCertifiedCapabilityCache.put(callerPackageName,
7477 applicationNetworkCapabilities);
7478 }
7479
7480 }
7481 } catch (PackageManager.NameNotFoundException ne) {
7482 throw new SecurityException(
7483 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7484 + " property");
7485 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7486 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007487 } finally {
7488 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007489 }
7490
7491 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7492 networkCapabilities);
7493 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007494 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007495 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007496 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7497 callingPackageName)) {
7498 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7499 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007500 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007501 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7502 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7503 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7504 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007505 }
junyulai96bd9fe2022-03-08 17:36:42 +08007506 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007507 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007508 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007509 }
7510 }
7511
fenglu3f357402015-03-20 11:29:56 -07007512 @Override
fenglub00f4882015-04-21 17:12:05 -07007513 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007514 enforceAccessPermission();
7515 NetworkAgentInfo nai = null;
7516 if (network == null) {
7517 return false;
7518 }
7519 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007520 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007521 }
7522 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007523 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007524 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007525 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007526 Integer uidReqs = mBandwidthRequests.get(uid);
7527 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007528 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007529 }
7530 mBandwidthRequests.put(uid, ++uidReqs);
7531 }
fenglu3f357402015-03-20 11:29:56 -07007532 return true;
7533 }
7534 return false;
7535 }
7536
Felipe Leme0a5ae422016-06-20 16:36:29 -07007537 private boolean isSystem(int uid) {
7538 return uid < Process.FIRST_APPLICATION_UID;
7539 }
fenglu3f357402015-03-20 11:29:56 -07007540
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007541 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007542 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007543 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007544 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007545 return;
7546 }
Hugo Benichi39621362017-02-11 17:04:43 +09007547 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7548 // Policy already enforced.
7549 return;
7550 }
paulhuaf50d7d2020-12-24 19:47:34 +08007551 final long ident = Binder.clearCallingIdentity();
7552 try {
7553 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7554 // If UID is restricted, don't allow them to bring up metered APNs.
7555 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7556 }
7557 } finally {
7558 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007559 }
7560 }
7561
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007562 @Override
7563 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007564 PendingIntent operation, @NonNull String callingPackageName,
7565 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007566 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007567 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007568 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007569 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007570 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007571 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007572 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007573 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007574 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007575 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7576 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007577
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007578 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007579 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007580 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7581 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007582 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007583 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7584 nri));
7585 return networkRequest;
7586 }
7587
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007588 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7589 mHandler.sendMessageDelayed(
7590 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007591 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007592 }
7593
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007594 @Override
7595 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007596 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007597 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007598 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007599 }
7600
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007601 // In order to implement the compatibility measure for pre-M apps that call
7602 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7603 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7604 // This ensures it has permission to do so.
7605 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7606 if (nc == null) {
7607 return false;
7608 }
7609 int[] transportTypes = nc.getTransportTypes();
7610 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7611 return false;
7612 }
7613 try {
7614 mContext.enforceCallingOrSelfPermission(
7615 android.Manifest.permission.ACCESS_WIFI_STATE,
7616 "ConnectivityService");
7617 } catch (SecurityException e) {
7618 return false;
7619 }
7620 return true;
7621 }
7622
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007623 @Override
7624 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007625 Messenger messenger, IBinder binder,
7626 @NetworkCallback.Flag int callbackFlags,
7627 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007628 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007629 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7630 enforceAccessPermission();
7631 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007632
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007633 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007634 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007635 Binder.getCallingPid(), callingUid, callingPackageName);
7636 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007637 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7638 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7639 // onLost and onAvailable callbacks when networks move in and out of the background.
7640 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7641 // can't request networks.
7642 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007643 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007644
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007645 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007646 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007647 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007648 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007649 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007650 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007651
7652 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7653 return networkRequest;
7654 }
7655
7656 @Override
7657 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007658 PendingIntent operation, @NonNull String callingPackageName,
7659 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007660 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007661 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007662 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7663 enforceAccessPermission();
7664 }
Chalard Jeandd421992021-12-16 23:16:02 +09007665 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007666 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007667 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007668 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007669 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007670
7671 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007672 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007673 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7674 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007675 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007676
WeiZhang1cc3f172021-06-03 19:02:04 -05007677 mHandler.sendMessage(mHandler.obtainMessage(
7678 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007679 }
7680
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007681 /** Returns the next Network provider ID. */
7682 public final int nextNetworkProviderId() {
7683 return mNextNetworkProviderId.getAndIncrement();
7684 }
7685
Erik Kline0c04b742016-07-07 16:50:58 +09007686 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007687 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007688 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007689 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007690 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007691 }
7692
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007693 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7694 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007695 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7696 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7697 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007698 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007699 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007700 return;
7701 }
7702
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007703 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7704 mNetworkProviderInfos.put(npi.messenger, npi);
7705 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007706 }
7707
7708 @Override
7709 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007710 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007711 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007712 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007713 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007714 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7715 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007716 }
7717
7718 @Override
7719 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007720 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007721 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007722 }
7723
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007724 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007725 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007726 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7727 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007728 Objects.requireNonNull(score);
7729 Objects.requireNonNull(caps);
7730 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007731 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007732 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007733 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7734 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007735 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7736 }
7737
Chalard Jeanbb902a52021-08-18 01:35:19 +09007738 private void updateOfferScore(final NetworkOffer offer) {
7739 final boolean yieldToBadWiFi =
7740 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7741 final NetworkOffer newOffer = new NetworkOffer(
7742 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7743 offer.caps, offer.callback, offer.providerId);
7744 if (offer.equals(newOffer)) return;
7745 handleRegisterNetworkOffer(newOffer);
7746 }
7747
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007748 @Override
7749 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007750 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007751 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7752 }
7753
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007754 private void handleUnregisterNetworkProvider(Messenger messenger) {
7755 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7756 if (npi == null) {
7757 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007758 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007759 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007760 // Unregister all the offers from this provider
7761 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7762 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007763 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007764 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7765 toRemove.add(noi);
7766 }
7767 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007768 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007769 handleUnregisterNetworkOffer(noi);
7770 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007771 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007772 }
7773
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007774 @Override
James Mattisf7027322020-12-13 16:28:14 -08007775 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007776 if (request.hasTransport(TRANSPORT_TEST)) {
7777 enforceNetworkFactoryOrTestNetworksPermission();
7778 } else {
7779 enforceNetworkFactoryPermission();
7780 }
James Mattisf7027322020-12-13 16:28:14 -08007781 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7782 if (nri != null) {
7783 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7784 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7785 mHandler.post(() -> handleReleaseNetworkRequest(
7786 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7787 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007788 }
7789
Paul Jensen1f567382015-02-13 14:18:39 -05007790 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7791 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007792 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007793 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007794 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007795 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007796 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007797
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007798 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007799 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007800 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007801
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007802 // UID ranges for users that are currently blocked by VPNs.
7803 // This array is accessed and iterated on multiple threads without holding locks, so its
7804 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7805 // (on the handler thread).
7806 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7807
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007808 // Must only be accessed on the handler thread
7809 @NonNull
7810 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7811
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007812 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007813 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007814
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007815 // Current OEM network preferences. This object must only be written to on the handler thread.
7816 // Since it is immutable and always non-null, other threads may read it if they only care
7817 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007818 @NonNull
7819 private OemNetworkPreferences mOemNetworkPreferences =
7820 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007821 // Current per-profile network preferences. This object follows the same threading rules as
7822 // the OEM network preferences above.
7823 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007824 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7825 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007826
lucaslin3ba7cc22022-12-19 02:35:33 +00007827 // Current VPN network preferences. This object follows the same threading rules as the OEM
7828 // network preferences above.
7829 @NonNull
7830 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7831 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7832
paulhu51f77dc2021-06-07 02:34:20 +00007833 // A set of UIDs that should use mobile data preferentially if available. This object follows
7834 // the same threading rules as the OEM network preferences above.
7835 @NonNull
7836 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7837
James Mattiscb1e0362021-04-06 17:07:42 -07007838 // OemNetworkPreferences activity String log entries.
7839 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7840 @NonNull
7841 private final LocalLog mOemNetworkPreferencesLogs =
7842 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7843
James Mattis02220e22021-03-13 19:27:21 -08007844 /**
7845 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7846 * @param packageName the package name to check existence of a mapping for.
7847 * @return true if a mapping exists, false otherwise
7848 */
7849 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7850 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7851 }
7852
James Mattise3ef1912020-12-20 11:09:58 -08007853 // The always-on request for an Internet-capable network that apps without a specific default
7854 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007855 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007856 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007857 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007858 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007859 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007860 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007861 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007862
James Mattisd31bdfa2020-12-23 16:37:26 -08007863 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7864 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7865 }
7866
7867 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007868 * Return the default network request currently tracking the given uid.
7869 * @param uid the uid to check.
7870 * @return the NetworkRequestInfo tracking the given uid.
7871 */
7872 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007873 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007874 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007875 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007876 // Checking the first request is sufficient as only multilayer requests will have more
7877 // than one request and for multilayer, all requests will track the same uids.
7878 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007879 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007880 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007881 highestPriorityNri = nri;
7882 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007883 }
7884 }
paulhuaa0743d2021-05-26 21:56:03 +08007885 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007886 }
7887
7888 /**
7889 * Get a copy of the network requests of the default request that is currently tracking the
7890 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007891 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7892 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007893 * @param requestorUid the uid to check the default for.
7894 * @param requestorPackageName the requestor's package name.
7895 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7896 */
7897 @NonNull
7898 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007899 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007900 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007901 getDefaultRequestTrackingUid(asUid).mRequests,
7902 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007903 }
7904
7905 /**
7906 * Copy the given nri's NetworkRequest collection.
7907 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007908 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7909 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007910 * @param requestorUid the uid to set on the copied collection.
7911 * @param requestorPackageName the package name to set on the copied collection.
7912 * @return the copied NetworkRequest collection.
7913 */
7914 @NonNull
7915 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007916 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7917 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007918 final List<NetworkRequest> requests = new ArrayList<>();
7919 for (final NetworkRequest nr : requestsToCopy) {
7920 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007921 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007922 nr.legacyType, nextNetworkRequestId(), nr.type));
7923 }
7924 return requests;
7925 }
7926
7927 @NonNull
7928 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007929 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7930 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007931 // These capabilities are for a TRACK_DEFAULT callback, so:
7932 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7933 // mDefaultRequest and a per-UID default request.
7934 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007935 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007936 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007937 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7938 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007939 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007940 restrictRequestUidsForCallerAndSetRequestorInfo(
7941 netCap, requestorUid, requestorPackageName);
7942 return netCap;
7943 }
7944
7945 /**
7946 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7947 * @param nr the network request to check for equality against.
7948 * @return the nri if one exists, null otherwise.
7949 */
7950 @Nullable
7951 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7952 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7953 if (nri.getNetworkRequestForCallback().equals(nr)) {
7954 return nri;
7955 }
7956 }
7957 return null;
7958 }
7959
7960 /**
7961 * Check if an nri is currently being managed by per-app default networking.
7962 * @param nri the nri to check.
7963 * @return true if this nri is currently being managed by per-app default networking.
7964 */
7965 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7966 // nri.mRequests.get(0) is only different from the original request filed in
7967 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7968 // functionality therefore if these two don't match, it means this particular nri is
7969 // currently being managed by a per-app default.
7970 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7971 }
7972
7973 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007974 * Determine if an nri is a managed default request that disallows default networking.
7975 * @param nri the request to evaluate
7976 * @return true if device-default networking is disallowed
7977 */
7978 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7979 // Check if this nri is a managed default that supports the default network at its
7980 // lowest priority request.
7981 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7982 final NetworkCapabilities lowestPriorityNetCap =
7983 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7984 return isPerAppDefaultRequest(nri)
7985 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7986 lowestPriorityNetCap));
7987 }
7988
Erik Kline05f2b402015-04-30 12:58:40 +09007989 // Request used to optionally keep mobile data active even when higher
7990 // priority networks like Wi-Fi are active.
7991 private final NetworkRequest mDefaultMobileDataRequest;
7992
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007993 // Request used to optionally keep wifi data active even when higher
7994 // priority networks like ethernet are active.
7995 private final NetworkRequest mDefaultWifiRequest;
7996
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007997 // Request used to optionally keep vehicle internal network always active
7998 private final NetworkRequest mDefaultVehicleRequest;
7999
James Mattisd31bdfa2020-12-23 16:37:26 -08008000 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8001 // network with no service. This NAI should never be matched against, nor should any public API
8002 // ever return the associated network. For this reason, this NAI is not in the list of available
8003 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8004 // default requests that don't support using the device default network which will ultimately
8005 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8006 @VisibleForTesting
8007 final NetworkAgentInfo mNoServiceNetwork;
8008
Chalard Jean5b409c72021-02-04 13:12:59 +09008009 // The NetworkAgentInfo currently satisfying the default request, if any.
8010 private NetworkAgentInfo getDefaultNetwork() {
8011 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008012 }
8013
James Mattis2516da32021-01-31 17:06:19 -08008014 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008015 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008016 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8017 // Currently, all network requests will have the same uids therefore checking the first
8018 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008019 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008020 if (null == uids) {
8021 continue;
8022 }
8023 for (final UidRange range : uids) {
8024 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008025 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008026 highestPriorityNri = nri;
8027 }
James Mattis2516da32021-01-31 17:06:19 -08008028 }
8029 }
8030 }
paulhuaa0743d2021-05-26 21:56:03 +08008031 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008032 }
8033
Varun Ananddf569952019-02-06 10:13:38 -08008034 @Nullable
8035 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8036 return nai != null ? nai.network : null;
8037 }
8038
8039 private void ensureRunningOnConnectivityServiceThread() {
8040 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8041 throw new IllegalStateException(
8042 "Not running on ConnectivityService thread: "
8043 + Thread.currentThread().getName());
8044 }
8045 }
8046
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008047 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008048 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8049 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008050 }
8051
Chalard Jean29d06db2018-05-02 21:14:54 +09008052 /**
8053 * Register a new agent with ConnectivityService to handle a network.
8054 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008055 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008056 * @param networkInfo the initial info associated with this network. It can be updated later :
8057 * see {@link #updateNetworkInfo}.
8058 * @param linkProperties the initial link properties of this network. They can be updated
8059 * later : see {@link #updateLinkProperties}.
8060 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008061 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008062 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008063 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008064 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008065 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008066 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008067 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09008068 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09008069 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
8070 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008071 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8072 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8073 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008074 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008075 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008076 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008077 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008078 } else {
8079 enforceNetworkFactoryPermission();
8080 }
8081
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008082 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008083 final long token = Binder.clearCallingIdentity();
8084 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008085 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09008086 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008087 } finally {
8088 Binder.restoreCallingIdentity(token);
8089 }
8090 }
8091
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008092 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008093 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09008094 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
8095 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008096
Chalard Jeandbc46952022-02-02 00:14:18 +09008097 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8098 // and mutate them at any time.
8099 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8100 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8101 final LinkProperties lpCopy = new LinkProperties(linkProperties);
8102
Chalard Jean366c5252022-01-25 18:27:53 +09008103 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008104 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008105 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8106 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008107 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008108 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09008109 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09008110 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
8111 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008112
Chalard Jeandbc46952022-02-02 00:14:18 +09008113 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008114 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008115 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008116 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008117 mDeps.getNetworkStack().makeNetworkMonitor(
8118 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008119 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8120 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008121 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008122 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008123 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008124 }
8125
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008126 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008127 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008128 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008129 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008130 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008131 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8132 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8133 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008134
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008135 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008136
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008137 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008138 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008139 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008140 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008141
8142 try {
8143 networkMonitor.start();
8144 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008145 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008146 }
Chalard Jean366c5252022-01-25 18:27:53 +09008147
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008148 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008149 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008150 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008151 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008152 }
8153
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008154 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8155 @NonNull public final NetworkOffer offer;
8156
8157 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8158 this.offer = offer;
8159 }
8160
8161 @Override
8162 public void binderDied() {
8163 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8164 }
8165 }
8166
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008167 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8168 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8169 if (npi.providerId == providerId) return true;
8170 }
8171 return false;
8172 }
8173
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008174 /**
8175 * Register or update a network offer.
8176 * @param newOffer The new offer. If the callback member is the same as an existing
8177 * offer, it is an update of that offer.
8178 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008179 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008180 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8181 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008182 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008183 // This may actually happen if a provider updates its score or registers and then
8184 // immediately unregisters. The offer would still be in the handler queue, but the
8185 // provider would have been removed.
8186 if (DBG) log("Received offer from an unregistered provider");
8187 return;
8188 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008189 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8190 if (null != existingOffer) {
8191 handleUnregisterNetworkOffer(existingOffer);
8192 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008193 if (DBG) {
8194 // handleUnregisterNetworkOffer has already logged the old offer
8195 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8196 }
8197 } else {
8198 if (DBG) {
8199 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8200 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008201 }
8202 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8203 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008204 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008205 } catch (RemoteException e) {
8206 noi.binderDied();
8207 return;
8208 }
8209 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008210 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008211 }
8212
8213 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8214 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008215 if (DBG) {
8216 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8217 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008218
8219 // If the provider removes the offer and dies immediately afterwards this
8220 // function may be called twice in a row, but the array will no longer contain
8221 // the offer.
8222 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008223 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008224 }
8225
8226 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8227 @NonNull final INetworkOfferCallback callback) {
8228 ensureRunningOnConnectivityServiceThread();
8229 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008230 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008231 }
8232 return null;
8233 }
8234
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008235 /**
8236 * Called when receiving LinkProperties directly from a NetworkAgent.
8237 * Stores into |nai| any data coming from the agent that might also be written to the network's
8238 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8239 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008240 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008241 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008242 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8243 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008244 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008245 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008246 }
8247
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008248 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008249 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008250 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008251
Lorenzo Colittid523d142020-04-01 20:16:30 +09008252 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8253 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8254 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008255 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008256
Suprabh Shukla1e312032023-01-24 03:36:37 -08008257 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008258
8259 // update filtering rules, need to happen after the interface update so netd knows about the
8260 // new interface (the interface name -> index map becomes initialized)
8261 updateVpnFiltering(newLp, oldLp, networkAgent);
8262
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008263 updateMtu(newLp, oldLp);
8264 // TODO - figure out what to do for clat
8265// for (LinkProperties lp : newLp.getStackedLinks()) {
8266// updateMtu(lp, null);
8267// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008268 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008269 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008270 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8271 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008272
Erik Klineb9888902016-04-05 13:30:49 +09008273 updateRoutes(newLp, oldLp, netId);
8274 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008275 // Make sure LinkProperties represents the latest private DNS status.
8276 // This does not need to be done before updateDnses because the
8277 // LinkProperties are not the source of the private DNS configuration.
8278 // updateDnses will fetch the private DNS configuration from DnsManager.
8279 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008280
Chalard Jean5b409c72021-02-04 13:12:59 +09008281 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008282 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008283 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008284 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008285 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008286
8287 updateWakeOnLan(newLp);
8288
Hai Shalome58bdc62021-01-11 18:45:34 -08008289 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8290 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8291 // does, it needs to be merged here.
8292 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8293 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008294
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008295 // TODO - move this check to cover the whole function
8296 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008297 synchronized (networkAgent) {
8298 networkAgent.linkProperties = newLp;
8299 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008300 // Start or stop DNS64 detection and 464xlat according to network state.
8301 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008302 // Notify NSS when relevant events happened. Currently, NSS only cares about
8303 // interface changed to update clat interfaces accounting.
8304 final boolean interfacesChanged = oldLp == null
8305 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8306 if (interfacesChanged) {
8307 notifyIfacesChangedForNetworkStats();
8308 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008309 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8310 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008311 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008312 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008313
8314 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008315 }
8316
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008317 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8318 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8319 }
8320
Hai Shalome58bdc62021-01-11 18:45:34 -08008321 /**
8322 * @param naData captive portal data from NetworkAgent
8323 * @param apiData captive portal data from capport API
8324 */
8325 @Nullable
8326 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8327 CaptivePortalData apiData) {
8328 if (naData == null || apiData == null) {
8329 return naData == null ? apiData : naData;
8330 }
8331 final CaptivePortalData.Builder captivePortalBuilder =
8332 new CaptivePortalData.Builder(naData);
8333
8334 if (apiData.isCaptive()) {
8335 captivePortalBuilder.setCaptive(true);
8336 }
8337 if (apiData.isSessionExtendable()) {
8338 captivePortalBuilder.setSessionExtendable(true);
8339 }
8340 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8341 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8342 // otherwise data would be inconsistent. Prefer the capport API info if present,
8343 // as it can generally be refreshed more often.
8344 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8345 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8346 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8347 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8348 // No source has time / bytes remaining information: surface the newest refresh time
8349 // for other fields
8350 captivePortalBuilder.setRefreshTime(
8351 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8352 }
8353
Hai Shalom7c6ab402021-02-04 19:34:06 -08008354 // Prioritize the user portal URL from the network agent if the source is authenticated.
8355 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8356 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8357 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8358 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008359 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008360 // Prioritize the venue information URL from the network agent if the source is
8361 // authenticated.
8362 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8363 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8364 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8365 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008366 }
8367 return captivePortalBuilder.build();
8368 }
8369
Suprabh Shukla53e16392023-04-26 18:47:36 -07008370 @VisibleForTesting
8371 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008372 // This needs to be kept in sync and backwards compatible with the decoding logic in
8373 // NetdEventListenerService, which is non-mainline code.
8374 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8375 }
8376
Suprabh Shukla75642282023-04-25 23:15:43 -07008377 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8378 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8379 return true;
8380 }
8381 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8382 return true;
8383 }
8384 return false;
8385 }
8386
Suprabh Shukla1e312032023-01-24 03:36:37 -08008387 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008388 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008389 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008390 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008391 return;
8392 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008393
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008394 // Mask/mark of zero will not detect anything interesting.
8395 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008396 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008397 return;
8398 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008399
Suprabh Shukla1e312032023-01-24 03:36:37 -08008400 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008401 try {
8402 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008403 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008404 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008405 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008406 }
8407 } catch (Exception e) {
8408 loge("Exception modifying wakeup packet monitoring: " + e);
8409 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008410 }
8411
Junyu Lai970963e2022-10-25 15:46:47 +08008412 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008413 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008414 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008415 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008416 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008417 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008418 for (final String iface : interfaceDiff.added) {
8419 try {
8420 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008421 mNetd.networkAddInterface(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008422 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008423 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008424 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008425 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008426 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008427 }
Paul Jensenbff73492014-04-28 10:33:11 -04008428 }
8429 }
Chalard Jean9589e722019-11-19 19:03:53 +09008430 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008431 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008432 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008433 wakeupModifyInterface(iface, nai, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008434 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008435 } catch (Exception e) {
8436 loge("Exception removing interface: " + e);
8437 }
8438 }
8439 }
8440
Tyler Weare4314862019-12-05 14:55:30 -08008441 // TODO: move to frameworks/libs/net.
8442 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
8443 final String nextHop;
8444
8445 switch (route.getType()) {
8446 case RouteInfo.RTN_UNICAST:
8447 if (route.hasGateway()) {
8448 nextHop = route.getGateway().getHostAddress();
8449 } else {
8450 nextHop = INetd.NEXTHOP_NONE;
8451 }
8452 break;
8453 case RouteInfo.RTN_UNREACHABLE:
8454 nextHop = INetd.NEXTHOP_UNREACHABLE;
8455 break;
8456 case RouteInfo.RTN_THROW:
8457 nextHop = INetd.NEXTHOP_THROW;
8458 break;
8459 default:
8460 nextHop = INetd.NEXTHOP_NONE;
8461 break;
8462 }
8463
8464 final RouteInfoParcel rip = new RouteInfoParcel();
8465 rip.ifName = route.getInterface();
8466 rip.destination = route.getDestination().toString();
8467 rip.nextHop = nextHop;
8468 rip.mtu = route.getMtu();
8469
8470 return rip;
8471 }
8472
Paul Jensene0fd4a82014-08-06 15:51:33 -04008473 /**
8474 * Have netd update routes from oldLp to newLp.
8475 * @return true if routes changed between oldLp and newLp
8476 */
Junyu Lai970963e2022-10-25 15:46:47 +08008477 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8478 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008479 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008480 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8481 new CompareOrUpdateResult<>(
8482 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008483 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008484 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008485
8486 // add routes before removing old in case it helps with continuous connectivity
8487
Chalard Jean9dd11612018-06-04 16:52:49 +09008488 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008489 for (RouteInfo route : routeDiff.added) {
8490 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008491 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008492 try {
Tyler Weare4314862019-12-05 14:55:30 -08008493 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008494 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008495 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008496 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008497 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008498 }
8499 }
8500 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008501 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008502 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008503 try {
Tyler Weare4314862019-12-05 14:55:30 -08008504 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008505 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008506 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008507 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008508 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008509 }
8510 }
8511
8512 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008513 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008514 try {
Tyler Weare4314862019-12-05 14:55:30 -08008515 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008516 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08008517 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008518 }
8519 }
Tyler Weare4314862019-12-05 14:55:30 -08008520
8521 for (RouteInfo route : routeDiff.updated) {
8522 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8523 try {
8524 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
8525 } catch (Exception e) {
8526 loge("Exception in networkUpdateRouteParcel: " + e);
8527 }
8528 }
8529 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8530 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008531 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008532
Junyu Lai970963e2022-10-25 15:46:47 +08008533 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8534 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008535 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8536 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008537 }
Erik Klineb9888902016-04-05 13:30:49 +09008538
Erik Kline31b4a9e2018-01-11 21:07:29 +09008539 if (DBG) {
8540 final Collection<InetAddress> dnses = newLp.getDnsServers();
8541 log("Setting DNS servers for network " + netId + " to " + dnses);
8542 }
Erik Klineb9888902016-04-05 13:30:49 +09008543 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008544 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008545 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008546 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008547 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008548 }
Erik Kline54e35c02017-04-07 15:29:29 +09008549 }
8550
Junyu Lai970963e2022-10-25 15:46:47 +08008551 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8552 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008553 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8554 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008555 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8556 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008557
8558 if (!wasFiltering && !needsFiltering) {
8559 // Nothing to do.
8560 return;
8561 }
8562
8563 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8564 // Nothing changed.
8565 return;
8566 }
8567
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008568 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008569 if (ranges == null || ranges.isEmpty()) {
8570 return;
8571 }
8572
Qingxi Libb8da982020-01-17 17:54:27 -08008573 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008574 // TODO: this create a window of opportunity for apps to receive traffic between the time
8575 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008576 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008577 // old rules are being removed.
8578 if (wasFiltering) {
8579 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8580 }
8581 if (needsFiltering) {
8582 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8583 }
8584 }
8585
Valentin Iftime9fa35092019-09-24 13:32:13 +02008586 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008587 if (mWolSupportedInterfaces == null) {
8588 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008589 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008590 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008591 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8592 }
8593
Luke Huangb913c812018-08-24 20:33:16 +08008594 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008595 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008596 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008597 }
8598 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008599 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008600 }
Luke Huangb913c812018-08-24 20:33:16 +08008601 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008602 }
8603
Chalard Jean62edfd82019-12-02 18:39:29 +09008604 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8605 @NonNull final NetworkCapabilities newNc) {
8606 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8607 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008608 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008609 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008610 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008611 } catch (RemoteException | ServiceSpecificException e) {
8612 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008613 }
8614 }
8615 }
8616
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008617 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008618 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008619 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008620 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008621 underlyingNetworks = underlyingNetworksOrDefault(
8622 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008623 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008624 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8625 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008626 // metered if any underlying is metered, or originally declared metered by the agent.
8627 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008628 boolean roaming = false; // roaming if any underlying is roaming
8629 boolean congested = false; // congested if any underlying is congested
8630 boolean suspended = true; // suspended if all underlying are suspended
8631
8632 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008633 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008634 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008635 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008636 for (Network underlyingNetwork : underlyingNetworks) {
8637 final NetworkAgentInfo underlying =
8638 getNetworkAgentInfoForNetwork(underlyingNetwork);
8639 if (underlying == null) continue;
8640
8641 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8642 hadUnderlyingNetworks = true;
8643 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008644 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008645 }
8646
8647 // Merge capabilities of this underlying network. For bandwidth, assume the
8648 // worst case.
8649 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8650 underlyingCaps.getLinkDownstreamBandwidthKbps());
8651 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8652 underlyingCaps.getLinkUpstreamBandwidthKbps());
8653 // If this underlying network is metered, the VPN is metered (it may cost money
8654 // to send packets on this network).
8655 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8656 // If this underlying network is roaming, the VPN is roaming (the billing structure
8657 // is different than the usual, local one).
8658 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8659 // If this underlying network is congested, the VPN is congested (the current
8660 // condition of the network affects the performance of this network).
8661 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8662 // If this network is not suspended, the VPN is not suspended (the VPN
8663 // is able to transfer some data).
8664 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008665 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008666 }
8667 }
8668 if (!hadUnderlyingNetworks) {
8669 // No idea what the underlying networks are; assume reasonable defaults
8670 metered = true;
8671 roaming = false;
8672 congested = false;
8673 suspended = false;
8674 }
8675
Chalard Jean1d420b32022-10-12 16:39:37 +09008676 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008677 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8678 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8679 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8680 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8681 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8682 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008683 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008684 }
8685
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008686 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008687 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8688 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8689 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008690 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008691 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008692 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008693 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008694 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8695 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008696 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008697 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008698 if (nai.everConnected()
8699 && !nai.isVPN()
8700 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008701 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008702 // does not cause any request (that is not a listen) currently matching that agent to
8703 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008704 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008705 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008706 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008707 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008708 }
8709
Paul Jensen53f08952015-06-16 14:27:36 -04008710 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008711 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008712 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008713 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008714 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008715 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008716 }
Chalard Jean254bd162022-08-25 13:04:51 +09008717 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008718 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008719 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008720 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008721 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008722 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008723 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008724 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008725 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008726 }
Chalard Jean254bd162022-08-25 13:04:51 +09008727 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008728 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8729 } else {
8730 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8731 }
lucasline117e2e2019-10-22 18:27:33 +08008732 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008733
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008734 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008735 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8736 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008737 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008738 }
8739
Lorenzo Colittibd079452021-07-02 11:47:57 +09008740 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008741 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008742 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008743 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008744 }
8745
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008746 return newNc;
8747 }
8748
Lorenzo Colitti44840702021-01-11 22:27:57 +09008749 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8750 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8751 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8752 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8753 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8754 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8755 if (prevSuspended != suspended) {
8756 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8757 // onResumed have been removed.
8758 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8759 : ConnectivityManager.CALLBACK_RESUMED);
8760 }
8761 if (prevSuspended != suspended || prevRoaming != roaming) {
8762 // updateNetworkInfo will mix in the suspended info from the capabilities and
8763 // take appropriate action for the network having possibly changed state.
8764 updateNetworkInfo(nai, nai.networkInfo);
8765 }
8766 }
8767
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008768 /**
8769 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8770 *
8771 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8772 * capabilities we manage and store in {@code nai}, such as validated status and captive
8773 * portal status)
8774 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8775 * potentially triggers rematches.
8776 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8777 * change.)
8778 *
8779 * @param oldScore score of the network before any of the changes that prompted us
8780 * to call this function.
8781 * @param nai the network having its capabilities updated.
8782 * @param nc the new network capabilities.
8783 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008784 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008785 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008786 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008787 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008788 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8789 if (null != differences) {
8790 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8791 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008792 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008793 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008794
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008795 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008796 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008797 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008798
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008799 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008800 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8801 // the change we're processing can't affect any requests, it can only affect the listens
8802 // on this network. We might have been called by rematchNetworkAndRequests when a
8803 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008804 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008805 } else {
8806 // If the requestable capabilities have changed or the score changed, we can't have been
8807 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008808 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008809 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008810 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008811 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008812
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008813 final boolean oldMetered = prevNc.isMetered();
8814 final boolean newMetered = newNc.isMetered();
8815 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008816
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008817 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008818 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8819 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008820 }
junyulaif2c67e42018-08-07 19:50:45 +08008821
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008822 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8823 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008824
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008825 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008826 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008827 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008828 }
8829
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008830 // This network might have been underlying another network. Propagate its capabilities.
8831 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008832
8833 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008834 mDnsManager.updateTransportsForNetwork(
8835 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008836 }
lucaslin53e8a262021-06-08 01:43:59 +08008837
8838 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008839 }
8840
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008841 /** Convenience method to update the capabilities for a given network. */
8842 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008843 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008844 }
8845
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008846 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008847 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008848 *
8849 * Ingress interface filtering enforces that all apps under the given network can only receive
8850 * packets from the network's interface (and loopback). This is important for VPNs because
8851 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8852 * non-VPN interfaces.
8853 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008854 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008855 * 1. the network is an app VPN (not legacy VPN)
8856 * 2. the VPN does not allow bypass
8857 * 3. the VPN is fully-routed
8858 * 4. the VPN interface is non-null
8859 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008860 * @see INetd#firewallAddUidInterfaceRules
8861 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008862 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008863 @Nullable
8864 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008865 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008866 if (nc == null || lp == null) return null;
8867 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008868 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008869 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008870 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008871 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008872 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008873 && !lp.hasExcludeRoute()) {
8874 return lp.getInterfaceName();
8875 }
8876 return null;
8877 }
8878
8879 /**
8880 * Returns whether we need to set interface filtering rule or not
8881 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008882 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008883 String isolationIface) {
8884 // Allow rules are always needed if VPN isolation is enabled.
8885 if (isolationIface != null) return true;
8886
8887 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8888 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8889 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09008890 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008891 }
8892
Chiachang Wang28afaff2020-12-10 22:24:47 +08008893 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8894 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8895 int index = 0;
8896 for (UidRange range : ranges) {
8897 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8898 index++;
8899 }
8900 return stableRanges;
8901 }
8902
Chalard Jeane6c95272022-01-25 21:04:21 +09008903 private static UidRangeParcel[] intsToUidRangeStableParcels(
8904 final @NonNull ArraySet<Integer> uids) {
8905 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8906 int index = 0;
8907 for (int uid : uids) {
8908 stableRanges[index] = new UidRangeParcel(uid, uid);
8909 index++;
8910 }
8911 return stableRanges;
8912 }
8913
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008914 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8915 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8916 for (int i = 0; i < ranges.length; i++) {
8917 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8918 }
8919 return stableRanges;
8920 }
8921
Motomu Utsumi93a22182023-03-16 17:04:21 +09008922 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09008923 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08008924 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8925 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09008926 if (mDeps.isAtLeastU()) {
8927 final Set<Integer> exemptUidSet = new ArraySet<>();
8928 for (final int uid: exemptUids) {
8929 exemptUidSet.add(uid);
8930 }
8931 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
8932 } else {
8933 mNetd.socketDestroy(uidRangeParcels, exemptUids);
8934 }
Ken Chen5e65a852020-12-24 12:59:10 +08008935 } catch (Exception e) {
8936 loge("Exception in socket destroy: ", e);
8937 }
8938 }
8939 }
8940
paulhuaa0743d2021-05-26 21:56:03 +08008941 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09008942 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08008943 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8944 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8945 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09008946 exemptUids[0] = VPN_UID;
8947 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08008948 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8949
Motomu Utsumi6345e462023-03-13 13:24:50 +09008950 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09008951 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008952 try {
8953 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008954 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008955 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008956 } else {
paulhu0e79d952021-06-09 16:11:35 +08008957 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008958 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008959 }
8960 } catch (Exception e) {
8961 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8962 " on netId " + nai.network.netId + ". " + e);
8963 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09008964 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09008965 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008966 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008967
lucaslin53e8a262021-06-08 01:43:59 +08008968 private boolean isProxySetOnAnyDefaultNetwork() {
8969 ensureRunningOnConnectivityServiceThread();
8970 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8971 final NetworkAgentInfo nai = nri.getSatisfier();
8972 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8973 return true;
8974 }
8975 }
8976 return false;
8977 }
8978
8979 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8980 NetworkCapabilities newNc) {
8981 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8982 // the proxy might be changed since the default network satisfied by the apps might also
8983 // changed.
8984 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8985 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008986 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8987 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008988 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008989 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8990 mProxyTracker.sendProxyBroadcast();
8991 }
8992 }
8993
Chalard Jeane6c95272022-01-25 21:04:21 +09008994 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8995 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008996 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8997 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008998 if (null == prevRanges) prevRanges = new ArraySet<>();
8999 if (null == newRanges) newRanges = new ArraySet<>();
9000 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9001
9002 prevRanges.removeAll(newRanges);
9003 newRanges.removeAll(prevRangesCopy);
9004
9005 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009006 // When updating the VPN uid routing rules, add the new range first then remove the old
9007 // range. If old range were removed first, there would be a window between the old
9008 // range being removed and the new range being added, during which UIDs contained
9009 // in both ranges are not subject to any VPN routing rules. Adding new range before
9010 // removing old range works because, unlike the filtering rules below, it's possible to
9011 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009012 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9013 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9014 // [1-5] & [1-2],[4-5] == [3]
9015 // Then we can do:
9016 // maybeCloseSockets([3])
9017 // mNetd.networkAddUidRanges([1-2],[4-5])
9018 // mNetd.networkRemoveUidRanges([1-5])
9019 // maybeCloseSockets([3])
9020 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9021 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009022 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009023 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009024 }
9025 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009026 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009027 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009028 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9029 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009030 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9031 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009032 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009033 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009034 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9035 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9036 // were added first and then newRanges got removed later, there would be only one uid
9037 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9038 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9039 // Note that this is in contrast with the (more robust) update of VPN routing rules
9040 // above, where the addition of new ranges happens before the removal of old ranges.
9041 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9042 // to be removed will never overlap with the new range to be added.
9043 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009044 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9045 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009046 }
9047 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009048 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009049 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009050 } catch (Exception e) {
9051 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009052 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009053 }
9054 }
9055
Chalard Jeande665262022-02-25 16:12:12 +09009056 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009057 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9058 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009059 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9060 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009061 if (prevEmpty && newEmpty) return;
9062
9063 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009064 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009065 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009066 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009067
9068 if (prevUids.equals(newUids)) return;
9069
9070 // This implementation is very simple and vastly faster for sets of Integers than
9071 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9072 // a key computed from the value and has storage for that.
9073 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9074 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9075 toRemove.removeAll(newUids);
9076 toAdd.removeAll(prevUids);
9077
9078 try {
9079 if (!toAdd.isEmpty()) {
9080 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9081 nai.network.netId,
9082 intsToUidRangeStableParcels(toAdd),
9083 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9084 }
9085 if (!toRemove.isEmpty()) {
9086 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9087 nai.network.netId,
9088 intsToUidRangeStableParcels(toRemove),
9089 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9090 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009091 } catch (ServiceSpecificException e) {
9092 // Has the interface disappeared since the network was built ?
9093 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009094 } catch (RemoteException e) {
9095 // Netd died. This usually causes a runtime restart anyway.
9096 }
9097 }
9098
Junyu Lai2ed7d412022-10-07 16:52:21 +08009099 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9100 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009101 ensureRunningOnConnectivityServiceThread();
9102
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009103 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009104 // Ignore updates for disconnected networks
9105 return;
9106 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009107 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009108 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009109 + "; created=" + nai.getCreatedTime()
9110 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009111 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009112 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9113 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009114 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009115 }
9116
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009117 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9118 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009119 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009120 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009121 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009122 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9123 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9124 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009125 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9126 // need to be sent as a separate extra.
9127 final NetworkRequest req = nri.isMultilayerRequest()
9128 ? nri.getActiveRequest()
9129 // Non-multilayer listen requests do not have an active request
9130 : nri.mRequests.get(0);
9131 if (req == null) {
9132 Log.wtf(TAG, "No request in NRI " + nri);
9133 }
9134 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009135 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009136 sendIntent(nri.mPendingIntent, intent);
9137 }
9138 // else not handled
9139 }
9140
Michael Groover73f69482023-01-27 11:01:25 -06009141 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9142 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009143 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9144 mPendingIntentWakeLock.acquire();
9145 try {
9146 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009147 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009148 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009149 // Explicitly disallow the receiver from starting activities, to prevent apps from
9150 // utilizing the PendingIntent as a backdoor to do this.
9151 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9152 }
9153 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9154 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009155 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009156 } catch (PendingIntent.CanceledException e) {
9157 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9158 mPendingIntentWakeLock.release();
9159 releasePendingNetworkRequest(pendingIntent);
9160 }
9161 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9162 }
9163
9164 @Override
9165 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9166 String resultData, Bundle resultExtras) {
9167 if (DBG) log("Finished sending " + pendingIntent);
9168 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009169 // Release with a delay so the receiving client has an opportunity to put in its
9170 // own request.
9171 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009172 }
9173
Chalard Jean46bfbf02022-02-02 00:56:25 +09009174 // networkAgent is only allowed to be null if notificationType is
9175 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9176 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009177 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009178 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009179 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009180 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009181 // Default request has no msgr. Also prevents callbacks from being invoked for
9182 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9183 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9184 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009185 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009186 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009187 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009188 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009189 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009190 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009191 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009192 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9193 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009194 }
Roshan Pius951c0032020-12-22 15:10:42 -08009195 final boolean includeLocationSensitiveInfo =
9196 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009197 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009198 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009199 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009200 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009201 networkCapabilitiesRestrictedForCallerPermissions(
9202 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9203 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009204 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009205 nri.mCallingAttributionTag);
9206 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009207 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9208 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08009209 // For this notification, arg1 contains the blocked status.
9210 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009211 break;
9212 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009213 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009214 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009215 break;
9216 }
9217 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009218 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009219 final NetworkCapabilities netCap =
9220 networkCapabilitiesRestrictedForCallerPermissions(
9221 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9222 putParcelable(
9223 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009224 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009225 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009226 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009227 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009228 break;
9229 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009230 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009231 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9232 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009233 break;
9234 }
junyulaif2c67e42018-08-07 19:50:45 +08009235 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009236 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009237 msg.arg1 = arg1;
9238 break;
9239 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009240 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009241 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009242 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009243 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009244 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009245 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009246 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009247 }
James Mattis45d81842021-01-10 14:24:24 -08009248 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009249 } catch (RemoteException e) {
9250 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009251 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009252 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009253 }
9254
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009255 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9256 bundle.putParcelable(t.getClass().getSimpleName(), t);
9257 }
9258
Chalard Jean0702f982021-09-16 21:50:07 +09009259 /**
9260 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9261 *
9262 * When a request should be assigned to a new network, it is normally lingered to give
9263 * time for apps to gracefully migrate their connections. When both networks are on the same
9264 * radio, but that radio can't do time-sharing efficiently, this may end up being
9265 * counter-productive because any traffic on the old network may drastically reduce the
9266 * performance of the new network.
9267 * The stack supports a configuration to let modem vendors state that their radio can't
9268 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9269 * from one cell network to another can't be done gracefully.
9270 *
9271 * @param oldNai the old network serving the request
9272 * @param newNai the new network serving the request
9273 * @return whether the switch can be graceful
9274 */
9275 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9276 @NonNull final NetworkAgentInfo newSatisfier) {
9277 if (mCellularRadioTimesharingCapable) return true;
9278 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9279 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9280 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9281 }
9282
Paul Jensenaf94b982014-09-30 15:37:41 -04009283 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009284 if (nai.numRequestNetworkRequests() != 0) {
9285 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9286 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009287 // Ignore listening and track default requests.
9288 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009289 loge("Dead network still had at least " + nr);
9290 break;
9291 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009292 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009293 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009294 }
9295
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009296 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9297 if (oldNetwork == null) {
9298 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9299 return;
9300 }
Chalard Jean49707572019-12-10 21:07:02 +09009301 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009302
9303 // If we get here it means that the last linger timeout for this network expired. So there
9304 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009305 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009306
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009307 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009308 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009309 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009310 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009311 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009312 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009313 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009314 }
9315
James Mattise3ef1912020-12-20 11:09:58 -08009316 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9317 boolean isDefaultChanged = false;
9318 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9319 final NetworkReassignment.RequestReassignment reassignment =
9320 changes.getReassignment(defaultRequestInfo);
9321 if (null == reassignment) {
9322 continue;
9323 }
9324 // reassignment only contains those instances where the satisfying network changed.
9325 isDefaultChanged = true;
9326 // Notify system services of the new default.
9327 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9328 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009329
James Mattise3ef1912020-12-20 11:09:58 -08009330 if (isDefaultChanged) {
9331 // Hold a wakelock for a short time to help apps in migrating to a new default.
9332 scheduleReleaseNetworkTransitionWakelock();
9333 }
9334 }
9335
Aaron Huang9fe47be2021-06-08 13:11:45 +08009336 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9337 if (null == oldDefaultNetwork) return;
9338 // The network stopped being the default. If it was using a PAC proxy, then the
9339 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9340 // to the local proxy server, which would forward them over the newly default network.
9341 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9342 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9343 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9344 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9345 }
9346
James Mattise3ef1912020-12-20 11:09:58 -08009347 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9348 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9349 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9350 if (DBG) {
9351 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9352 }
Chalard Jean8e382112019-12-03 20:45:30 +09009353
James Mattisd31bdfa2020-12-23 16:37:26 -08009354 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9355 if (newDefaultNetwork != null) {
9356 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009357 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009358
James Mattisd31bdfa2020-12-23 16:37:26 -08009359 // Set an app level managed default and return since further processing only applies to the
9360 // default network.
9361 if (mDefaultRequest != nri) {
9362 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9363 return;
9364 }
9365
9366 makeDefaultNetwork(newDefaultNetwork);
9367
James Mattise3ef1912020-12-20 11:09:58 -08009368 if (oldDefaultNetwork != null) {
9369 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9370 }
9371 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009372 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009373 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009374 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009375 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009376 updateTcpBufferSizes(null != newDefaultNetwork
9377 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009378 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009379 }
9380
James Mattisd31bdfa2020-12-23 16:37:26 -08009381 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9382 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9383 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9384 try {
9385 if (VDBG) {
9386 log("Setting default network for " + nri
9387 + " using UIDs " + nri.getUids()
9388 + " with old network " + (oldDefaultNetwork != null
9389 ? oldDefaultNetwork.network().getNetId() : "null")
9390 + " and new network " + (newDefaultNetwork != null
9391 ? newDefaultNetwork.network().getNetId() : "null"));
9392 }
9393 if (nri.getUids().isEmpty()) {
9394 throw new IllegalStateException("makeDefaultForApps called without specifying"
9395 + " any applications to set as the default." + nri);
9396 }
9397 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009398 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009399 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009400 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009401 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009402 }
9403 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009404 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009405 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009406 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009407 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009408 }
9409 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009410 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009411 }
9412 }
9413
Junyu Lai35665cc2022-12-19 17:37:48 +08009414 /**
9415 * Collect restricted uid ranges for the given network and UserHandle, these uids
9416 * are not restricted for matched enterprise networks but being restricted for non-matched
9417 * enterprise networks and non-enterprise networks.
9418 */
9419 @NonNull
9420 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9421 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9422 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9423 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9424 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9425
9426 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9427 // The NC is built from a `ProfileNetworkPreference` which has only one
9428 // enterprise ID, so it's guaranteed to have exactly one.
9429 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9430 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9431 continue;
9432 }
9433 }
9434
9435 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9436 pref.capabilities.getUidRanges())) {
9437 throw new IllegalArgumentException(
9438 "Overlapping uid range in preference: " + pref);
9439 }
9440 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9441 }
9442 return restrictedUidRanges;
9443 }
9444
9445 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009446 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +09009447 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009448
Junyu Lai35665cc2022-12-19 17:37:48 +08009449 ensureRunningOnConnectivityServiceThread();
9450 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9451 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9452 .getUserHandles(true /* excludeDying */);
9453 if (users.isEmpty()) {
9454 throw new IllegalStateException("No user is available");
9455 }
9456
9457 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9458 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9459 for (final UserHandle user : users) {
9460 final ArraySet<UidRange> restrictedUidRanges =
9461 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9462 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9463 UidRange.createForUser(user), restrictedUidRanges));
9464 }
9465
9466 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9467 configs.add(new NativeUidRangeConfig(
9468 nai.network.netId, rangesParcel, 0 /* subPriority */));
9469 }
9470
9471 // The netd API replaces the previous configs with the current configs.
9472 // Thus, for network disconnection or preference removal, no need to
9473 // unset previous config. Instead, collecting all currently needed
9474 // configs and issue to netd.
9475 try {
9476 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9477 } catch (ServiceSpecificException e) {
9478 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009479 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009480 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009481 // Netd died. This will cause a runtime restart anyway.
9482 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009483 }
9484 }
9485
James Mattisd31bdfa2020-12-23 16:37:26 -08009486 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9487 try {
9488 if (null != newDefaultNetwork) {
9489 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9490 } else {
9491 mNetd.networkClearDefault();
9492 }
9493 } catch (RemoteException | ServiceSpecificException e) {
9494 loge("Exception setting default network :" + e);
9495 }
9496 }
9497
Chalard Jean05cbe972019-12-09 11:50:38 +09009498 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009499 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009500 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009501 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009502 processNewlySatisfiedListenRequests(nai);
9503 }
9504
9505 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009506 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9507 if (nri.isMultilayerRequest()) {
9508 continue;
9509 }
9510 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009511 if (!nr.isListen()) continue;
9512 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009513 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009514 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9515 }
9516 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009517 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009518
Chalard Jeancd397a22019-11-22 22:33:33 +09009519 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009520 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9521 if (nri.isMultilayerRequest()) {
9522 continue;
9523 }
9524 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009525 if (!nr.isListen()) continue;
9526 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9527 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009528 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009529 }
9530 }
9531 }
9532
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009533 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009534 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009535 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009536 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009537 @Nullable public final NetworkRequest mOldNetworkRequest;
9538 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009539 @Nullable public final NetworkAgentInfo mOldNetwork;
9540 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009541 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009542 @Nullable final NetworkRequest oldNetworkRequest,
9543 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009544 @Nullable final NetworkAgentInfo oldNetwork,
9545 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009546 mNetworkRequestInfo = networkRequestInfo;
9547 mOldNetworkRequest = oldNetworkRequest;
9548 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009549 mOldNetwork = oldNetwork;
9550 mNewNetwork = newNetwork;
9551 }
Chalard Jean49707572019-12-10 21:07:02 +09009552
9553 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009554 final NetworkRequest requestToShow = null != mNewNetworkRequest
9555 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9556 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009557 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9558 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009559 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009560 }
9561
Chalard Jean46a62372019-12-10 21:25:24 +09009562 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009563
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009564 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009565 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009566 }
9567
9568 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009569 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009570 // The code is never supposed to add two reassignments of the same request. Make
9571 // sure this stays true, but without imposing this expensive check on all
9572 // reassignments on all user devices.
9573 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009574 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009575 throw new IllegalStateException("Trying to reassign ["
9576 + reassignment + "] but already have ["
9577 + existing + "]");
9578 }
9579 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009580 }
Chalard Jean46a62372019-12-10 21:25:24 +09009581 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009582 }
9583
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009584 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009585 // the passed request.
9586 @Nullable
9587 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009588 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009589 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009590 }
9591 return null;
9592 }
Chalard Jean49707572019-12-10 21:07:02 +09009593
9594 public String toString() {
9595 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9596 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009597 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009598 for (final RequestReassignment rr : getRequestReassignments()) {
9599 sj.add(rr.toString());
9600 }
9601 return sj.toString();
9602 }
9603
9604 public String debugString() {
9605 final StringBuilder sb = new StringBuilder();
9606 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009607 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009608 for (final RequestReassignment rr : getRequestReassignments()) {
9609 sb.append("\n ").append(rr);
9610 }
9611 return sb.append("\n").toString();
9612 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009613 }
9614
Chalard Jean24344d72019-12-04 13:32:31 +09009615 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009616 @Nullable final NetworkRequest previousRequest,
9617 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009618 @Nullable final NetworkAgentInfo previousSatisfier,
9619 @Nullable final NetworkAgentInfo newSatisfier,
9620 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009621 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009622 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009623 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009624 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009625 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09009626 }
James Mattisa076c532020-12-02 14:12:41 -08009627 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009628 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009629 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009630 // If this network switch can't be supported gracefully, the request is not
9631 // lingered. This allows letting go of the network sooner to reclaim some
9632 // performance on the new network, since the radio can't do both at the same
9633 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009634 //
9635 // Also don't linger the request if the old network has been destroyed.
9636 // A destroyed network does not provide actual network connectivity, so
9637 // lingering it is not useful. In particular this ensures that a destroyed
9638 // network is outscored by its replacement,
9639 // then it is torn down immediately instead of being lingered, and any apps that
9640 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009641 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9642 }
Chalard Jean24344d72019-12-04 13:32:31 +09009643 } else {
9644 if (VDBG || DDBG) log(" accepting network in place of null");
9645 }
junyulai0ac374f2020-12-14 18:41:52 +08009646
9647 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9648 // and immediately satisfies a request then remove the timer. This will happen for
9649 // all networks except in the case of an underlying network for a VCN.
9650 if (newSatisfier.isNascent()) {
9651 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009652 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009653 }
9654
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009655 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009656 newSatisfier.unlingerRequest(newRequest.requestId);
9657 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009658 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009659 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009660 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009661 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009662 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009663 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009664 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009665 }
James Mattisa076c532020-12-02 14:12:41 -08009666 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009667 }
James Mattisa076c532020-12-02 14:12:41 -08009668 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009669 }
9670
James Mattisa076c532020-12-02 14:12:41 -08009671 /**
9672 * This function is triggered when something can affect what network should satisfy what
9673 * request, and it computes the network reassignment from the passed collection of requests to
9674 * network match to the one that the system should now have. That data is encoded in an
9675 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9676 * satisfier.
9677 *
9678 * After the reassignment is computed, it is applied to the state objects.
9679 *
9680 * @param networkRequests the nri objects to evaluate for possible network reassignment
9681 * @return NetworkReassignment listing of proposed network assignment changes
9682 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009683 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009684 private NetworkReassignment computeNetworkReassignment(
9685 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009686 final NetworkReassignment changes = new NetworkReassignment();
9687
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009688 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009689 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009690 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009691 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009692 }
Chalard Jean857a1712019-12-10 21:08:07 +09009693
James Mattisa076c532020-12-02 14:12:41 -08009694 for (final NetworkRequestInfo nri : networkRequests) {
9695 // Non-multilayer listen requests can be ignored.
9696 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9697 continue;
9698 }
9699 NetworkAgentInfo bestNetwork = null;
9700 NetworkRequest bestRequest = null;
9701 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009702 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009703 // Stop evaluating as the highest possible priority request is satisfied.
9704 if (null != bestNetwork) {
9705 bestRequest = req;
9706 break;
9707 }
9708 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009709 if (null == bestNetwork && isDefaultBlocked(nri)) {
9710 // Remove default networking if disallowed for managed default requests.
9711 bestNetwork = mNoServiceNetwork;
9712 }
9713 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009714 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009715 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009716 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009717 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009718 }
9719 return changes;
9720 }
9721
James Mattisa076c532020-12-02 14:12:41 -08009722 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9723 return new HashSet<>(mNetworkRequests.values());
9724 }
9725
Paul Jensenc88b39b2015-06-16 14:27:36 -04009726 /**
James Mattisa076c532020-12-02 14:12:41 -08009727 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009728 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009729 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009730 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009731 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9732 }
9733
9734 /**
9735 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9736 * being disconnected.
9737 */
9738 private void rematchNetworksAndRequests(
9739 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9740 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009741 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009742 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009743 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009744 final long computed = SystemClock.elapsedRealtime();
9745 applyNetworkReassignment(changes, start);
9746 final long applied = SystemClock.elapsedRealtime();
9747 issueNetworkNeeds();
9748 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009749 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009750 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9751 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009752 log(changes.debugString());
9753 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009754 // Shorter form, only one line of log
9755 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9756 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009757 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009758 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009759
Chalard Jeand7f762d2019-12-10 19:01:29 +09009760 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009761 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009762 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009763
9764 // Since most of the time there are only 0 or 1 background networks, it would probably
9765 // be more efficient to just use an ArrayList here. TODO : measure performance
9766 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9767 for (final NetworkAgentInfo nai : nais) {
9768 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9769 }
9770
Chalard Jeand7f762d2019-12-10 19:01:29 +09009771 // First, update the lists of satisfied requests in the network agents. This is necessary
9772 // because some code later depends on this state to be correct, most prominently computing
9773 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009774 for (final NetworkReassignment.RequestReassignment event :
9775 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009776 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9777 event.mOldNetworkRequest, event.mNewNetworkRequest,
9778 event.mOldNetwork, event.mNewNetwork,
9779 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009780 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009781
James Mattise3ef1912020-12-20 11:09:58 -08009782 // Process default network changes if applicable.
9783 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009784
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009785 // Notify requested networks are available after the default net is switched, but
9786 // before LegacyTypeTracker sends legacy broadcasts
9787 for (final NetworkReassignment.RequestReassignment event :
9788 changes.getRequestReassignments()) {
9789 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009790 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009791 } else {
James Mattisa076c532020-12-02 14:12:41 -08009792 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009793 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009794 }
9795 }
9796
junyulai0ac374f2020-12-14 18:41:52 +08009797 // Update the inactivity state before processing listen callbacks, because the background
9798 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009799 // just yet though, because they have to be sent after the listens are processed to keep
9800 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009801 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009802 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009803 // Rematching may have altered the inactivity state of some networks, so update all
9804 // inactivity timers. updateInactivityState reads the state from the network agent
9805 // and does nothing if the state has not changed : the source of truth is controlled
9806 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9807 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009808 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009809 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009810 }
9811 }
9812
Chalard Jeanb10ab412019-12-11 14:12:30 +09009813 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009814 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009815 // Process listen requests and update capabilities if the background state has
9816 // changed for this network. For consistency with previous behavior, send onLost
9817 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009818 processNewlyLostListenRequests(nai);
9819 if (oldBackground != nai.isBackgroundNetwork()) {
9820 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009821 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009822 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009823 }
9824
junyulai0ac374f2020-12-14 18:41:52 +08009825 for (final NetworkAgentInfo nai : inactiveNetworks) {
9826 // For nascent networks, if connecting with no foreground request, skip broadcasting
9827 // LOSING for backward compatibility. This is typical when mobile data connected while
9828 // wifi connected with mobile data always-on enabled.
9829 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009830 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009831 }
9832
James Mattise3ef1912020-12-20 11:09:58 -08009833 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009834
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009835 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +00009836 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009837 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009838 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009839 // This network has active linger timers and no requests, but is not
9840 // lingering. Linger it.
9841 //
9842 // One way (the only way?) this can happen if this network is unvalidated
9843 // and became unneeded due to another network improving its score to the
9844 // point where this network will no longer be able to satisfy any requests
9845 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009846 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009847 notifyNetworkLosing(nai, now);
9848 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009849 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009850 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009851 teardownUnneededNetwork(nai);
9852 }
9853 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009854 }
9855 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009856
Chalard Jean62edfd82019-12-02 18:39:29 +09009857 /**
9858 * Apply a change in background state resulting from rematching networks with requests.
9859 *
9860 * During rematch, a network may change background states by starting to satisfy or stopping
9861 * to satisfy a foreground request. Listens don't count for this. When a network changes
9862 * background states, its capabilities need to be updated and callbacks fired for the
9863 * capability change.
9864 *
9865 * @param nai The network that changed background states
9866 */
9867 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
9868 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
9869 if (Objects.equals(nai.networkCapabilities, newNc)) return;
9870 updateNetworkPermissions(nai, newNc);
9871 nai.getAndSetNetworkCapabilities(newNc);
9872 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
9873 }
9874
Chalard Jeanf0344532019-11-19 19:23:38 +09009875 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08009876 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009877 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09009878 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
9879 changes.getReassignment(mDefaultRequest);
9880 final NetworkAgentInfo oldDefaultNetwork =
9881 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
9882 final NetworkAgentInfo newDefaultNetwork =
9883 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08009884
Chalard Jean5b409c72021-02-04 13:12:59 +09009885 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009886 // Maintain the illusion : since the legacy API only understands one network at a time,
9887 // if the default network changed, apps should see a disconnected broadcast for the
9888 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009889 if (oldDefaultNetwork != null) {
9890 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9891 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009892 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009893 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009894 // The new default network can be newly null if and only if the old default
9895 // network doesn't satisfy the default request any more because it lost a
9896 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009897 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009898 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009899 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009900 }
9901 }
9902
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009903 // Now that all the callbacks have been sent, send the legacy network broadcasts
9904 // as needed. This is necessary so that legacy requests correctly bind dns
9905 // requests to this network. The legacy users are listening for this broadcast
9906 // and will generally do a dns request so they can ensureRouteToHost and if
9907 // they do that before the callbacks happen they'll use the default network.
9908 //
9909 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
9910 // callbacks, but if apps can receive the broadcast before the callback, they still might
9911 // have an inconsistent view of networking.
9912 //
9913 // This *does* introduce a race where if the user uses the new api
9914 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
9915 // they may get old info. Reverse this after the old startUsing api is removed.
9916 // This is on top of the multiple intent sequencing referenced in the todo above.
9917 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09009918 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009919 addNetworkToLegacyTypeTracker(nai);
9920 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08009921 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009922 }
9923
Chalard Jean0354d8c2021-01-12 10:58:56 +09009924 private void issueNetworkNeeds() {
9925 ensureRunningOnConnectivityServiceThread();
9926 for (final NetworkOfferInfo noi : mNetworkOffers) {
9927 issueNetworkNeeds(noi);
9928 }
9929 }
9930
9931 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
9932 ensureRunningOnConnectivityServiceThread();
9933 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9934 informOffer(nri, noi.offer, mNetworkRanker);
9935 }
9936 }
9937
9938 /**
9939 * Inform a NetworkOffer about any new situation of a request.
9940 *
9941 * This function handles updates to offers. A number of events may happen that require
9942 * updating the registrant for this offer about the situation :
9943 * • The offer itself was updated. This may lead the offer to no longer being able
9944 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
9945 * or conversely being strengthened enough to beat the satisfier (and therefore
9946 * start being needed)
9947 * • The network satisfying a request changed (including cases where the request
9948 * starts or stops being satisfied). The new network may be a stronger or weaker
9949 * match than the old one, possibly affecting whether the offer is needed.
9950 * • The network satisfying a request updated their score. This may lead the offer
9951 * to no longer be able to beat it if the current satisfier got better, or
9952 * conversely start being a good choice if the current satisfier got weaker.
9953 *
9954 * @param nri The request
9955 * @param offer The offer. This may be an updated offer.
9956 */
9957 private static void informOffer(@NonNull NetworkRequestInfo nri,
9958 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9959 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9960 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009961
9962 // Multi-layer requests have a currently active request, the one being satisfied.
9963 // Since the system will try to bring up a better network than is currently satisfying
9964 // the request, NetworkProviders need to be told the offers matching the requests *above*
9965 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9966 // not needed, and the offer is needed for the active request iff the offer can beat
9967 // the satisfier.
9968 // For non-multilayer requests, the logic above gracefully degenerates to only the
9969 // last case.
9970 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9971 // providers that the offer is needed for this request, until the active request is found.
9972 // In a second phase, deal with the currently active request. In a third phase, inform
9973 // the providers that offer is unneeded for the remaining requests.
9974
9975 // First phase : inform providers of all requests above the active request.
9976 int i;
9977 for (i = 0; nri.mRequests.size() > i; ++i) {
9978 final NetworkRequest request = nri.mRequests.get(i);
9979 if (activeRequest == request) break; // Found the active request : go to phase 2
9980 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9981 // Since this request is higher-priority than the one currently satisfied, if the
9982 // offer can satisfy it, the provider should try and bring up the network for sure ;
9983 // no need to even ask the ranker – an offer that can satisfy is always better than
9984 // no network. Hence tell the provider so unless it already knew.
9985 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9986 offer.onNetworkNeeded(request);
9987 }
9988 }
9989
9990 // Second phase : deal with the active request (if any)
9991 if (null != activeRequest && activeRequest.isRequest()) {
9992 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009993 // If an offer can satisfy the request, it is considered needed if it is currently
9994 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009995 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009996 && satisfier.factorySerialNumber == offer.providerId
9997 && activeRequest.canBeSatisfiedBy(offer.caps);
9998 final boolean newNeeded = currentlyServing
9999 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010000 if (newNeeded != oldNeeded) {
10001 if (newNeeded) {
10002 offer.onNetworkNeeded(activeRequest);
10003 } else {
10004 // The offer used to be able to beat the satisfier. Now it can't.
10005 offer.onNetworkUnneeded(activeRequest);
10006 }
10007 }
10008 }
10009
10010 // Third phase : inform the providers that the offer isn't needed for any request
10011 // below the active one.
10012 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10013 final NetworkRequest request = nri.mRequests.get(i);
10014 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10015 // Since this request is lower-priority than the one currently satisfied, if the
10016 // offer can satisfy it, the provider should not try and bring up the network.
10017 // Hence tell the provider so unless it already knew.
10018 if (offer.neededFor(request)) {
10019 offer.onNetworkUnneeded(request);
10020 }
10021 }
10022 }
10023
Chalard Jean61c79252019-11-07 23:07:32 +090010024 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10025 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10026 NetworkRequest nr = nai.requestAt(i);
10027 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10028 // legacy type tracker filters out repeat adds
10029 mLegacyTypeTracker.add(nr.legacyType, nai);
10030 }
10031 }
10032
10033 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010034 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010035 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10036 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10037 if (nai.isVPN()) {
10038 mLegacyTypeTracker.add(TYPE_VPN, nai);
10039 }
10040 }
10041
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010042 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010043 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010044 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010045 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010046 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010047 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010048
Chalard Jean254bd162022-08-25 13:04:51 +090010049 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010050 // Don't repeat publish.
10051 if (newInetCondition == mDefaultInetConditionPublished) return;
10052
10053 mDefaultInetConditionPublished = newInetCondition;
10054 sendInetConditionBroadcast(nai.networkInfo);
10055 }
10056
Chalard Jeand61375d2020-01-14 22:46:36 +090010057 @NonNull
10058 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10059 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010060 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010061 final boolean suspended =
10062 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10063 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10064 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10065 // state. This is because the network could have been suspended before connecting,
10066 // or it could be disconnecting while being suspended, and in both these cases
10067 // the state should not be overridden. Note that the only detailed state that
10068 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10069 // worry about multiple different substates of CONNECTED.
10070 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10071 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010072 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10073 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10074 // network agent is created, then goes to suspended, then goes out of suspended without
10075 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010076 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010077 ? NetworkInfo.DetailedState.CONNECTED
10078 : NetworkInfo.DetailedState.CONNECTING,
10079 info.getReason(),
10080 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010081 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010082 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010083 return newInfo;
10084 }
10085
10086 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10087 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10088
Erik Kline99f301b2017-02-15 19:59:17 +090010089 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010090 NetworkInfo oldInfo = null;
10091 synchronized (networkAgent) {
10092 oldInfo = networkAgent.networkInfo;
10093 networkAgent.networkInfo = newInfo;
10094 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010095
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010096 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010097 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10098 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010099 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010100
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010101 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010102 // A network that has just connected has zero requests and is thus a foreground network.
10103 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10104
Luke Huangfdd11f82019-04-09 18:41:49 +080010105 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010106
10107 networkAgent.setCreated();
10108
10109 // If the network is created immediately on register, then apply the LinkProperties now.
10110 // Otherwise, this is done further down when the network goes into connected state.
10111 // Applying the LinkProperties means that the network is ready to carry traffic -
10112 // interfaces and routing rules have been added, DNS servers programmed, etc.
10113 // For VPNs, this must be done before the capabilities are updated, because as soon as
10114 // that happens, UIDs are routed to the network.
10115 if (shouldCreateNetworksImmediately()) {
10116 applyInitialLinkProperties(networkAgent);
10117 }
10118
10119 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10120 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010121 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010122 // Initialize the network's capabilities to their starting values according to the
10123 // underlying networks. This ensures that the capabilities are correct before
10124 // anything happens to the network.
10125 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010126 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010127 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010128 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010129 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010130 }
10131
Chalard Jean254bd162022-08-25 13:04:51 +090010132 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10133 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010134
lucaslin45e639b2019-04-03 17:09:28 +080010135 // NetworkCapabilities need to be set before sending the private DNS config to
10136 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010137 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10138
Erik Kline9a62f012018-03-21 07:18:33 -070010139 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010140 if (!shouldCreateNetworksImmediately()) {
10141 applyInitialLinkProperties(networkAgent);
10142 } else {
10143 // The network was created when the agent registered, and the LinkProperties are
10144 // already up-to-date. However, updateLinkProperties also makes some changes only
10145 // when the network connects. Apply those changes here. On T and below these are
10146 // handled by the applyInitialLinkProperties call just above.
10147 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10148 // If something depends on both LinkProperties and connected state, it should be in
10149 // this method as well.
10150 networkAgent.clatd.update();
10151 updateProxy(networkAgent.linkProperties, null);
10152 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010153
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010154 // If a rate limit has been configured and is applicable to this network (network
10155 // provides internet connectivity), apply it. The tc police filter cannot be attached
10156 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
10157 // updateInterfaces -> INetd#networkAddInterface.
10158 // Note: in case of a system server crash, the NetworkController constructor in netd
10159 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10160 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10161 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10162 mIngressRateLimit);
10163 }
10164
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010165 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10166 // command must be sent after updating LinkProperties to maximize chances of
10167 // NetworkMonitor seeing the correct LinkProperties when starting.
10168 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010169 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010170 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010171 }
Chalard Jeand4900722022-02-06 12:25:38 +090010172 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10173 params.networkAgentConfig = networkAgent.networkAgentConfig;
10174 params.networkCapabilities = networkAgent.networkCapabilities;
10175 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10176 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010177 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10178 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10179 // call that would cause a Log.wtf to be emitted from the system_server process, and
10180 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10181 // process to check the interface version, just use an SDK check. NetworkStack will
10182 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010183 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010184 networkAgent.networkMonitor().notifyNetworkConnected(params);
10185 } else {
10186 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10187 params.networkCapabilities);
10188 }
Chalard Jean0f141332023-06-05 19:26:17 +090010189 final long evaluationDelay;
10190 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10191 // If the network is anything other than pure wifi, use the default timeout.
10192 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10193 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10194 // If the network is explicitly selected, use the default timeout because it's
10195 // shorter and the user is likely staring at the screen expecting it to validate
10196 // right away.
10197 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10198 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10199 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10200 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10201 } else {
10202 // It's wifi, automatically connected, and bad wifi is preferred : use the
10203 // longer timeout to avoid the device switching to captive portals with bad
10204 // signal or very slow response.
10205 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10206 }
10207 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010208
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010209 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10210 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10211 // capabilities, so it only needs to be done once on initial connect, not every time the
10212 // network's capabilities change. Note that we do this before rematching the network,
10213 // so we could decide to tear it down immediately afterwards. That's fine though - on
10214 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10215 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010216 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010217
junyulai0ac374f2020-12-14 18:41:52 +080010218 // Before first rematching networks, put an inactivity timer without any request, this
10219 // allows {@code updateInactivityState} to update the state accordingly and prevent
10220 // tearing down for any {@code unneeded} evaluation in this period.
10221 // Note that the timer will not be rescheduled since the expiry time is
10222 // fixed after connection regardless of the network satisfying other requests or not.
10223 // But it will be removed as soon as the network satisfies a request for the first time.
10224 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10225 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010226 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010227
Paul Jensen05e85ee2014-09-11 11:00:39 -040010228 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010229 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010230
10231 // This has to happen after matching the requests, because callbacks are just requests.
10232 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010233 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010234 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010235 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010236 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010237 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010238 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010239 if (networkAgent.isVPN()) {
10240 // As the active or bound network changes for apps, broadcast the default proxy, as
10241 // apps may need to update their proxy data. This is called after disconnecting from
10242 // VPN to make sure we do not broadcast the old proxy data.
10243 // TODO(b/122649188): send the broadcast only to VPN users.
10244 mProxyTracker.sendProxyBroadcast();
10245 }
Chalard Jean254bd162022-08-25 13:04:51 +090010246 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10247 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010248 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010249 }
10250 }
10251
Chalard Jean28018572020-12-21 18:36:52 +090010252 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010253 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10254 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010255 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010256 }
10257
Erik Kline99f301b2017-02-15 19:59:17 +090010258 // Notify only this one new request of the current state. Transfer all the
10259 // current state by calling NetworkCapabilities and LinkProperties callbacks
10260 // so that callers can be guaranteed to have as close to atomicity in state
10261 // transfer as can be supported by this current API.
10262 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010263 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010264 if (nri.mPendingIntent != null) {
10265 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10266 // Attempt no subsequent state pushes where intents are involved.
10267 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010268 }
Erik Kline99f301b2017-02-15 19:59:17 +090010269
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010270 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010271 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010272 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10273 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10274 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010275 }
10276
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010277 // Notify the requests on this NAI that the network is now lingered.
10278 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010279 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010280 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10281 }
10282
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010283 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10284 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10285 return vpnBlocked
10286 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10287 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10288 }
10289
10290 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10291 if (blockedReasons == BLOCKED_REASON_NONE) {
10292 mUidBlockedReasons.delete(uid);
10293 } else {
10294 mUidBlockedReasons.put(uid, blockedReasons);
10295 }
10296 }
10297
junyulaif2c67e42018-08-07 19:50:45 +080010298 /**
10299 * Notify of the blocked state apps with a registered callback matching a given NAI.
10300 *
10301 * Unlike other callbacks, blocked status is different between each individual uid. So for
10302 * any given nai, all requests need to be considered according to the uid who filed it.
10303 *
10304 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010305 * @param oldMetered True if the previous network capabilities were metered.
10306 * @param newMetered True if the current network capabilities are metered.
10307 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10308 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010309 */
10310 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010311 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10312 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010313
10314 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10315 NetworkRequest nr = nai.requestAt(i);
10316 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010317
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010318 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10319 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10320 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010321 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010322 : oldVpnBlocked;
10323
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010324 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10325 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10326 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010327 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010328 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010329 }
10330 }
10331 }
10332
10333 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010334 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010335 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010336 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010337 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010338 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010339 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010340 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010341 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010342
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010343 final int oldBlockedState = getBlockedState(
10344 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10345 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10346 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010347 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010348 }
junyulaif2c67e42018-08-07 19:50:45 +080010349 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10350 NetworkRequest nr = nai.requestAt(i);
10351 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010352 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010353 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10354 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010355 }
10356 }
10357 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010358 }
10359
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010360 @VisibleForTesting
10361 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010362 // The NetworkInfo we actually send out has no bearing on the real
10363 // state of affairs. For example, if the default connection is mobile,
10364 // and a request for HIPRI has just gone away, we need to pretend that
10365 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10366 // the state to DISCONNECTED, even though the network is of type MOBILE
10367 // and is still connected.
10368 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10369 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010370 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010371 if (state != DetailedState.DISCONNECTED) {
10372 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010373 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010374 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010375 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010376 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10377 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10378 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10379 if (info.isFailover()) {
10380 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10381 nai.networkInfo.setFailover(false);
10382 }
10383 if (info.getReason() != null) {
10384 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10385 }
10386 if (info.getExtraInfo() != null) {
10387 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10388 }
10389 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010390 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010391 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010392 if (newDefaultAgent != null) {
10393 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10394 newDefaultAgent.networkInfo);
10395 } else {
10396 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10397 }
10398 }
10399 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10400 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010401 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010402 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010403 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010404 }
10405 }
10406 }
10407
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010408 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010409 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010410 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010411 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010412 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010413 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10414 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010415 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10416 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010417 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010418 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010419 } else {
10420 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10421 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010422 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010423 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010424
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010425 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10426 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10427 }
10428
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010429 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010430 * Returns the list of all interfaces that could be used by network traffic that does not
10431 * explicitly specify a network. This includes the default network, but also all VPNs that are
10432 * currently connected.
10433 *
10434 * Must be called on the handler thread.
10435 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010436 @NonNull
10437 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010438 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010439 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010440 final Set<Integer> activeNetIds = new ArraySet<>();
10441 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10442 if (nri.isBeingSatisfied()) {
10443 activeNetIds.add(nri.getSatisfier().network().netId);
10444 }
10445 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010446 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010447 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010448 defaultNetworks.add(nai.network);
10449 }
10450 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010451 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010452 }
10453
10454 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010455 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10456 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010457 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010458 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010459 ensureRunningOnConnectivityServiceThread();
10460 String activeIface = null;
10461 LinkProperties activeLinkProperties = getActiveLinkProperties();
10462 if (activeLinkProperties != null) {
10463 activeIface = activeLinkProperties.getInterfaceName();
10464 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010465
junyulai2050bed2021-01-23 09:46:34 +080010466 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010467 try {
junyulaide41fc22021-01-22 22:46:01 +080010468 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010469 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010470 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10471 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010472 } catch (Exception ignored) {
10473 }
10474 }
10475
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010476 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010477 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010478 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010479 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010480 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010481
10482 if (!TextUtils.isEmpty(settingUrl)) {
10483 return settingUrl;
10484 }
10485
10486 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010487 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010488 if (!TextUtils.isEmpty(settingUrl)) {
10489 return settingUrl;
10490 }
10491
10492 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010493 }
10494
10495 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010496 public void startNattKeepalive(Network network, int intervalSeconds,
10497 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010498 enforceKeepalivePermission();
10499 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010500 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010501 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10502 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010503 // false and set the underpinned network to null because there is no way and no
10504 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10505 // deprecated method.
10506 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010507 }
10508
10509 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010510 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010511 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010512 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010513 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010514 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010515 mKeepaliveTracker.startNattKeepalive(
10516 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010517 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10518 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010519 } finally {
10520 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10521 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010522 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10523 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010524 }
10525 }
junyulaid05a1922019-01-15 11:32:44 +080010526 }
10527
10528 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010529 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010530 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010531 try {
10532 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010533 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010534 mKeepaliveTracker.startTcpKeepalive(
10535 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10536 } finally {
10537 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10538 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010539 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10540 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010541 }
10542 }
junyulai0835a1e2019-01-08 20:04:33 +080010543 }
10544
10545 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010546 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010547 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010548 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10549 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010550 }
10551
10552 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090010553 public int[] getSupportedKeepalives() {
10554 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10555 // Backwards compatibility with CTS 13
10556 android.Manifest.permission.QUERY_ALL_PACKAGES);
10557
10558 return BinderUtils.withCleanCallingIdentity(() ->
10559 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10560 }
10561
10562 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010563 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010564 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010565
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010566 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010567 final long token = Binder.clearCallingIdentity();
10568 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010569 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10570 UserHandle.getUserHandleForUid(uid))) {
10571 return;
10572 }
10573
Heemin Seogdb8489d2019-06-12 09:21:44 -070010574 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10575 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010576
10577 // Turn airplane mode off
10578 setAirplaneMode(false);
10579
10580 // restore private DNS settings to default mode (opportunistic)
10581 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10582 UserHandle.getUserHandleForUid(uid))) {
10583 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10584 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10585 }
10586
10587 Settings.Global.putString(mContext.getContentResolver(),
10588 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010589 } finally {
10590 Binder.restoreCallingIdentity(token);
10591 }
Stuart Scottd5463642015-04-02 18:00:02 -070010592 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010593
Ricky Wai7097cc92018-01-23 04:09:45 +000010594 @Override
10595 public byte[] getNetworkWatchlistConfigHash() {
10596 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10597 if (nwm == null) {
10598 loge("Unable to get NetworkWatchlistManager");
10599 return null;
10600 }
10601 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10602 return nwm.getWatchlistConfigHash();
10603 }
10604
Hugo Benichibe0c7652016-05-31 16:28:06 +090010605 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010606 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010607 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010608 }
Hugo Benichif4210292017-04-21 15:07:12 +090010609
10610 private static boolean toBool(int encodedBoolean) {
10611 return encodedBoolean != 0; // Only 0 means false.
10612 }
10613
10614 private static int encodeBool(boolean b) {
10615 return b ? 1 : 0;
10616 }
mswest4632928412018-03-12 10:34:34 -070010617
10618 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010619 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10620 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10621 @NonNull String[] args) {
10622 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10623 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010624 }
10625
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010626 private Boolean parseBooleanArgument(final String arg) {
10627 if ("true".equals(arg)) {
10628 return true;
10629 } else if ("false".equals(arg)) {
10630 return false;
10631 } else {
10632 return null;
10633 }
10634 }
10635
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010636 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010637 @Override
10638 public int onCommand(String cmd) {
10639 if (cmd == null) {
10640 return handleDefaultCommands(cmd);
10641 }
10642 final PrintWriter pw = getOutPrintWriter();
10643 try {
10644 switch (cmd) {
10645 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010646 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
10647 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070010648 final String action = getNextArg();
10649 if ("enable".equals(action)) {
10650 setAirplaneMode(true);
10651 return 0;
10652 } else if ("disable".equals(action)) {
10653 setAirplaneMode(false);
10654 return 0;
10655 } else if (action == null) {
10656 final ContentResolver cr = mContext.getContentResolver();
10657 final int enabled = Settings.Global.getInt(cr,
10658 Settings.Global.AIRPLANE_MODE_ON);
10659 pw.println(enabled == 0 ? "disabled" : "enabled");
10660 return 0;
10661 } else {
10662 onHelp();
10663 return -1;
10664 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010665 case "set-chain3-enabled": {
10666 final Boolean enabled = parseBooleanArgument(getNextArg());
10667 if (null == enabled) {
10668 onHelp();
10669 return -1;
10670 }
10671 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
10672 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
10673 enabled);
10674 return 0;
10675 }
10676 case "get-chain3-enabled": {
10677 final boolean chainEnabled = getFirewallChainEnabled(
10678 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
10679 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
10680 return 0;
10681 }
10682 case "set-package-networking-enabled": {
10683 final Boolean enabled = parseBooleanArgument(getNextArg());
10684 final String packageName = getNextArg();
10685 if (null == enabled || null == packageName) {
10686 onHelp();
10687 return -1;
10688 }
10689 // Throws NameNotFound if the package doesn't exist.
10690 final int appId = setPackageFirewallRule(
10691 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
10692 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
10693 final String msg = (enabled ? "Enabled" : "Disabled")
10694 + " networking for " + packageName + ", appId " + appId;
10695 Log.i(TAG, msg);
10696 pw.println(msg);
10697 return 0;
10698 }
10699 case "get-package-networking-enabled": {
10700 final String packageName = getNextArg();
10701 final int rule = getPackageFirewallRule(
10702 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
10703 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
10704 pw.println(packageName + ":" + "allow");
10705 } else if (FIREWALL_RULE_DENY == rule) {
10706 pw.println(packageName + ":" + "deny");
10707 } else {
10708 throw new IllegalStateException("Unknown rule " + rule + " for package "
10709 + packageName);
10710 }
10711 return 0;
10712 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010713 case "reevaluate":
10714 // Usage : adb shell cmd connectivity reevaluate <netId>
10715 // If netId is omitted, then reevaluate the default network
10716 final String netId = getNextArg();
10717 final NetworkAgentInfo nai;
10718 if (null == netId) {
10719 // Note that the command is running on the wrong thread to call this,
10720 // so this could in principle return stale data. But it can't crash.
10721 nai = getDefaultNetwork();
10722 } else {
10723 // If netId can't be parsed, this throws NumberFormatException, which
10724 // is passed back to adb who prints it.
10725 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10726 }
10727 if (null == nai) {
10728 pw.println("Unknown network (net ID not found or no default network)");
10729 return 0;
10730 }
10731 Log.d(TAG, "Reevaluating network " + nai.network);
10732 reportNetworkConnectivity(nai.network, !nai.isValidated());
10733 return 0;
mswest4632928412018-03-12 10:34:34 -070010734 default:
10735 return handleDefaultCommands(cmd);
10736 }
10737 } catch (Exception e) {
10738 pw.println(e);
10739 }
10740 return -1;
10741 }
10742
10743 @Override
10744 public void onHelp() {
10745 PrintWriter pw = getOutPrintWriter();
10746 pw.println("Connectivity service commands:");
10747 pw.println(" help");
10748 pw.println(" Print this help text.");
10749 pw.println(" airplane-mode [enable|disable]");
10750 pw.println(" Turn airplane mode on or off.");
10751 pw.println(" airplane-mode");
10752 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010753 pw.println(" set-chain3-enabled [true|false]");
10754 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
10755 pw.println(" get-chain3-enabled");
10756 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
10757 pw.println(" set-package-networking-enabled [true|false] [package name]");
10758 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
10759 + " no effect if the chain is disabled.");
10760 pw.println(" get-package-networking-enabled [package name]");
10761 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
mswest4632928412018-03-12 10:34:34 -070010762 }
10763 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010764
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010765 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010766 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10767 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10768 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010769 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010770 }
10771
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010772 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10773 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010774 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10775 final TransportInfo newInfo = nc.getTransportInfo();
10776 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10777 return;
10778 }
10779 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010780 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010781 }
10782 }
10783
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010784 /**
10785 * @param connectionInfo the connection to resolve.
10786 * @return {@code uid} if the connection is found and the app has permission to observe it
10787 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10788 * connection is not found.
10789 */
10790 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010791 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10792 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10793 }
10794
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010795 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010796 connectionInfo.local, connectionInfo.remote);
10797
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010798 if (uid == INVALID_UID) return uid; // Not found.
10799
10800 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10801 // VPN, if any, that applies to the UID that owns the connection.
10802 if (checkNetworkStackPermission()) return uid;
10803
10804 final NetworkAgentInfo vpn = getVpnForUid(uid);
10805 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010806 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010807 return INVALID_UID;
10808 }
10809
10810 return uid;
10811 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010812
Benedict Wong493e04b2018-11-09 14:45:34 -080010813 /**
10814 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10815 *
10816 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10817 */
10818 @Override
10819 public IBinder startOrGetTestNetworkService() {
10820 synchronized (mTNSLock) {
10821 TestNetworkService.enforceTestNetworkPermissions(mContext);
10822
10823 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010824 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010825 }
10826
10827 return mTNS;
10828 }
10829 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010830
Cody Kesting73708bf2019-12-18 10:57:50 -080010831 /**
10832 * Handler used for managing all Connectivity Diagnostics related functions.
10833 *
10834 * @see android.net.ConnectivityDiagnosticsManager
10835 *
10836 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10837 */
10838 @VisibleForTesting
10839 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010840 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10841
Cody Kesting73708bf2019-12-18 10:57:50 -080010842 /**
10843 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10844 * android.net.ConnectivityDiagnosticsManager}.
10845 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10846 * NetworkRequestInfo to be registered
10847 */
10848 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10849
10850 /**
10851 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10852 * android.net.ConnectivityDiagnosticsManager}.
10853 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10854 * arg1 = the uid of the caller
10855 */
10856 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10857
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010858 /**
10859 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010860 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010861 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10862 * NetworkMonitor.
10863 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010864 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010865 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010866
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010867 /**
10868 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10869 * been detected on the network.
10870 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10871 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10872 * arg2 = NetID.
10873 * data = PersistableBundle of extras passed from NetworkMonitor.
10874 */
10875 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10876
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010877 /**
10878 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10879 * the platform. This event will invoke {@link
10880 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10881 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070010882 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010883 */
10884 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
10885
Cody Kesting73708bf2019-12-18 10:57:50 -080010886 private ConnectivityDiagnosticsHandler(Looper looper) {
10887 super(looper);
10888 }
10889
10890 @Override
10891 public void handleMessage(Message msg) {
10892 switch (msg.what) {
10893 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10894 handleRegisterConnectivityDiagnosticsCallback(
10895 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
10896 break;
10897 }
10898 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10899 handleUnregisterConnectivityDiagnosticsCallback(
10900 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
10901 break;
10902 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010903 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010904 final ConnectivityReportEvent reportEvent =
10905 (ConnectivityReportEvent) msg.obj;
10906
Aaron Huang959d3642021-01-21 15:47:41 +080010907 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010908 break;
10909 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010910 case EVENT_DATA_STALL_SUSPECTED: {
10911 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080010912 final Pair<Long, PersistableBundle> arg =
10913 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010914 if (nai == null) break;
10915
Aaron Huang959d3642021-01-21 15:47:41 +080010916 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010917 break;
10918 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010919 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070010920 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010921 break;
10922 }
10923 default: {
10924 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
10925 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010926 }
10927 }
10928 }
10929
10930 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
10931 @VisibleForTesting
10932 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
10933 @NonNull private final IConnectivityDiagnosticsCallback mCb;
10934 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010935 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010936
10937 @VisibleForTesting
10938 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010939 @NonNull IConnectivityDiagnosticsCallback cb,
10940 @NonNull NetworkRequestInfo nri,
10941 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010942 mCb = cb;
10943 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010944 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010945 }
10946
10947 @Override
10948 public void binderDied() {
10949 log("ConnectivityDiagnosticsCallback IBinder died.");
10950 unregisterConnectivityDiagnosticsCallback(mCb);
10951 }
10952 }
10953
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010954 /**
10955 * Class used for sending information from {@link
10956 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
10957 */
10958 private static class NetworkTestedResults {
10959 private final int mNetId;
10960 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010961 @Nullable private final String mRedirectUrl;
10962
10963 private NetworkTestedResults(
10964 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
10965 mNetId = netId;
10966 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010967 mRedirectUrl = redirectUrl;
10968 }
10969 }
10970
10971 /**
10972 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
10973 * ConnectivityDiagnosticsHandler}.
10974 */
10975 private static class ConnectivityReportEvent {
10976 private final long mTimestampMillis;
10977 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080010978 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010979
Aaron Huang959d3642021-01-21 15:47:41 +080010980 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
10981 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010982 mTimestampMillis = timestampMillis;
10983 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080010984 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010985 }
10986 }
10987
Cody Kestingf1120be2020-08-03 18:01:40 -070010988 /**
10989 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
10990 * ConnectivityDiagnosticsHandler}.
10991 */
10992 private static class ReportedNetworkConnectivityInfo {
10993 public final boolean hasConnectivity;
10994 public final boolean isNetworkRevalidating;
10995 public final int reporterUid;
10996 @NonNull public final NetworkAgentInfo nai;
10997
10998 private ReportedNetworkConnectivityInfo(
10999 boolean hasConnectivity,
11000 boolean isNetworkRevalidating,
11001 int reporterUid,
11002 @NonNull NetworkAgentInfo nai) {
11003 this.hasConnectivity = hasConnectivity;
11004 this.isNetworkRevalidating = isNetworkRevalidating;
11005 this.reporterUid = reporterUid;
11006 this.nai = nai;
11007 }
11008 }
11009
Cody Kesting73708bf2019-12-18 10:57:50 -080011010 private void handleRegisterConnectivityDiagnosticsCallback(
11011 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11012 ensureRunningOnConnectivityServiceThread();
11013
11014 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011015 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011016 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11017
James Mattis64b8b0f2020-11-24 17:40:49 -080011018 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11019 // confusing for these networks to change when an NRI is satisfied in another layer.
11020 if (nri.isMultilayerRequest()) {
11021 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11022 + "network requests.");
11023 }
11024
Cody Kesting73708bf2019-12-18 10:57:50 -080011025 // This means that the client registered the same callback multiple times. Do
11026 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011027 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011028 if (VDBG) log("Diagnostics callback is already registered");
11029
11030 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11031 // incremented when the NetworkRequestInfo is created as part of
11032 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011033 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011034 return;
11035 }
11036
Cody Kesting31f1ff62020-03-05 10:46:02 -080011037 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011038
11039 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011040 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011041 } catch (RemoteException e) {
11042 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011043 return;
11044 }
11045
11046 // Once registered, provide ConnectivityReports for matching Networks
11047 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11048 synchronized (mNetworkForNetId) {
11049 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11050 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011051 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11052 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011053 matchingNetworks.add(nai);
11054 }
11055 }
11056 }
11057 for (final NetworkAgentInfo nai : matchingNetworks) {
11058 final ConnectivityReport report = nai.getConnectivityReport();
11059 if (report == null) {
11060 continue;
11061 }
11062 if (!checkConnectivityDiagnosticsPermissions(
11063 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11064 continue;
11065 }
11066
11067 try {
11068 cb.onConnectivityReportAvailable(report);
11069 } catch (RemoteException e) {
11070 // Exception while sending the ConnectivityReport. Move on to the next network.
11071 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011072 }
11073 }
11074
11075 private void handleUnregisterConnectivityDiagnosticsCallback(
11076 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11077 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011078 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011079
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011080 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11081 mConnectivityDiagnosticsCallbacks.remove(iCb);
11082 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011083 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11084 return;
11085 }
11086
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011087 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011088
Cody Kesting70fa2b22020-12-02 12:16:56 -080011089 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11090 // (if the Binder died)
11091 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11092 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011093 return;
11094 }
11095
Cody Kesting46cb1672020-03-04 13:35:20 -080011096 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11097 // incremented when the NetworkRequestInfo is created as part of
11098 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011099 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011100
Cody Kesting31f1ff62020-03-05 10:46:02 -080011101 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011102 }
11103
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011104 private void handleNetworkTestedWithExtras(
11105 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11106 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011107 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011108 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011109 final ConnectivityReport report =
11110 new ConnectivityReport(
11111 reportEvent.mNai.network,
11112 reportEvent.mTimestampMillis,
11113 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011114 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011115 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011116 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011117
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011118 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011119 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011120 for (final IConnectivityDiagnosticsCallback cb : results) {
11121 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011122 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011123 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011124 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011125 }
11126 }
11127 }
11128
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011129 private void handleDataStallSuspected(
11130 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11131 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011132 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011133 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011134 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011135 new DataStallReport(
11136 nai.network,
11137 timestampMillis,
11138 detectionMethod,
11139 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011140 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011141 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011142 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011143 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011144 for (final IConnectivityDiagnosticsCallback cb : results) {
11145 try {
11146 cb.onDataStallSuspected(report);
11147 } catch (RemoteException ex) {
11148 loge("Error invoking onDataStallSuspected", ex);
11149 }
11150 }
11151 }
11152
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011153 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011154 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11155 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11156 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11157
11158 // If the Network is being re-validated as a result of this call to
11159 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11160 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011161 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011162 getMatchingPermissionedCallbacks(
11163 nai,
11164 reportedNetworkConnectivityInfo.isNetworkRevalidating
11165 ? Process.INVALID_UID
11166 : reportedNetworkConnectivityInfo.reporterUid);
11167
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011168 for (final IConnectivityDiagnosticsCallback cb : results) {
11169 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011170 cb.onNetworkConnectivityReported(
11171 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011172 } catch (RemoteException ex) {
11173 loge("Error invoking onNetworkConnectivityReported", ex);
11174 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011175
11176 // If the Network isn't re-validating, also provide the cached report. If there is no
11177 // cached report, the Network is still being validated and a report will be sent once
11178 // validation is complete. Note that networks which never undergo validation will still
11179 // have a cached ConnectivityReport with RESULT_SKIPPED.
11180 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11181 try {
11182 cb.onConnectivityReportAvailable(cachedReport);
11183 } catch (RemoteException ex) {
11184 loge("Error invoking onConnectivityReportAvailable", ex);
11185 }
11186 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011187 }
11188 }
11189
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011190 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011191 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11192 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011193 sanitized.setUids(null);
11194 sanitized.setAdministratorUids(new int[0]);
11195 sanitized.setOwnerUid(Process.INVALID_UID);
11196 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011197 }
11198
Cody Kestingf1120be2020-08-03 18:01:40 -070011199 /**
11200 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11201 *
11202 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11203 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011204 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011205 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011206 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011207 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011208 mConnectivityDiagnosticsCallbacks.entrySet()) {
11209 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11210 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011211
James Mattis64b8b0f2020-11-24 17:40:49 -080011212 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011213 if (!nai.satisfies(nri.mRequests.get(0))) {
11214 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011215 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011216
11217 // UID for this callback must either be:
11218 // - INVALID_UID (which sends callbacks to all UIDs), or
11219 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11220 // notified as a result)
11221 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11222 continue;
11223 }
11224
11225 if (!checkConnectivityDiagnosticsPermissions(
11226 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11227 continue;
11228 }
11229
11230 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011231 }
11232 return results;
11233 }
11234
Cody Kesting7474f672021-05-11 14:22:40 -070011235 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11236 @NonNull NetworkAgentInfo nai) {
11237 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11238 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11239 }
11240
Cody Kesting160ef392021-05-05 13:17:22 -070011241 private boolean hasLocationPermission(String packageName, int uid) {
11242 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11243 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11244 // call in a try-catch.
11245 try {
11246 if (!mLocationPermissionChecker.checkLocationPermission(
11247 packageName, null /* featureId */, uid, null /* message */)) {
11248 return false;
11249 }
11250 } catch (SecurityException e) {
11251 return false;
11252 }
11253
11254 return true;
11255 }
11256
11257 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11258 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011259 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011260 && virtual.networkCapabilities.getOwnerUid() == uid
11261 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11262 return true;
11263 }
11264 }
11265
11266 return false;
11267 }
11268
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011269 @VisibleForTesting
11270 boolean checkConnectivityDiagnosticsPermissions(
11271 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
11272 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
11273 return true;
11274 }
11275
Cody Kesting160ef392021-05-05 13:17:22 -070011276 // Administrator UIDs also contains the Owner UID
11277 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11278 if (!CollectionUtils.contains(administratorUids, callbackUid)
11279 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011280 return false;
11281 }
11282
Cody Kesting7474f672021-05-11 14:22:40 -070011283 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11284 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011285 }
11286
Cody Kestingd199a9d2019-12-17 12:55:28 -080011287 @Override
11288 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011289 @NonNull IConnectivityDiagnosticsCallback callback,
11290 @NonNull NetworkRequest request,
11291 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011292 Objects.requireNonNull(callback, "callback must not be null");
11293 Objects.requireNonNull(request, "request must not be null");
11294 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11295
Cody Kesting73708bf2019-12-18 10:57:50 -080011296 if (request.legacyType != TYPE_NONE) {
11297 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11298 + " Please use NetworkCapabilities instead.");
11299 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011300 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011301 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011302
11303 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11304 // and administrator uids to be safe.
11305 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011306 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011307
11308 final NetworkRequest requestWithId =
11309 new NetworkRequest(
11310 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11311
11312 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11313 //
11314 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11315 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11316 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011317 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011318 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011319 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011320
11321 mConnectivityDiagnosticsHandler.sendMessage(
11322 mConnectivityDiagnosticsHandler.obtainMessage(
11323 ConnectivityDiagnosticsHandler
11324 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11325 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011326 }
11327
11328 @Override
11329 public void unregisterConnectivityDiagnosticsCallback(
11330 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011331 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011332 mConnectivityDiagnosticsHandler.sendMessage(
11333 mConnectivityDiagnosticsHandler.obtainMessage(
11334 ConnectivityDiagnosticsHandler
11335 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011336 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011337 0,
11338 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011339 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011340
Yan Yanfe96dde2022-12-05 23:00:01 +000011341 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11342 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11343 if (underlyingNetworks == null) return false;
11344
11345 for (Network network : underlyingNetworks) {
11346 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11347 return true;
11348 }
11349 }
11350 return false;
11351 }
11352
Cody Kestingf53a0752020-04-15 12:33:28 -070011353 @Override
11354 public void simulateDataStall(int detectionMethod, long timestampMillis,
11355 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011356 Objects.requireNonNull(network, "network must not be null");
11357 Objects.requireNonNull(extras, "extras must not be null");
11358
paulhu3ffffe72021-09-16 10:15:22 +080011359 enforceAnyPermissionOf(mContext,
11360 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011361 android.Manifest.permission.NETWORK_STACK);
11362 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011363 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11364 throw new SecurityException(
11365 "Data Stall simulation is only possible for test networks or networks built on"
11366 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011367 }
11368
11369 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011370 if (nai == null
11371 || (nai.creatorUid != mDeps.getCallingUid()
11372 && nai.creatorUid != Process.SYSTEM_UID)) {
11373 throw new SecurityException(
11374 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011375 }
11376
Cody Kesting652e3ec2020-05-21 12:08:21 -070011377 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11378 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11379 // Data Stall information as a DataStallReportParcelable and passing to
11380 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11381 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011382 final DataStallReportParcelable p = new DataStallReportParcelable();
11383 p.timestampMillis = timestampMillis;
11384 p.detectionMethod = detectionMethod;
11385
11386 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11387 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11388 }
11389 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11390 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11391 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11392 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11393 }
11394
Serik Beketayevec8ad212020-12-07 22:43:07 -080011395 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011396 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011397
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011398 /**
11399 * Class to hold the information for network activity change event from idle timers
11400 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
11401 */
11402 private static final class NetworkActivityParams {
11403 public final boolean isActive;
11404 // Label used for idle timer. Transport type is used as label.
11405 // label is int since NMS was using the identifier as int, and it has not been changed
11406 public final int label;
11407 public final long timestampNs;
11408 // Uid represents the uid that was responsible for waking the radio.
11409 // -1 for no uid and uid is -1 if isActive is false.
11410 public final int uid;
11411
11412 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
11413 this.isActive = isActive;
11414 this.label = label;
11415 this.timestampNs = timestampNs;
11416 this.uid = uid;
11417 }
11418 }
11419
lucaslin66f44212021-02-23 01:12:55 +080011420 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11421 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011422 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080011423 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011424 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
11425 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080011426 }
lucaslin37a16d92021-01-21 19:48:09 +080011427
11428 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011429 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011430 mHandler.post(() -> {
11431 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011432 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011433 }
11434 });
lucaslin37a16d92021-01-21 19:48:09 +080011435 }
11436
11437 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011438 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011439 mHandler.post(() -> {
11440 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011441 nai.clatd.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011442 }
11443 });
lucaslin66f44212021-02-23 01:12:55 +080011444 }
11445 }
11446
lucaslin1a8b4c62021-01-21 02:02:55 +080011447 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11448
11449 /**
11450 * Class used for updating network activity tracking with netd and notify network activity
11451 * changes.
11452 */
11453 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011454 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011455 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011456 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011457 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080011458 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11459 new RemoteCallbackList<>();
11460 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090011461 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011462 // If there is no default network, default network is considered active to keep the existing
11463 // behavior. Initial value is used until first connect to the default network.
11464 private volatile boolean mIsDefaultNetworkActive = true;
Chalard Jean46bfbf02022-02-02 00:56:25 +090011465 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080011466
Chalard Jean46bfbf02022-02-02 00:56:25 +090011467 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011468 public final int timeout;
11469 public final int transportType;
11470
11471 IdleTimerParams(int timeout, int transport) {
11472 this.timeout = timeout;
11473 this.transportType = transport;
11474 }
11475 }
11476
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011477 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011478 @NonNull Handler handler) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011479 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011480 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011481 mHandler = handler;
11482 }
11483
11484 private void ensureRunningOnConnectivityServiceThread() {
11485 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
11486 throw new IllegalStateException("Not running on ConnectivityService thread: "
11487 + Thread.currentThread().getName());
11488 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011489 }
11490
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011491 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011492 ensureRunningOnConnectivityServiceThread();
Motomu Utsumic298cf02023-05-31 12:06:12 +090011493 if (mActiveIdleTimers.isEmpty()) {
11494 // This activity change is not for the current default network.
11495 // This can happen if netd callback post activity change event message but
11496 // the default network is lost before processing this message.
11497 return;
11498 }
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011499 sendDataActivityBroadcast(transportTypeToLegacyType(activityParams.label),
11500 activityParams.isActive, activityParams.timestampNs);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011501 mIsDefaultNetworkActive = activityParams.isActive;
11502 if (mIsDefaultNetworkActive) {
11503 reportNetworkActive();
lucaslin66f44212021-02-23 01:12:55 +080011504 }
11505 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011506
lucaslin1193a5d2021-01-21 02:04:15 +080011507 private void reportNetworkActive() {
11508 final int length = mNetworkActivityListeners.beginBroadcast();
11509 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
11510 try {
11511 for (int i = 0; i < length; i++) {
11512 try {
11513 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
11514 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011515 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080011516 }
11517 }
11518 } finally {
11519 mNetworkActivityListeners.finishBroadcast();
11520 }
11521 }
11522
lucaslin1a8b4c62021-01-21 02:02:55 +080011523 // This is deprecated and only to support legacy use cases.
11524 private int transportTypeToLegacyType(int type) {
11525 switch (type) {
11526 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011527 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080011528 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011529 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080011530 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011531 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080011532 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011533 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080011534 default:
11535 loge("Unexpected transport in transportTypeToLegacyType: " + type);
11536 }
11537 return ConnectivityManager.TYPE_NONE;
11538 }
11539
11540 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
11541 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
11542 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
11543 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
11544 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
11545 final long ident = Binder.clearCallingIdentity();
11546 try {
11547 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
11548 RECEIVE_DATA_ACTIVITY_CHANGE,
11549 null /* resultReceiver */,
11550 null /* scheduler */,
11551 0 /* initialCode */,
11552 null /* initialData */,
11553 null /* initialExtra */);
11554 } finally {
11555 Binder.restoreCallingIdentity(ident);
11556 }
11557 }
11558
11559 /**
11560 * Setup data activity tracking for the given network.
11561 *
11562 * Every {@code setupDataActivityTracking} should be paired with a
11563 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090011564 *
11565 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080011566 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090011567 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011568 final String iface = networkAgent.linkProperties.getInterfaceName();
11569
11570 final int timeout;
11571 final int type;
11572
11573 if (networkAgent.networkCapabilities.hasTransport(
11574 NetworkCapabilities.TRANSPORT_CELLULAR)) {
11575 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011576 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080011577 10);
11578 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11579 } else if (networkAgent.networkCapabilities.hasTransport(
11580 NetworkCapabilities.TRANSPORT_WIFI)) {
11581 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011582 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080011583 15);
11584 type = NetworkCapabilities.TRANSPORT_WIFI;
11585 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011586 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080011587 }
11588
lucaslinb961efc2021-01-21 02:03:17 +080011589 updateRadioPowerState(true /* isActive */, type);
11590
lucaslin1a8b4c62021-01-21 02:02:55 +080011591 if (timeout > 0 && iface != null) {
11592 try {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011593 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
11594 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
Motomu Utsumi6225d572023-05-29 15:08:57 +090011595 return true;
lucaslin1a8b4c62021-01-21 02:02:55 +080011596 } catch (Exception e) {
11597 // You shall not crash!
11598 loge("Exception in setupDataActivityTracking " + e);
11599 }
11600 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011601 return false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011602 }
11603
11604 /**
11605 * Remove data activity tracking when network disconnects.
11606 */
11607 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
11608 final String iface = networkAgent.linkProperties.getInterfaceName();
11609 final NetworkCapabilities caps = networkAgent.networkCapabilities;
11610
lucaslinb961efc2021-01-21 02:03:17 +080011611 if (iface == null) return;
11612
11613 final int type;
11614 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
11615 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11616 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
11617 type = NetworkCapabilities.TRANSPORT_WIFI;
11618 } else {
11619 return; // do not track any other networks
11620 }
11621
11622 try {
11623 updateRadioPowerState(false /* isActive */, type);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011624 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
11625 if (params == null) {
11626 // IdleTimer is not added if the configured timeout is 0 or negative value
11627 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080011628 }
Motomu Utsumic298cf02023-05-31 12:06:12 +090011629 // The call fails silently if no idle timer setup for this interface
11630 mNetd.idletimerRemoveInterface(iface, params.timeout,
11631 Integer.toString(params.transportType));
lucaslinb961efc2021-01-21 02:03:17 +080011632 } catch (Exception e) {
11633 // You shall not crash!
11634 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080011635 }
11636 }
11637
Motomu Utsumi6225d572023-05-29 15:08:57 +090011638 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
11639 boolean hasIdleTimer) {
11640 if (defaultNetwork != null) {
11641 mIsDefaultNetworkActive = true;
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011642 // Callbacks are called only when the network has the idle timer.
11643 if (hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011644 reportNetworkActive();
11645 }
11646 } else {
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011647 // If there is no default network, default network is considered active to keep the
11648 // existing behavior.
11649 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090011650 }
11651 }
11652
lucaslin1a8b4c62021-01-21 02:02:55 +080011653 /**
11654 * Update data activity tracking when network state is updated.
11655 */
11656 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
11657 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011658 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi6225d572023-05-29 15:08:57 +090011659 boolean hasIdleTimer = false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011660 if (newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011661 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080011662 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011663 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
lucaslin1a8b4c62021-01-21 02:02:55 +080011664 if (oldNetwork != null) {
11665 removeDataActivityTracking(oldNetwork);
11666 }
11667 }
lucaslinb961efc2021-01-21 02:03:17 +080011668
11669 private void updateRadioPowerState(boolean isActive, int transportType) {
11670 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
11671 switch (transportType) {
11672 case NetworkCapabilities.TRANSPORT_CELLULAR:
11673 bs.reportMobileRadioPowerState(isActive, NO_UID);
11674 break;
11675 case NetworkCapabilities.TRANSPORT_WIFI:
11676 bs.reportWifiRadioPowerState(isActive, NO_UID);
11677 break;
11678 default:
11679 logw("Untracked transport type:" + transportType);
11680 }
11681 }
lucaslin1193a5d2021-01-21 02:04:15 +080011682
11683 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011684 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080011685 }
11686
11687 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
11688 mNetworkActivityListeners.register(l);
11689 }
11690
11691 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
11692 mNetworkActivityListeners.unregister(l);
11693 }
lucaslin012f7a12021-01-21 02:04:35 +080011694
11695 public void dump(IndentingPrintWriter pw) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011696 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
11697 pw.println("Idle timers:");
11698 try {
11699 for (Map.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
lucaslin012f7a12021-01-21 02:04:35 +080011700 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
11701 final IdleTimerParams params = ent.getValue();
11702 pw.print(" timeout="); pw.print(params.timeout);
11703 pw.print(" type="); pw.println(params.transportType);
11704 }
Motomu Utsumic298cf02023-05-31 12:06:12 +090011705 } catch (Exception e) {
11706 // mActiveIdleTimers should only be accessed from handler thread, except dump().
11707 // As dump() is never called in normal usage, it would be needlessly expensive
11708 // to lock the collection only for its benefit.
11709 // Also, mActiveIdleTimers is not expected to be updated frequently.
11710 // So catching the exception and logging.
11711 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080011712 }
11713 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011714 }
James Mattis47db0582021-01-01 14:13:35 -080011715
Daniel Brightf9e945b2020-06-15 16:10:01 -070011716 /**
11717 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
11718 *
11719 * @param socketInfo the socket information
11720 * @param callback the callback to register
11721 */
11722 @Override
11723 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
11724 @NonNull final IQosCallback callback) {
11725 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
11726 if (nai == null || nai.networkCapabilities == null) {
11727 try {
11728 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
11729 } catch (final RemoteException ex) {
11730 loge("registerQosCallbackInternal: RemoteException", ex);
11731 }
11732 return;
11733 }
11734 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
11735 }
11736
11737 /**
11738 * Register a {@link IQosCallback} with base {@link QosFilter}.
11739 *
11740 * @param filter the filter to register
11741 * @param callback the callback to register
11742 * @param nai the agent information related to the filter's network
11743 */
11744 @VisibleForTesting
11745 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
11746 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011747 Objects.requireNonNull(filter, "filter must be non-null");
11748 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011749
11750 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080011751 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
11752 // on this network is unregistered when the app loses permission or b) no QoS
11753 // callbacks are sent for restricted networks unless the app currently has permission
11754 // to access restricted networks.
11755 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070011756 }
11757 mQosCallbackTracker.registerCallback(callback, filter, nai);
11758 }
11759
11760 /**
11761 * Unregisters the given callback.
11762 *
11763 * @param callback the callback to unregister
11764 */
11765 @Override
11766 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011767 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011768 mQosCallbackTracker.unregisterCallback(callback);
11769 }
James Mattis47db0582021-01-01 14:13:35 -080011770
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011771 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
11772 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
11773 // Enterprise device can be fully managed like device owner and such use case
11774 // also should be supported. Calling app check for work profile and fully managed device
11775 // is already done in DevicePolicyManager.
11776 // This check is an extra caution to be sure device is fully managed or not.
11777 final UserManager um = mContext.getSystemService(UserManager.class);
11778 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
11779 if (um.isManagedProfile(profile.getIdentifier())) {
11780 return true;
11781 }
Chalard Jeandf29a852023-05-29 17:02:43 +090011782 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011783 return false;
11784 }
11785
James Mattis45d81842021-01-10 14:24:24 -080011786 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011787 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011788 *
11789 * See the documentation for the individual preferences for a description of the supported
11790 * behaviors.
11791 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011792 * @param profile If the device owner is set, any profile is allowed.
11793 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011794 * @param preferences the list of profile network preferences for the
11795 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011796 * @param listener an optional listener to listen for completion of the operation.
11797 */
11798 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011799 public void setProfileNetworkPreferences(
11800 @NonNull final UserHandle profile,
11801 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090011802 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011803 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011804 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011805
11806 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011807 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11808 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11809 .build();
11810 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011811 }
11812
paulhu3ffffe72021-09-16 10:15:22 +080011813 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011814 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011815 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011816 }
11817 if (profile.getIdentifier() < 0) {
11818 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11819 + "UserHandle.CURRENT not supported)");
11820 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011821 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11822 throw new IllegalArgumentException("Profile must be a managed profile "
11823 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011824 }
paulhuaa0743d2021-05-26 21:56:03 +080011825
Chalard Jean0606fc82022-12-14 20:34:43 +090011826 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011827 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011828 for (final ProfileNetworkPreference preference : preferences) {
11829 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011830 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011831 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011832 switch (preference.getPreference()) {
11833 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11834 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011835 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011836 if (preference.getPreferenceEnterpriseId() != 0) {
11837 throw new IllegalArgumentException(
11838 "Invalid enterprise identifier in setProfileNetworkPreferences");
11839 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011840 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011841 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11842 blockingNonEnterprise = true;
11843 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011844 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11845 allowFallback = false;
11846 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011847 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011848 // This code is needed even though there is a check later on,
11849 // because isRangeAlreadyInPreferenceList assumes that every preference
11850 // has a UID list.
11851 if (hasDefaultPreference) {
11852 throw new IllegalArgumentException(
11853 "Default profile preference should not be set along with other "
11854 + "preference");
11855 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011856 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11857 throw new IllegalArgumentException(
11858 "Invalid enterprise identifier in setProfileNetworkPreferences");
11859 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011860 final Set<UidRange> uidRangeSet =
11861 getUidListToBeAppliedForNetworkPreference(profile, preference);
11862 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11863 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11864 } else {
11865 throw new IllegalArgumentException(
11866 "Overlapping uid range in setProfileNetworkPreferences");
11867 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011868 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011869 nc.addEnterpriseId(
11870 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011871 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11872 break;
11873 default:
11874 throw new IllegalArgumentException(
11875 "Invalid preference in setProfileNetworkPreferences");
11876 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011877 preferenceList.add(new ProfileNetworkPreferenceInfo(
11878 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011879 if (hasDefaultPreference && preferenceList.size() > 1) {
11880 throw new IllegalArgumentException(
11881 "Default profile preference should not be set along with other preference");
11882 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011883 }
11884 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011885 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011886 }
11887
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011888 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
11889 @NonNull final UserHandle profile,
11890 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
11891 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080011892 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
11893 profileNetworkPreference.getIncludedUids());
11894
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011895 if (uidRangeSet.size() > 0) {
11896 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
11897 throw new IllegalArgumentException(
11898 "Allow uid range is outside the uid range of profile.");
11899 }
11900 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080011901 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011902 profileNetworkPreference.getExcludedUids());
11903 if (disallowUidRangeSet.size() > 0) {
11904 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
11905 throw new IllegalArgumentException(
11906 "disallow uid range is outside the uid range of profile.");
11907 }
11908 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
11909 disallowUidRangeSet);
11910 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011911 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011912 uidRangeSet.add(profileUids);
11913 }
11914 }
11915 return uidRangeSet;
11916 }
11917
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011918 private boolean isEnterpriseIdentifierValid(
11919 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011920 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011921 return true;
11922 }
11923 return false;
11924 }
11925
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011926 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090011927 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011928 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090011929 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011930 // The NRI for a user should contain the request for capabilities.
11931 // If fallback to default network is needed then NRI should include
11932 // the request for the default network. Create an image of it to
11933 // have the correct UIDs in it (also a request can only be part of one NRI, because
11934 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011935 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
11936 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011937 if (pref.allowFallback) {
11938 nrs.add(createDefaultInternetRequestForTransport(
11939 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11940 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011941 if (VDBG) {
11942 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
11943 pref.capabilities.getUids()));
11944 }
11945
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011946 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080011947 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080011948 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011949 result.add(nri);
11950 }
11951 return result;
11952 }
11953
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011954 /**
11955 * Compare if the given UID range sets have the same UIDs.
11956 *
11957 */
11958 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090011959 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011960 @NonNull Set<UidRange> uidRangeSet) {
11961 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
11962 return false;
11963 }
Chalard Jean0606fc82022-12-14 20:34:43 +090011964 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011965 if (UidRangeUtils.doesRangeSetOverlap(
11966 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
11967 return true;
11968 }
11969 }
11970 return false;
11971 }
11972
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011973 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090011974 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011975 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011976 /*
11977 * handleSetProfileNetworkPreference is always called for single user.
11978 * preferenceList only contains preferences for different uids within the same user
11979 * (enforced by getUidListToBeAppliedForNetworkPreference).
11980 * Clear all the existing preferences for the user before applying new preferences.
11981 *
11982 */
Chalard Jean0606fc82022-12-14 20:34:43 +090011983 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
11984 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011985 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
11986 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011987
paulhu74128522021-09-28 02:29:03 +000011988 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
11989 addPerAppDefaultNetworkRequests(
11990 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080011991 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080011992
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011993 // Finally, rematch.
11994 rematchAllNetworksAndRequests();
11995
11996 if (null != listener) {
11997 try {
11998 listener.onComplete();
11999 } catch (RemoteException e) {
12000 loge("Listener for setProfileNetworkPreference has died");
12001 }
12002 }
12003 }
12004
paulhu51f77dc2021-06-07 02:34:20 +000012005 @VisibleForTesting
12006 @NonNull
12007 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12008 @NonNull final Set<Integer> uids) {
12009 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12010 if (uids.size() == 0) {
12011 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12012 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
12013 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
12014 return nris;
12015 }
12016
12017 final List<NetworkRequest> requests = new ArrayList<>();
12018 // The NRI should be comprised of two layers:
12019 // - The request for the mobile network preferred.
12020 // - The request for the default network, for fallback.
12021 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012022 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012023 requests.add(createDefaultInternetRequestForTransport(
12024 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12025 final Set<UidRange> ranges = new ArraySet<>();
12026 for (final int uid : uids) {
12027 ranges.add(new UidRange(uid, uid));
12028 }
12029 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080012030 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080012031 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000012032 return nris;
12033 }
12034
12035 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012036 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012037 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12038 addPerAppDefaultNetworkRequests(
12039 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012040 // Finally, rematch.
12041 rematchAllNetworksAndRequests();
12042 }
12043
Patrick Rohr2857ac42022-01-21 14:58:16 +010012044 private void handleIngressRateLimitChanged() {
12045 final long oldIngressRateLimit = mIngressRateLimit;
12046 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12047 mContext);
12048 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12049 if (canNetworkBeRateLimited(networkAgent)) {
12050 // If rate limit has previously been enabled, remove the old limit first.
12051 if (oldIngressRateLimit >= 0) {
12052 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12053 }
12054 if (mIngressRateLimit >= 0) {
12055 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12056 mIngressRateLimit);
12057 }
12058 }
12059 }
12060 }
12061
12062 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012063 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090012064 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012065
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012066 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12067 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12068 // internet connectivity can be rate limited.
12069 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12070 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012071 return false;
12072 }
12073
12074 final String iface = networkAgent.linkProperties.getInterfaceName();
12075 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012076 // This may happen in tests, but if there is no interface then there is nothing that
12077 // can be rate limited.
12078 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012079 return false;
12080 }
12081 return true;
12082 }
12083
James Mattis45d81842021-01-10 14:24:24 -080012084 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012085 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12086 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012087 }
12088
12089 /**
12090 * Used by automotive devices to set the network preferences used to direct traffic at an
12091 * application level as per the given OemNetworkPreferences. An example use-case would be an
12092 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12093 * vehicle via a particular network.
12094 *
12095 * Calling this will overwrite the existing preference.
12096 *
James Mattisda32cfe2021-01-26 16:23:52 -080012097 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012098 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012099 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012100 */
James Mattis47db0582021-01-01 14:13:35 -080012101 @Override
James Mattis45d81842021-01-10 14:24:24 -080012102 public void setOemNetworkPreference(
12103 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012104 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012105
James Mattisfa270db2021-05-31 17:11:10 -070012106 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12107 // Only bypass the permission/device checks if this is a valid test request.
12108 if (isValidTestOemNetworkPreference(preference)) {
12109 enforceManageTestNetworksPermission();
12110 } else {
12111 enforceAutomotiveDevice();
12112 enforceOemNetworkPreferencesPermission();
12113 validateOemNetworkPreferences(preference);
12114 }
James Mattis45d81842021-01-10 14:24:24 -080012115
James Mattis45d81842021-01-10 14:24:24 -080012116 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12117 new Pair<>(preference, listener)));
12118 }
12119
James Mattisfa270db2021-05-31 17:11:10 -070012120 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012121 * Sets the specified UIDs to get/receive the VPN as the only default network.
12122 *
12123 * Calling this will overwrite the existing network preference for this session, and the
12124 * specified UIDs won't get any default network when no VPN is connected.
12125 *
12126 * @param session The VPN session which manages the passed UIDs.
12127 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12128 * setting for this session if the array is empty. Null is not allowed, the
12129 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12130 * @hide
12131 */
12132 @Override
12133 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12134 Objects.requireNonNull(ranges);
12135 enforceNetworkStackOrSettingsPermission();
12136 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12137 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12138 throw new IllegalArgumentException(
12139 "setVpnNetworkPreference: Passed UID ranges overlap");
12140 }
12141
12142 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12143 new VpnNetworkPreferenceInfo(session,
12144 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12145 }
12146
12147 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12148 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12149
12150 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12151 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12152
12153 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12154 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12155 // Finally, rematch.
12156 rematchAllNetworksAndRequests();
12157 }
12158
12159 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12160 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12161 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12162 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
12163 final List<NetworkRequest> requests = new ArrayList<>();
12164 // Request VPN only, so other networks won't be the fallback options when VPN is not
12165 // connected temporarily.
12166 requests.add(createVpnRequest());
12167 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
12168 setNetworkRequestUids(requests, uidRanges);
12169 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
12170 }
12171 return nris;
12172 }
12173
12174 /**
James Mattisfa270db2021-05-31 17:11:10 -070012175 * Check the validity of an OEM network preference to be used for testing purposes.
12176 * @param preference the preference to validate
12177 * @return true if this is a valid OEM network preference test request.
12178 */
12179 private boolean isValidTestOemNetworkPreference(
12180 @NonNull final OemNetworkPreferences preference) {
12181 // Allow for clearing of an existing OemNetworkPreference used for testing.
12182 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
12183 // changes after this check is complete. This is an unlikely scenario as calling of this API
12184 // is controlled by the OEM therefore the added complexity is not worth adding given those
12185 // circumstances. That said, it is an edge case to be aware of hence this comment.
12186 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
12187 && isTestOemNetworkPreference(mOemNetworkPreferences);
12188 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
12189 }
12190
12191 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
12192 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
12193 return prefMap.size() == 1
12194 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
12195 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
12196 }
12197
James Mattis45d81842021-01-10 14:24:24 -080012198 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
12199 for (@OemNetworkPreferences.OemNetworkPreference final int pref
12200 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070012201 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
12202 throw new IllegalArgumentException(
12203 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
12204 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080012205 }
12206 }
12207 }
12208
12209 private void handleSetOemNetworkPreference(
12210 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012211 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080012212 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12213 if (DBG) {
12214 log("set OEM network preferences :" + preference.toString());
12215 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012216
James Mattiscb1e0362021-04-06 17:07:42 -070012217 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012218 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12219 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12220 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012221 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012222
12223 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012224 try {
12225 listener.onComplete();
12226 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012227 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012228 }
James Mattis45d81842021-01-10 14:24:24 -080012229 }
12230 }
12231
paulhu74128522021-09-28 02:29:03 +000012232 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012233 // Skip the requests which are set by other network preference. Because the uid range rules
12234 // should stay in netd.
12235 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012236 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012237 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012238 }
12239
James Mattis3ce3d3c2021-02-09 18:18:28 -080012240 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12241 ensureRunningOnConnectivityServiceThread();
12242 mDefaultNetworkRequests.addAll(nris);
12243 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12244 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012245 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012246 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12247 nrisToRegister.addAll(
12248 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12249 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012250 }
12251
12252 /**
12253 * All current requests that are tracking the default network need to be assessed as to whether
12254 * or not the current set of per-application default requests will be changing their default
12255 * network. If so, those requests will need to be updated so that they will send callbacks for
12256 * default network changes at the appropriate time. Additionally, those requests tracking the
12257 * default that were previously updated by this flow will need to be reassessed.
12258 * @return the nris which will need to be updated.
12259 */
12260 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12261 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12262 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12263 // same nri in the map's values for each of its NetworkRequest objects.
12264 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012265 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012266 // Include this nri if it is currently being tracked.
12267 if (isPerAppTrackedNri(nri)) {
12268 defaultCallbackRequests.add(nri);
12269 continue;
12270 }
12271 // We only track callbacks for requests tracking the default.
12272 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12273 continue;
12274 }
12275 // Include this nri if it will be tracked by the new per-app default requests.
12276 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012277 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012278 if (isNriGoingToBeTracked) {
12279 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012280 }
12281 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012282 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012283 }
12284
James Mattis3ce3d3c2021-02-09 18:18:28 -080012285 /**
12286 * Create nris for those network requests that are currently tracking the default network that
12287 * are being controlled by a per-application default.
12288 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12289 * foundation when creating the nri. Important items include the calling uid's original
12290 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12291 * requests are assumed to have already been validated as needing to be updated.
12292 * @return the Set of nris to use when registering network requests.
12293 */
12294 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12295 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12296 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12297 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12298 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012299 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012300
Chalard Jean9473c982021-07-29 20:03:04 +090012301 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012302 if (trackingNri == mDefaultRequest) {
12303 callbackRequestsToRegister.add(new NetworkRequestInfo(
12304 callbackRequest,
12305 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12306 continue;
12307 }
12308
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012309 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012310 callbackRequestsToRegister.add(new NetworkRequestInfo(
12311 callbackRequest,
12312 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012313 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012314 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012315 }
12316 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012317 }
12318
Chalard Jean17215832021-03-01 14:06:28 +090012319 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12320 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012321 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012322 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012323 }
12324 }
12325
James Mattis45d81842021-01-10 14:24:24 -080012326 /**
12327 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12328 */
12329 @VisibleForTesting
12330 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012331 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080012332 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012333 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080012334 final SparseArray<Set<Integer>> uids =
12335 createUidsFromOemNetworkPreferences(preference);
12336 for (int i = 0; i < uids.size(); i++) {
12337 final int key = uids.keyAt(i);
12338 final Set<Integer> value = uids.valueAt(i);
12339 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
12340 // No need to add an nri without any requests.
12341 if (0 == nri.mRequests.size()) {
12342 continue;
12343 }
12344 nris.add(nri);
12345 }
12346
12347 return nris;
12348 }
12349
12350 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
12351 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070012352 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080012353 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080012354 final List<UserHandle> users =
12355 mContext.getSystemService(UserManager.class).getUserHandles(true);
12356 if (null == users || users.size() == 0) {
12357 if (VDBG || DDBG) {
12358 log("No users currently available for setting the OEM network preference.");
12359 }
James Mattisb6b6a432021-06-01 22:30:36 -070012360 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080012361 }
James Mattis45d81842021-01-10 14:24:24 -080012362 for (final Map.Entry<String, Integer> entry :
12363 preference.getNetworkPreferences().entrySet()) {
12364 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070012365 // Add the rules for all users as this policy is device wide.
12366 for (final UserHandle user : users) {
12367 try {
12368 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
12369 if (!prefToUids.contains(pref)) {
12370 prefToUids.put(pref, new ArraySet<>());
12371 }
12372 prefToUids.get(pref).add(uid);
12373 } catch (PackageManager.NameNotFoundException e) {
12374 // Although this may seem like an error scenario, it is ok that uninstalled
12375 // packages are sent on a network preference as the system will watch for
12376 // package installations associated with this network preference and update
12377 // accordingly. This is done to minimize race conditions on app install.
12378 continue;
James Mattis45d81842021-01-10 14:24:24 -080012379 }
James Mattis45d81842021-01-10 14:24:24 -080012380 }
12381 }
James Mattisb6b6a432021-06-01 22:30:36 -070012382 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080012383 }
12384
12385 private NetworkRequestInfo createNriFromOemNetworkPreferences(
12386 @OemNetworkPreferences.OemNetworkPreference final int preference,
12387 @NonNull final Set<Integer> uids) {
12388 final List<NetworkRequest> requests = new ArrayList<>();
12389 // Requests will ultimately be evaluated by order of insertion therefore it matters.
12390 switch (preference) {
12391 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
12392 requests.add(createUnmeteredNetworkRequest());
12393 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070012394 requests.add(createDefaultInternetRequestForTransport(
12395 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080012396 break;
12397 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
12398 requests.add(createUnmeteredNetworkRequest());
12399 requests.add(createOemPaidNetworkRequest());
12400 break;
12401 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
12402 requests.add(createOemPaidNetworkRequest());
12403 break;
12404 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
12405 requests.add(createOemPrivateNetworkRequest());
12406 break;
James Mattisfa270db2021-05-31 17:11:10 -070012407 case OEM_NETWORK_PREFERENCE_TEST:
12408 requests.add(createUnmeteredNetworkRequest());
12409 requests.add(createTestNetworkRequest());
12410 requests.add(createDefaultRequest());
12411 break;
12412 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
12413 requests.add(createTestNetworkRequest());
12414 break;
James Mattis45d81842021-01-10 14:24:24 -080012415 default:
12416 // This should never happen.
12417 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
12418 + " called with invalid preference of " + preference);
12419 }
12420
James Mattisfa270db2021-05-31 17:11:10 -070012421 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090012422 for (final int uid : uids) {
12423 ranges.add(new UidRange(uid, uid));
12424 }
12425 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080012426 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080012427 }
12428
12429 private NetworkRequest createUnmeteredNetworkRequest() {
12430 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12431 .addCapability(NET_CAPABILITY_NOT_METERED)
12432 .addCapability(NET_CAPABILITY_VALIDATED);
12433 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
12434 }
12435
12436 private NetworkRequest createOemPaidNetworkRequest() {
12437 // NET_CAPABILITY_OEM_PAID is a restricted capability.
12438 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12439 .addCapability(NET_CAPABILITY_OEM_PAID)
12440 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12441 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12442 }
12443
12444 private NetworkRequest createOemPrivateNetworkRequest() {
12445 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
12446 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12447 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
12448 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12449 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12450 }
12451
12452 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070012453 final NetworkCapabilities netcap = new NetworkCapabilities();
12454 netcap.addCapability(NET_CAPABILITY_INTERNET);
12455 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
12456 return netcap;
12457 }
12458
12459 private NetworkRequest createTestNetworkRequest() {
12460 final NetworkCapabilities netcap = new NetworkCapabilities();
12461 netcap.clearAll();
12462 netcap.addTransportType(TRANSPORT_TEST);
12463 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080012464 }
James Mattis47db0582021-01-01 14:13:35 -080012465 }
markchien738ad912021-12-09 18:15:45 +080012466
12467 @Override
12468 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
12469 enforceNetworkStackOrSettingsPermission();
12470
12471 try {
12472 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012473 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012474 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012475 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012476 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012477 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012478 throw new IllegalStateException(e);
12479 }
12480 }
12481
12482 @Override
12483 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
12484 enforceNetworkStackOrSettingsPermission();
12485
12486 try {
12487 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012488 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012489 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012490 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012491 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012492 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012493 throw new IllegalStateException(e);
12494 }
12495 }
markchiene1561fa2021-12-09 22:00:56 +080012496
Chalard Jeanc8fefb32023-09-05 21:41:13 +090012497 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
12498 throws PackageManager.NameNotFoundException {
12499 final PackageManager pm = mContext.getPackageManager();
12500 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
12501 if (appId < Process.FIRST_APPLICATION_UID) {
12502 throw new RuntimeException("Can't set package firewall rule for system app "
12503 + packageName + " with appId " + appId);
12504 }
12505 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
12506 final int uid = uh.getUid(appId);
12507 setUidFirewallRule(chain, uid, rule);
12508 }
12509 return appId;
12510 }
12511
markchiene1561fa2021-12-09 22:00:56 +080012512 @Override
markchien3c04e662022-03-22 16:29:56 +080012513 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080012514 enforceNetworkStackOrSettingsPermission();
12515
markchien3c04e662022-03-22 16:29:56 +080012516 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
12517 int firewallRule = getFirewallRuleType(chain, rule);
12518
12519 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
12520 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
12521 }
12522
markchiene1561fa2021-12-09 22:00:56 +080012523 try {
markchien3c04e662022-03-22 16:29:56 +080012524 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012525 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080012526 throw new IllegalStateException(e);
12527 }
12528 }
markchien98a6f952022-01-13 23:43:53 +080012529
Chalard Jeanc8fefb32023-09-05 21:41:13 +090012530 private int getPackageFirewallRule(final int chain, final String packageName)
12531 throws PackageManager.NameNotFoundException {
12532 final PackageManager pm = mContext.getPackageManager();
12533 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
12534 return getUidFirewallRule(chain, appId);
12535 }
12536
Motomu Utsumi900b8062023-01-19 16:16:49 +090012537 @Override
12538 public int getUidFirewallRule(final int chain, final int uid) {
12539 enforceNetworkStackOrSettingsPermission();
12540 return mBpfNetMaps.getUidRule(chain, uid);
12541 }
12542
markchien3c04e662022-03-22 16:29:56 +080012543 private int getFirewallRuleType(int chain, int rule) {
12544 final int defaultRule;
12545 switch (chain) {
12546 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000012547 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
12548 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000012549 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080012550 defaultRule = FIREWALL_RULE_ALLOW;
12551 break;
12552 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
12553 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
12554 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
12555 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
12556 defaultRule = FIREWALL_RULE_DENY;
12557 break;
12558 default:
12559 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
12560 }
12561 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
12562
12563 return rule;
12564 }
12565
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012566 private void closeSocketsForFirewallChainLocked(final int chain)
12567 throws ErrnoException, SocketException, InterruptedIOException {
12568 if (mBpfNetMaps.isFirewallAllowList(chain)) {
12569 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
12570 // So, close all non-system socket owned by uids that are not explicitly allowed
12571 Set<Range<Integer>> ranges = new ArraySet<>();
12572 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
12573 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
12574 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
12575 } else {
12576 // Denylist means the firewall allows all by default, uids must be explicitly denied
12577 // So, close socket owned by uids that are explicitly denied
12578 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
12579 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
12580 }
12581 }
12582
markchien98a6f952022-01-13 23:43:53 +080012583 @Override
12584 public void setFirewallChainEnabled(final int chain, final boolean enable) {
12585 enforceNetworkStackOrSettingsPermission();
12586
12587 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012588 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012589 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080012590 throw new IllegalStateException(e);
12591 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012592
Chalard Jeandf29a852023-05-29 17:02:43 +090012593 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012594 try {
12595 closeSocketsForFirewallChainLocked(chain);
12596 } catch (ErrnoException | SocketException | InterruptedIOException e) {
12597 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
12598 }
12599 }
markchien98a6f952022-01-13 23:43:53 +080012600 }
12601
markchien00a0bed2022-01-13 23:46:13 +080012602 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012603 public boolean getFirewallChainEnabled(final int chain) {
12604 enforceNetworkStackOrSettingsPermission();
12605
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000012606 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012607 }
12608
12609 @Override
markchien00a0bed2022-01-13 23:46:13 +080012610 public void replaceFirewallChain(final int chain, final int[] uids) {
12611 enforceNetworkStackOrSettingsPermission();
12612
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000012613 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080012614 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080012615
12616 @Override
12617 public IBinder getCompanionDeviceManagerProxyService() {
12618 enforceNetworkStackPermission(mContext);
12619 return mCdmps;
12620 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070012621}