blob: 6ce6fcf3757c5a2498d2e59265358deeb9c54404 [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000018
Haoyu Baib5da5752012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Mark Fasheh7c999d82023-05-04 20:23:11 +000020import static android.app.ActivityManager.UidFrozenStateChangedCallback.UID_FROZEN_STATE_FROZEN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090021import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
Chalard Jeane0aaca52023-10-17 13:23:07 +090022import static android.content.pm.PackageManager.FEATURE_LEANBACK;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090023import static android.content.pm.PackageManager.FEATURE_WATCH;
24import static android.content.pm.PackageManager.FEATURE_WIFI;
25import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
Chalard Jean9a396cc2018-02-21 18:43:54 +090026import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090027import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
28import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
29import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
33import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
34import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090035import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
36import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000037import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Aaron Huang9fe47be2021-06-08 13:11:45 +080038import static android.net.ConnectivityManager.CALLBACK_IP_CHANGED;
Jeff Sharkey971cd162011-08-29 16:02:57 -070039import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
markchien3c04e662022-03-22 16:29:56 +080040import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
41import static android.net.ConnectivityManager.FIREWALL_RULE_DEFAULT;
42import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090043import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090044import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090045import static android.net.ConnectivityManager.TYPE_MOBILE;
46import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
47import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
48import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
49import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
50import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
51import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
52import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
53import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
54import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070055import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090056import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070057import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090058import static android.net.ConnectivityManager.TYPE_WIFI;
59import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070060import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070061import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080062import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080063import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080064import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070065import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080066import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040067import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090068import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090070import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Chalard Jeane0aaca52023-10-17 13:23:07 +090071import static android.net.NetworkCapabilities.NET_CAPABILITY_LOCAL_NETWORK;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090072import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090073import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
74import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060075import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090076import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080077import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090078import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080079import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
80import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080081import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Chalard Jeanf95e2de2023-08-22 19:07:47 +090082import static android.net.NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090083import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080084import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
85import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080086import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
87import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
88import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090089import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090090import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060091import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070092import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080093import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090094import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070095import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
96import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070097import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080098import static android.os.Process.VPN_UID;
Patrick Rohr2857ac42022-01-21 14:58:16 +010099import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700100import static android.system.OsConstants.IPPROTO_TCP;
101import static android.system.OsConstants.IPPROTO_UDP;
Chalard Jeaneb663892023-10-07 15:17:07 +0900102
Xiao Ma60142372022-07-16 17:30:20 +0900103import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Junyu Lai4c6fe232023-04-11 11:33:46 +0800104import static com.android.net.module.util.PermissionUtils.checkAnyPermissionOf;
paulhu3ffffe72021-09-16 10:15:22 +0800105import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
106import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
107import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900108import static com.android.server.ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE;
Chalard Jeaneb663892023-10-07 15:17:07 +0900109
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800110import static java.util.Map.Entry;
111
Chalard Jean5b639762020-03-09 21:25:37 +0900112import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000113import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800114import android.annotation.Nullable;
Michael Groover73f69482023-01-27 11:01:25 -0600115import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800116import android.annotation.TargetApi;
Mark Fasheh7c999d82023-05-04 20:23:11 +0000117import android.app.ActivityManager;
118import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800119import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800120import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700121import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700122import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900123import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800124import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700125import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800126import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800127import android.content.ContentResolver;
128import android.content.Context;
129import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700130import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800131import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900132import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700133import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900134import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900135import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700136import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800137import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800138import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800139import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900140import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800141import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900142import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800143import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900144import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800145import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700146import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900147import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800148import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800149import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800150import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800151import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800152import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900153import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900154import android.net.INetworkMonitor;
155import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900156import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900157import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700158import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800159import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900160import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900161import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900162import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800163import android.net.LinkProperties;
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +0900164import android.net.LocalNetworkConfig;
Charles He9369e612017-05-15 17:07:18 +0100165import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800166import android.net.NativeNetworkConfig;
167import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800168import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700169import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700170import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900171import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700172import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800173import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700174import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900175import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900176import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000177import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900178import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700179import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900180import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700181import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900182import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700183import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800184import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900185import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700186import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000187import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800188import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900189import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800190import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400191import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700192import android.net.QosCallbackException;
193import android.net.QosFilter;
194import android.net.QosSocketFilter;
195import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700196import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800197import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800198import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800199import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900200import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400201import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800202import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800203import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400204import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800205import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900206import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900207import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900208import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900209import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800210import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900211import android.net.networkstack.ModuleNetworkStackClient;
212import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900213import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800214import android.net.resolv.aidl.DnsHealthEventParcel;
215import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
216import android.net.resolv.aidl.Nat64PrefixEventParcel;
217import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900218import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900219import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800220import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800221import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800222import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700223import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000224import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800225import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700226import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700227import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800228import android.os.Looper;
229import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700230import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700231import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900232import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800233import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700234import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700235import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800236import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700237import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900238import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900239import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700240import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700241import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400242import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800243import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900244import android.stats.connectivity.MeteredState;
245import android.stats.connectivity.RequestType;
246import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900247import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700248import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700249import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700250import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800251import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900252import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000253import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600254import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900255import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900256import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700257import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700258import android.util.SparseIntArray;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900259import android.util.StatsEvent;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800260
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800261import androidx.annotation.RequiresApi;
262
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900263import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400264import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400265import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700266import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900267import com.android.internal.util.MessageUtils;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900268import com.android.metrics.ConnectionDurationForTransports;
269import com.android.metrics.ConnectionDurationPerTransports;
270import com.android.metrics.ConnectivitySampleMetricsHelper;
271import com.android.metrics.ConnectivityStateSample;
272import com.android.metrics.NetworkCountForTransports;
273import com.android.metrics.NetworkCountPerTransports;
274import com.android.metrics.NetworkDescription;
275import com.android.metrics.NetworkList;
276import com.android.metrics.NetworkRequestCount;
277import com.android.metrics.RequestCountForType;
Chiachang Wang62740142020-11-02 16:51:24 +0800278import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900279import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800280import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000281import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900282import com.android.net.module.util.BitUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900283import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900284import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100285import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900286import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
287import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900288import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800289import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800290import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100291import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000292import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800293import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
294import com.android.networkstack.apishim.ConstantsShim;
295import com.android.networkstack.apishim.common.BroadcastOptionsShim;
296import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900297import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900298import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000299import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900300import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800301import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800302import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900303import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900304import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900305import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500306import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700307import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900308import com.android.server.connectivity.FullScore;
Junyu Laif8dba342023-10-12 17:01:03 +0800309import com.android.server.connectivity.HandlerUtils;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900310import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900311import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000312import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100313import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700314import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900315import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700316import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600317import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900318import com.android.server.connectivity.NetworkNotificationManager;
319import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900320import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900321import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900322import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700323import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900324import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900325import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700326import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800327import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000328import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800329import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600330
Josh Gao461a1222020-06-16 15:58:11 -0700331import libcore.io.IoUtils;
332
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900333import org.xmlpull.v1.XmlPullParserException;
334
The Android Open Source Project28527d22009-03-03 19:31:44 -0800335import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100336import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900337import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800338import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900339import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700340import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700341import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900342import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900343import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700344import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700345import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700346import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700347import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800348import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900349import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800350import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700351import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700352import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700353import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700354import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900355import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700356import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900357import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600358import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900359import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600360import java.util.TreeSet;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900361import java.util.concurrent.TimeUnit;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900362import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800363
364/**
365 * @hide
366 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800367public class ConnectivityService extends IConnectivityManager.Stub
368 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900369 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800370
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900371 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900372 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900373 private static final String NETWORK_ARG = "networks";
374 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800375 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900376
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900377 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900378 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
379 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800380
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900381 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700382
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100383 /**
384 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
385 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800386 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100387 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
388 * (preferably via runtime resource overlays).
389 */
390 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
391 "http://connectivitycheck.gstatic.com/generate_204";
392
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700393 // TODO: create better separation between radio types and network types
394
Robert Greenwalt2034b912009-08-12 16:08:25 -0700395 // how long to wait before switching back to a radio's default network
396 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
397 // system property that can override the above value
398 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
399 "android.telephony.apn-restore";
400
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900401 // How long to wait before putting up a "This network doesn't have an Internet connection,
402 // connect anyway?" dialog after the user selects a network that doesn't validate.
403 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
404
Chalard Jean5fb43c72022-09-08 19:03:14 +0900405 // How long to wait before considering that a network is bad in the absence of any form
406 // of connectivity (valid, partial, captive portal). If none has been detected after this
407 // delay, the stack considers this network bad, which may affect how it's handled in ranking
408 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900409 // Timeout in case the "actively prefer bad wifi" feature is on
410 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
411 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900412 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900413
junyulai0ac374f2020-12-14 18:41:52 +0800414 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900415 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
416 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800417 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700418
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800419 // Delimiter used when creating the broadcast delivery group for sending
420 // CONNECTIVITY_ACTION broadcast.
421 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
422
he_won.hwang881307a2022-03-15 21:23:52 +0900423 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900424 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900425
Daniel Brightf9e945b2020-06-15 16:10:01 -0700426 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900427 @VisibleForTesting
428 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700429
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900430 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700431 @VisibleForTesting
432 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900433
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900434 @VisibleForTesting
435 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800436 @VisibleForTesting
437 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900438 // True if the cell radio of the device is capable of time-sharing.
439 @VisibleForTesting
440 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900441
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800442 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800443 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800444 private final int mReleasePendingIntentDelayMs;
445
Chalard Jean46bfbf02022-02-02 00:56:25 +0900446 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900447
Motomu Utsumif360aa62023-01-30 17:52:20 +0900448 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700449
Chalard Jean9473c982021-07-29 20:03:04 +0900450 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800451 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700452 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800453 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700454
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900455 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700456
junyulaif2c67e42018-08-07 19:50:45 +0800457 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000458 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
459 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800460 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900461 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800462
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900463 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900464 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000465 private final int mWakeUpMark;
466 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000467 // The Context is created for UserHandle.ALL.
468 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900469 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900470 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700471 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700472 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800473
Chenbo Feng15416292018-11-08 17:36:21 -0800474 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800475 protected IDnsResolver mDnsResolver;
476 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800477 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700478 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900479 private final NetworkStatsManager mStatsManager;
480 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800481 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700482
Benedict Wong493e04b2018-11-09 14:45:34 -0800483 /**
484 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
485 * instances.
486 */
487 @GuardedBy("mTNSLock")
488 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800489 private final CompanionDeviceManagerProxyService mCdmps;
Benedict Wong493e04b2018-11-09 14:45:34 -0800490
491 private final Object mTNSLock = new Object();
492
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700493 private String mCurrentTcpBufferSizes;
494
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900495 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000496 new Class[] {
497 ConnectivityService.class,
498 NetworkAgent.class,
499 NetworkAgentInfo.class,
500 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900501
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500502 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400503 // Tear down networks that have no chance (e.g. even if validated) of becoming
504 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500505 // all networks have been rematched against all NetworkRequests.
506 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400507 // Don't reap networks. This should be passed when some networks have not yet been
508 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500509 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900510 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500511
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900512 private enum UnneededFor {
513 LINGER, // Determine whether this network is unneeded and should be lingered.
514 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
515 }
516
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700517 /**
paulhuaa0743d2021-05-26 21:56:03 +0800518 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800519 * should have priority. The order is passed to netd which will use it together
520 * with UID ranges to generate the corresponding IP rule. This serves to
521 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800522 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800523 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000524 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800525 *
paulhu48291862021-07-14 14:53:57 +0800526 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
527 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800528 */
paulhu48291862021-07-14 14:53:57 +0800529 // Used when sending to netd to code for "no order".
530 static final int PREFERENCE_ORDER_NONE = 0;
531 // Order for requests that don't code for a per-app preference. As it is
532 // out of the valid range, the corresponding order should be
533 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800534 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800535 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800536 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800537 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
538 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800539 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800540 static final int PREFERENCE_ORDER_OEM = 10;
541 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800542 // See {@link #setProfileNetworkPreference}.
543 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800544 static final int PREFERENCE_ORDER_PROFILE = 20;
545 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800546 // better scores are connected.
547 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800548 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800549 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900550 // Preference order that signifies the network shouldn't be set as a default network for
551 // the UIDs, only give them access to it. TODO : replace this with a boolean
552 // in NativeUidRangeConfig
553 @VisibleForTesting
554 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
555 // Bound for the lowest valid preference order.
556 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800557
558 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700559 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700560 * from one net to another. Clear happens when we get a new
561 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
562 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700563 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700564 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700565
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700566 /**
567 * used internally to reload global proxy settings
568 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700569 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700570
Robert Greenwalt34848c02011-03-25 13:09:25 -0700571 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400572 * PAC manager has received new port.
573 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800574 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400575
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700576 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900577 * used internally when registering NetworkProviders
578 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700579 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900580 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700581
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700582 /**
583 * used internally when registering NetworkAgents
584 * obj = Messenger
585 */
586 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
587
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700588 /**
589 * used to add a network request
590 * includes a NetworkRequestInfo
591 */
592 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
593
594 /**
595 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900596 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700597 * cancel it.
598 * includes a NetworkRequestInfo
599 */
600 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
601
602 /**
603 * used to add a network listener - no request
604 * includes a NetworkRequestInfo
605 */
606 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
607
608 /**
609 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400610 * arg1 = UID of caller
611 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700612 */
613 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
614
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700615 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900616 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700617 * obj = Messenger
618 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900619 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700620
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700621 /**
622 * used internally to expire a wakelock when transitioning
623 * from one net to another. Expire happens when we fail to find
624 * a new network (typically after 1 minute) -
625 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
626 * a replacement network.
627 */
628 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
629
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700630 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800631 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400632 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800633 */
634 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
635
636 /**
637 * used to remove a pending intent and its associated network request.
638 * arg1 = UID of caller
639 * obj = PendingIntent
640 */
641 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
642
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900643 /**
644 * used to specify whether a network should be used even if unvalidated.
645 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
646 * arg2 = whether to remember this choice in the future (1 or 0)
647 * obj = network
648 */
649 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
650
651 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700652 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900653 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700654 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900655
Paul Jensenc8873fc2015-06-17 14:15:39 -0400656 /**
657 * used to add a network listener with a pending intent
658 * obj = NetworkRequestInfo
659 */
660 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
661
Hugo Benichid6b510a2017-04-06 17:22:18 +0900662 /**
663 * used to specify whether a network should not be penalized when it becomes unvalidated.
664 */
665 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
666
667 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700668 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900669 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700670 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900671
Erik Kline31b4a9e2018-01-11 21:07:29 +0900672 // Handle changes in Private DNS settings.
673 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
674
dalyk1720e542018-03-05 12:42:22 -0500675 // Handle private DNS validation status updates.
676 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
677
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900678 /**
679 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
680 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800681 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
682 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
683 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900684 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900685 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900686
687 /**
688 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
689 * config was resolved.
690 * obj = PrivateDnsConfig
691 * arg2 = netid
692 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900693 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900694
695 /**
696 * Request ConnectivityService display provisioning notification.
697 * arg1 = Whether to make the notification visible.
698 * arg2 = NetID.
699 * obj = Intent to be launched when notification selected by user, null if !arg1.
700 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900701 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900702
703 /**
lucaslin2240ef62019-03-12 13:08:03 +0800704 * Used to specify whether a network should be used even if connectivity is partial.
705 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
706 * false)
707 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
708 * obj = network
709 */
lucaslin444d43a2020-02-20 16:56:59 +0800710 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800711
712 /**
lucasline117e2e2019-10-22 18:27:33 +0800713 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
714 * Both of the arguments are bitmasks, and the value of bits come from
715 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900716 * arg1 = unused
717 * arg2 = netId
718 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800719 */
lucaslin444d43a2020-02-20 16:56:59 +0800720 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800721
722 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900723 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
724 * arg1 = unused
725 * arg2 = netId
726 * obj = captive portal data
727 */
lucaslin444d43a2020-02-20 16:56:59 +0800728 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900729
730 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900731 * Used by setRequireVpnForUids.
732 * arg1 = whether the specified UID ranges are required to use a VPN.
733 * obj = Array of UidRange objects.
734 */
735 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
736
737 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900738 * Used internally when setting the default networks for OemNetworkPreferences.
739 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800740 */
741 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
742
743 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800744 * Used to indicate the system default network becomes active.
745 */
746 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
747
748 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900749 * Used internally when setting a network preference for a user profile.
750 * obj = Pair<ProfileNetworkPreference, Listener>
751 */
752 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
753
754 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000755 * Event to specify that reasons for why an uid is blocked changed.
756 * arg1 = uid
757 * arg2 = blockedReasons
758 */
759 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
760
761 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900762 * Event to register a new network offer
763 * obj = NetworkOffer
764 */
765 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
766
767 /**
768 * Event to unregister an existing network offer
769 * obj = INetworkOfferCallback
770 */
771 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
772
773 /**
paulhu51f77dc2021-06-07 02:34:20 +0000774 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
775 */
776 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
777
778 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800779 * Event to set temporary allow bad wifi within a limited time to override
780 * {@code config_networkAvoidBadWifi}.
781 */
782 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
783
784 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100785 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
786 */
787 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
788
789 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900790 * The initial evaluation period is over for this network.
791 *
792 * If no form of connectivity has been found on this network (valid, partial, captive portal)
793 * then the stack will now consider it to have been determined bad.
794 */
795 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
796
797 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000798 * Used internally when the user does not want the network from captive portal app.
799 * obj = Network
800 */
801 private static final int EVENT_USER_DOES_NOT_WANT = 58;
802
803 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000804 * Event to set VPN as preferred network for specific apps.
805 * obj = VpnNetworkPreferenceInfo
806 */
807 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
808
809 /**
chiachangwange0192a72023-02-06 13:25:01 +0000810 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
811 */
812 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
813
814 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000815 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
816 */
817 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
818
819 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900820 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
821 * should be shown.
822 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900823 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900824
825 /**
826 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
827 * should be hidden.
828 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900829 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900830
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800831 /**
832 * The maximum alive time to allow bad wifi configuration for testing.
833 */
834 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
835
Patrick Rohr2857ac42022-01-21 14:58:16 +0100836 /**
chiachangwange0192a72023-02-06 13:25:01 +0000837 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
838 * testing.
839 */
840 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
841
842 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100843 * The priority of the tc police rate limiter -- smaller value is higher priority.
844 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
845 */
846 private static final short TC_PRIO_POLICE = 1;
847
848 /**
849 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
850 */
851 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700852 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100853
Hugo Benichi47011212017-03-30 10:46:05 +0900854 private static String eventName(int what) {
855 return sMagicDecoderRing.get(what, Integer.toString(what));
856 }
857
paulhua10d8212020-11-10 15:32:56 +0800858 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900859 final DnsResolverServiceManager dsm = context.getSystemService(
860 DnsResolverServiceManager.class);
861 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800862 }
863
Cody Kesting73708bf2019-12-18 10:57:50 -0800864 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900865 @VisibleForTesting
866 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700867 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700868 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700869 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700870 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800871 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
872 @VisibleForTesting
873 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
874
Erik Kline32120082017-12-13 19:40:49 +0900875 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900876 @VisibleForTesting
877 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700878
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400879 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800880 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400881
Chalard Jean46bfbf02022-02-02 00:56:25 +0900882 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800883 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700884
Chalard Jean5d70ba42018-06-07 16:44:04 +0900885 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
886 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800887 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400888
Erik Kline05f2b402015-04-30 12:58:40 +0900889 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700890
Chalard Jean46bfbf02022-02-02 00:56:25 +0900891 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400892
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700893 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900894 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700895
Valentin Iftime9fa35092019-09-24 13:32:13 +0200896 private Set<String> mWolSupportedInterfaces;
897
Roshan Pius08c94fb2020-01-16 12:17:17 -0800898 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800899 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800900 private final AppOpsManager mAppOpsManager;
901
902 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400903
chiachangwang3d60bac2023-01-17 14:38:08 +0000904 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900905 private final QosCallbackTracker mQosCallbackTracker;
906 private final NetworkNotificationManager mNotifier;
907 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900908
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700909 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800910 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700911
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900912 // Sequence number for NetworkProvider IDs.
913 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
914 NetworkProvider.FIRST_PROVIDER_ID);
915
Erik Klineedf878b2015-07-09 18:24:03 +0900916 // NetworkRequest activity String log entries.
917 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
918 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
919
Hugo Benichid159fdd2016-07-11 11:05:12 +0900920 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900921 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900922 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
923
Hugo Benichi47011212017-03-30 10:46:05 +0900924 private static final int MAX_WAKELOCK_LOGS = 20;
925 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900926 private int mTotalWakelockAcquisitions = 0;
927 private int mTotalWakelockReleases = 0;
928 private long mTotalWakelockDurationMs = 0;
929 private long mMaxWakelockDurationMs = 0;
930 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900931
Hugo Benichi208c0102016-07-28 17:53:06 +0900932 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900933
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700934 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900935 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700936
Erik Kline95ecfee2016-10-02 18:02:14 +0900937 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900938 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900939
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900940 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800941 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
942 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800943
Patrick Rohr2857ac42022-01-21 14:58:16 +0100944 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
945 // configured via {@link
946 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
947 // Only the handler thread is allowed to access this field.
948 private long mIngressRateLimit = -1;
949
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900950 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
951 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900952 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900953 @GuardedBy("mSelfCertifiedCapabilityCache")
954 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
955 mSelfCertifiedCapabilityCache = new HashMap<>();
956
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900957 // Flag to enable the feature of closing frozen app sockets.
958 private final boolean mDestroyFrozenSockets;
959
960 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
961 private final boolean mDelayDestroyFrozenSockets;
962
963 // Uids that ConnectivityService is pending to close sockets of.
964 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
965
Robert Greenwalt802c1102014-06-02 15:32:02 -0700966 /**
967 * Implements support for the legacy "one network per network type" model.
968 *
969 * We used to have a static array of NetworkStateTrackers, one for each
970 * network type, but that doesn't work any more now that we can have,
971 * for example, more that one wifi network. This class stores all the
972 * NetworkAgentInfo objects that support a given type, but the legacy
973 * API will only see the first one.
974 *
975 * It serves two main purposes:
976 *
977 * 1. Provide information about "the network for a given type" (since this
978 * API only supports one).
979 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
980 * the first network for a given type changes, or if the default network
981 * changes.
982 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900983 @VisibleForTesting
984 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900985
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900986 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900987 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900988
Robert Greenwalt802c1102014-06-02 15:32:02 -0700989 /**
990 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
991 * Each list holds references to all NetworkAgentInfos that are used to
992 * satisfy requests for that network type.
993 *
994 * This array is built out at startup such that an unsupported network
995 * doesn't get an ArrayList instance, making this a tristate:
996 * unsupported, supported but not active and active.
997 *
998 * The actual lists are populated when we scan the network types that
999 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +09001000 *
1001 * Threading model:
1002 * - addSupportedType() is only called in the constructor
1003 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1004 * They are therefore not thread-safe with respect to each other.
1005 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1006 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001007 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001008 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001009 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001010 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001011 @NonNull
1012 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001013
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001014 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1015 // an entry have no timer (equivalent to -1). Lazily loaded.
1016 @NonNull
1017 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1018
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001019 LegacyTypeTracker(@NonNull ConnectivityService service) {
1020 mService = service;
1021 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001022 }
1023
Chiachang Wang3bc52762021-11-25 14:17:57 +08001024 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1025 // addressed.
1026 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001027 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1028 final PackageManager pm = ctx.getPackageManager();
1029 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1030 addSupportedType(TYPE_WIFI);
1031 }
1032 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1033 addSupportedType(TYPE_WIFI_P2P);
1034 }
1035 if (tm.isDataCapable()) {
1036 // Telephony does not have granular support for these types: they are either all
1037 // supported, or none is supported
1038 addSupportedType(TYPE_MOBILE);
1039 addSupportedType(TYPE_MOBILE_MMS);
1040 addSupportedType(TYPE_MOBILE_SUPL);
1041 addSupportedType(TYPE_MOBILE_DUN);
1042 addSupportedType(TYPE_MOBILE_HIPRI);
1043 addSupportedType(TYPE_MOBILE_FOTA);
1044 addSupportedType(TYPE_MOBILE_IMS);
1045 addSupportedType(TYPE_MOBILE_CBS);
1046 addSupportedType(TYPE_MOBILE_IA);
1047 addSupportedType(TYPE_MOBILE_EMERGENCY);
1048 }
1049 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1050 addSupportedType(TYPE_BLUETOOTH);
1051 }
1052 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1053 // TYPE_PROXY is only used on Wear
1054 addSupportedType(TYPE_PROXY);
1055 }
1056 // Ethernet is often not specified in the configs, although many devices can use it via
1057 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001058 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001059 addSupportedType(TYPE_ETHERNET);
1060 }
1061
1062 // Always add TYPE_VPN as a supported type
1063 addSupportedType(TYPE_VPN);
1064 }
1065
1066 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001067 if (mTypeLists[type] != null) {
1068 throw new IllegalStateException(
1069 "legacy list for type " + type + "already initialized");
1070 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001071 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001072 }
1073
Robert Greenwalt802c1102014-06-02 15:32:02 -07001074 public boolean isTypeSupported(int type) {
1075 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1076 }
1077
1078 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001079 synchronized (mTypeLists) {
1080 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1081 return mTypeLists[type].get(0);
1082 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001083 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001084 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001085 }
1086
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001087 public int getRestoreTimerForType(int type) {
1088 synchronized (mTypeLists) {
1089 if (mRestoreTimers == null) {
1090 mRestoreTimers = loadRestoreTimers();
1091 }
1092 return mRestoreTimers.getOrDefault(type, -1);
1093 }
1094 }
1095
1096 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1097 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001098 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001099 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1100 for (final String config : configs) {
1101 final String[] splits = TextUtils.split(config, ",");
1102 if (splits.length != 2) {
1103 logwtf("Invalid restore timer token count: " + config);
1104 continue;
1105 }
1106 try {
1107 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1108 } catch (NumberFormatException e) {
1109 logwtf("Invalid restore timer number format: " + config, e);
1110 }
1111 }
1112 return ret;
1113 }
1114
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001115 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001116 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001117 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001118 log("Sending " + state
1119 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001120 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001121 }
1122 }
1123
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001124 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1125 // network type, to preserve previous behaviour.
1126 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1127 if (vpnNai != mService.getLegacyLockdownNai()) return;
1128
1129 if (vpnNai.declaredUnderlyingNetworks == null
1130 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1131 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1132 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1133 return;
1134 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001135 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001136 vpnNai.declaredUnderlyingNetworks[0]);
1137 if (underlyingNai == null) return;
1138
1139 final int type = underlyingNai.networkInfo.getType();
1140 final DetailedState state = DetailedState.CONNECTED;
1141 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1142 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1143 }
1144
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001145 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001146 public void add(int type, NetworkAgentInfo nai) {
1147 if (!isTypeSupported(type)) {
1148 return; // Invalid network type.
1149 }
1150 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1151
1152 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1153 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001154 return;
1155 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001156 synchronized (mTypeLists) {
1157 list.add(nai);
1158 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001159
Chalard Jean5b409c72021-02-04 13:12:59 +09001160 // Send a broadcast if this is the first network of its type or if it's the default.
1161 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001162
1163 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1164 // to preserve previous behaviour.
1165 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001166 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001167 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1168 mService.sendLegacyNetworkBroadcast(nai, state, type);
1169 }
1170
1171 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1172 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001173 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001174 }
1175
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001176 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001177 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001178 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1179 if (list == null || list.isEmpty()) {
1180 return;
1181 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001182 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001183
Hugo Benichi389633f2016-06-21 09:48:07 +09001184 synchronized (mTypeLists) {
1185 if (!list.remove(nai)) {
1186 return;
1187 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001188 }
1189
Lorenzo Colitti49767722015-05-01 00:30:10 +09001190 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001191 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1192 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001193 }
1194
1195 if (!list.isEmpty() && wasFirstNetwork) {
1196 if (DBG) log("Other network available for type " + type +
1197 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001198 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001199 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001200 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001201 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001202 }
1203 }
1204
1205 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001206 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1207 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001208 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001209 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001210 }
1211 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001212
Chalard Jean46bfbf02022-02-02 00:56:25 +09001213 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001214 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001215 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001216 final DetailedState state = nai.networkInfo.getDetailedState();
1217 for (int type = 0; type < mTypeLists.length; type++) {
1218 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001219 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001220 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001221 if (isFirst || contains && isDefault) {
1222 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001223 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001224 }
1225 }
1226 }
1227
Robert Greenwalt94e22142014-07-30 16:31:24 -07001228 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001229 pw.println("mLegacyTypeTracker:");
1230 pw.increaseIndent();
1231 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001232 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001233 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001234 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001235 pw.println();
1236 pw.println("Current state:");
1237 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001238 synchronized (mTypeLists) {
1239 for (int type = 0; type < mTypeLists.length; type++) {
1240 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1241 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001242 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001243 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001244 }
1245 }
1246 pw.decreaseIndent();
1247 pw.decreaseIndent();
1248 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001249 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001250 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001251 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001252
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001253 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001254 /**
1255 * Helper class which parses out priority arguments and dumps sections according to their
1256 * priority. If priority arguments are omitted, function calls the legacy dump command.
1257 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001258 private class LocalPriorityDump {
1259 private static final String PRIORITY_ARG = "--dump-priority";
1260 private static final String PRIORITY_ARG_HIGH = "HIGH";
1261 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
Junyu Laif8dba342023-10-12 17:01:03 +08001262 private static final int DUMPSYS_DEFAULT_TIMEOUT_MS = 10_000;
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001263
1264 LocalPriorityDump() {}
1265
1266 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
Junyu Laif8dba342023-10-12 17:01:03 +08001267 if (!HandlerUtils.runWithScissors(mHandler, () -> {
1268 doDump(fd, pw, new String[]{DIAG_ARG});
1269 doDump(fd, pw, new String[]{SHORT_ARG});
1270 }, DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1271 pw.println("dumpHigh timeout");
1272 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001273 }
1274
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001275 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
Junyu Laif8dba342023-10-12 17:01:03 +08001276 if (!HandlerUtils.runWithScissors(mHandler, () -> doDump(fd, pw, args),
1277 DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1278 pw.println("dumpNormal timeout");
1279 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001280 }
1281
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001282 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1283 if (args == null) {
1284 dumpNormal(fd, pw, args);
1285 return;
1286 }
1287
1288 String priority = null;
1289 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1290 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1291 argIndex++;
1292 priority = args[argIndex];
1293 }
1294 }
1295
1296 if (PRIORITY_ARG_HIGH.equals(priority)) {
1297 dumpHigh(fd, pw);
1298 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1299 dumpNormal(fd, pw, args);
1300 } else {
1301 // ConnectivityService publishes binder service using publishBinderService() with
1302 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001303 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1304 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001305 // TODO: Integrate into signal dump.
1306 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001307 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001308 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001309 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001310
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001311 /**
1312 * Dependencies of ConnectivityService, for injection in tests.
1313 */
1314 @VisibleForTesting
1315 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001316 public int getCallingUid() {
1317 return Binder.getCallingUid();
1318 }
1319
Chalard Jeandf29a852023-05-29 17:02:43 +09001320 public boolean isAtLeastS() {
1321 return SdkLevel.isAtLeastS();
1322 }
1323
1324 public boolean isAtLeastT() {
1325 return SdkLevel.isAtLeastT();
1326 }
1327
1328 public boolean isAtLeastU() {
1329 return SdkLevel.isAtLeastU();
1330 }
1331
Chalard Jeaneb663892023-10-07 15:17:07 +09001332 public boolean isAtLeastV() {
1333 return SdkLevel.isAtLeastV();
1334 }
1335
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001336 /**
1337 * Get system properties to use in ConnectivityService.
1338 */
1339 public MockableSystemProperties getSystemProperties() {
1340 return new MockableSystemProperties();
1341 }
1342
1343 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001344 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1345 */
1346 public ConnectivityResources getResources(@NonNull Context ctx) {
1347 return new ConnectivityResources(ctx);
1348 }
1349
1350 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001351 * Create a HandlerThread to use in ConnectivityService.
1352 */
1353 public HandlerThread makeHandlerThread() {
1354 return new HandlerThread("ConnectivityServiceThread");
1355 }
1356
1357 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001358 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001359 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001360 public NetworkStackClientBase getNetworkStack() {
1361 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001362 }
1363
1364 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001365 * @see ProxyTracker
1366 */
1367 public ProxyTracker makeProxyTracker(@NonNull Context context,
1368 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001369 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001370 }
1371
1372 /**
1373 * @see NetIdManager
1374 */
1375 public NetIdManager makeNetIdManager() {
1376 return new NetIdManager();
1377 }
1378
1379 /**
1380 * @see NetworkUtils#queryUserAccess(int, int)
1381 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001382 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1383 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001384 }
1385
1386 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001387 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1388 * requires CAP_NET_ADMIN, which the unit tests do not have.
1389 */
1390 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1391 InetSocketAddress remote) {
1392 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1393 }
1394
1395 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001396 * @see MultinetworkPolicyTracker
1397 */
1398 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1399 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1400 return new MultinetworkPolicyTracker(c, h, r);
1401 }
1402
Aaron Huang330a4c02020-10-27 03:36:19 +08001403 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001404 * @see AutomaticOnOffKeepaliveTracker
1405 */
1406 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1407 @NonNull Context c, @NonNull Handler h) {
1408 return new AutomaticOnOffKeepaliveTracker(c, h);
1409 }
1410
1411 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001412 * @see BatteryStatsManager
1413 */
1414 public void reportNetworkInterfaceForTransports(Context context, String iface,
1415 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001416 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001417 context.getSystemService(BatteryStatsManager.class);
1418 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1419 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001420
1421 public boolean getCellular464XlatEnabled() {
1422 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1423 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001424
1425 /**
1426 * @see PendingIntent#intentFilterEquals
1427 */
1428 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1429 return a.intentFilterEquals(b);
1430 }
1431
1432 /**
1433 * @see LocationPermissionChecker
1434 */
1435 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1436 return new LocationPermissionChecker(context);
1437 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001438
1439 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001440 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001441 *
1442 * This method returns null in versions before T, where carrier privilege
1443 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001444 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001445 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001446 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1447 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001448 if (isAtLeastT()) {
Chalard Jean84dfa9f2023-01-30 11:23:20 +09001449 return new CarrierPrivilegeAuthenticator(context, this, tm);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001450 } else {
1451 return null;
1452 }
1453 }
1454
1455 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001456 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001457 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001458 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001459 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001460 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001461
1462 /**
1463 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001464 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001465 * @return BpfNetMaps implementation.
1466 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001467 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1468 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001469 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001470
1471 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001472 * @see ClatCoordinator
1473 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001474 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001475 public ClatCoordinator getClatCoordinator(INetd netd) {
1476 return new ClatCoordinator(
1477 new ClatCoordinator.Dependencies() {
1478 @NonNull
1479 public INetd getNetd() {
1480 return netd;
1481 }
1482 });
1483 }
1484
1485 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001486 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1487 */
1488 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1489 final InterfaceParams params = InterfaceParams.getByName(iface);
1490 if (params == null) {
1491 // the interface might have disappeared.
1492 logw("Failed to get interface params for interface " + iface);
1493 return;
1494 }
1495 try {
1496 // converting rateInBytesPerSecond from long to int is safe here because the
1497 // setting's range is limited to INT_MAX.
1498 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001499 Log.i(TAG,
1500 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001501 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1502 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1503 } catch (IOException e) {
1504 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1505 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1506 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1507 + ") failure: ", e);
1508 }
1509 }
1510
1511 /**
1512 * Wraps {@link TcUtils#tcFilterDelDev}
1513 */
1514 public void disableIngressRateLimit(String iface) {
1515 final InterfaceParams params = InterfaceParams.getByName(iface);
1516 if (params == null) {
1517 // the interface might have disappeared.
1518 logw("Failed to get interface params for interface " + iface);
1519 return;
1520 }
1521 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001522 Log.i(TAG,
1523 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001524 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1525 } catch (IOException e) {
1526 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1527 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1528 }
1529 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001530
1531 /**
1532 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1533 */
1534 // TODO: when available in all active branches:
1535 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1536 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1537 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1538 return BroadcastOptionsShimImpl.newInstance(options);
1539 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001540
1541 /**
1542 * Wrapper method for
1543 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1544 *
1545 * @param changeId The ID of the compatibility change in question.
1546 * @param packageName The package name of the app in question.
1547 * @param user The user that the operation is done for.
1548 * @return {@code true} if the change is enabled for the specified package.
1549 */
1550 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1551 @NonNull final UserHandle user) {
1552 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1553 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001554
1555 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001556 * As above but with a UID.
1557 * @see CompatChanges#isChangeEnabled(long, int)
1558 */
1559 public boolean isChangeEnabled(final long changeId, final int uid) {
1560 return CompatChanges.isChangeEnabled(changeId, uid);
1561 }
1562
1563 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001564 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1565 *
1566 * @param ranges target uid ranges
1567 * @param exemptUids uids to skip close socket
1568 */
1569 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1570 @NonNull final Set<Integer> exemptUids)
1571 throws SocketException, InterruptedIOException, ErrnoException {
1572 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1573 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001574
1575 /**
1576 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1577 *
1578 * @param ownerUids target uids to close sockets
1579 */
1580 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1581 throws SocketException, InterruptedIOException, ErrnoException {
1582 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1583 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001584
1585 /**
1586 * Schedule the evaluation timeout.
1587 *
1588 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1589 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1590 * of these events happen, this time will run out, after which the network is considered
1591 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1592 * on this network and considers it won't provide connectivity. In particular, that means
1593 * it's when the system prefers it to cell if it's wifi and configuration says it should
1594 * prefer bad wifi to cell.
1595 */
1596 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1597 @NonNull final Network network, final long delayMs) {
1598 handler.sendMessageDelayed(
1599 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1600 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001601 }
1602
junyulaie7c7d2a2021-01-26 15:29:15 +08001603 public ConnectivityService(Context context) {
1604 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001605 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1606 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001607 }
1608
1609 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001610 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1611 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001612 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001613
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001614 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001615 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001616 mSystemProperties = mDeps.getSystemProperties();
1617 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001618 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001619 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001620 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1621 // Pass limit - 1 to maintain backward compatibility.
1622 // TODO: Remove the workaround.
1623 mNetworkRequestCounter =
1624 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1625 mSystemNetworkRequestCounter =
1626 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001627
Hugo Benichi208c0102016-07-28 17:53:06 +09001628 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001629 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1630 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001631 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001632 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001633 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001634 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1635 mDefaultNetworkRequests.add(mDefaultRequest);
1636 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001637
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001638 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001639 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001640
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001641 // The default WiFi request is a background request so that apps using WiFi are
1642 // migrated to a better network (typically ethernet) when one comes up, instead
1643 // of staying on WiFi forever.
1644 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1645 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1646
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001647 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1648 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1649 NetworkRequest.Type.BACKGROUND_REQUEST);
1650
Chalard Jean0702f982021-09-16 21:50:07 +09001651 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1652 // TODO: Consider making the timer customizable.
1653 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1654 mCellularRadioTimesharingCapable =
1655 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1656
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001657 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1658 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1659
1660 if (SdkLevel.isAtLeastU()) {
1661 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1662 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1663 final int defaultUMarkMask = 0x80000000; // u32
1664
1665 if ((mark == 0) || (mask == 0)) {
1666 // simply treat unset/disabled as the default U value
1667 mark = defaultUMarkMask;
1668 mask = defaultUMarkMask;
1669 }
1670 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1671 // invalid device overlay settings
1672 throw new IllegalArgumentException(
1673 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1674 }
1675 }
1676
1677 mWakeUpMark = mark;
1678 mWakeUpMask = mask;
1679
Paul Hu51f816b2022-08-11 14:43:47 +00001680 mNetd = netd;
1681 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001682 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001683 mPermissionMonitor =
1684 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001685 mHandlerThread.start();
1686 mHandler = new InternalHandler(mHandlerThread.getLooper());
1687 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001688 mConnectivityDiagnosticsHandler =
1689 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001690
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001691 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001692 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001693
junyulaie7c7d2a2021-01-26 15:29:15 +08001694 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001695 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001696 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001697 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001698
Wink Saville32506bc2013-06-29 21:10:57 -07001699 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001700 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001701 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001702 mCarrierPrivilegeAuthenticator =
1703 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001704
Sudheer Shanka9967d462021-03-18 19:09:25 +00001705 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001706 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1707 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001708 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001709
1710 final PowerManager powerManager = (PowerManager) context.getSystemService(
1711 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001712 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001713 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001714
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001715 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1716 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001717 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001718 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001719 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001720 mProtectedNetworks.add(p);
1721 } else {
1722 if (DBG) loge("Ignoring protectedNetwork " + p);
1723 }
1724 }
1725
soma, kawata29444ae2019-05-23 09:30:40 +09001726 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1727
James Mattis02220e22021-03-13 19:27:21 -08001728 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001729 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001730 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001731 final IntentFilter userIntentFilter = new IntentFilter();
1732 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1733 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1734 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1735 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001736
James Mattis02220e22021-03-13 19:27:21 -08001737 // Listen to package add/removes for netd
1738 final IntentFilter packageIntentFilter = new IntentFilter();
1739 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1740 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1741 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1742 packageIntentFilter.addDataScheme("package");
1743 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001744 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001745
Motomu Utsumi1e51a642023-07-18 15:11:41 +09001746 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001747
Chalard Jean46bfbf02022-02-02 00:56:25 +09001748 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001749 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001750 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001751 } catch (RemoteException | ServiceSpecificException e) {
1752 loge("Error registering event listener :" + e);
1753 }
1754
Erik Kline05f2b402015-04-30 12:58:40 +09001755 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1756 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001757
chiachangwang7c17c282023-02-02 05:58:59 +00001758 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001759 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001760 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001761
1762 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001763 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001764 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1765 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001766 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001767 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1768 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001769
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001770 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001771 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001772 mNetworkRanker =
1773 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1774
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001775 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001776
Chiachang Wangc1215d32020-10-20 15:38:58 +08001777 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001778 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001779
Chalard Jean28018572020-12-21 18:36:52 +09001780 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1781 // request that doesn't allow fallback to the default network. It should never be visible
1782 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1783 // arguments like the handler or the DnsResolver.
1784 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001785 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001786 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001787 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09001788 new LinkProperties(), new NetworkCapabilities(), null /* localNetworkConfig */,
Chalard Jean28018572020-12-21 18:36:52 +09001789 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001790 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1791 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001792
1793 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001794 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1795 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1796 // Even if it could, running on S would at least require mocking out the BPF map,
1797 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1798 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001799 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001800 mDscpPolicyTracker = new DscpPolicyTracker();
1801 }
Tyler Wear72388212021-09-09 14:49:02 -07001802 } catch (ErrnoException e) {
1803 loge("Unable to create DscpPolicyTracker");
1804 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001805
1806 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1807 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001808
Chalard Jeandf29a852023-05-29 17:02:43 +09001809 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001810 mCdmps = new CompanionDeviceManagerProxyService(context);
1811 } else {
1812 mCdmps = null;
1813 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001814
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001815 mDestroyFrozenSockets = mDeps.isAtLeastU()
1816 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
1817 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1818 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
1819 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001820 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1821 new UidFrozenStateChangedCallback() {
1822 @Override
1823 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1824 if (uids.length != frozenStates.length) {
1825 Log.wtf(TAG, "uids has length " + uids.length
1826 + " but frozenStates has length " + frozenStates.length);
1827 return;
1828 }
1829
1830 final UidFrozenStateChangedArgs args =
1831 new UidFrozenStateChangedArgs(uids, frozenStates);
1832
1833 mHandler.sendMessage(
1834 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1835 }
1836 };
1837
1838 final ActivityManager activityManager =
1839 mContext.getSystemService(ActivityManager.class);
1840 activityManager.registerUidFrozenStateChangedCallback(
1841 (Runnable r) -> r.run(), frozenStateChangedCallback);
1842 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001843 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001844
Xiao Ma0a171c02022-01-23 16:14:51 +00001845 /**
1846 * Check whether or not the device supports Ethernet transport.
1847 */
1848 public static boolean deviceSupportsEthernet(final Context context) {
1849 final PackageManager pm = context.getPackageManager();
1850 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1851 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1852 }
1853
Chalard Jean46adcf32018-04-18 20:18:38 +09001854 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001855 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1856 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001857 }
1858
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001859 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1860 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001861 final NetworkCapabilities netCap = new NetworkCapabilities();
1862 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001863 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001864 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001865 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001866 return netCap;
1867 }
1868
James Mattis45d81842021-01-10 14:24:24 -08001869 private NetworkRequest createDefaultRequest() {
1870 return createDefaultInternetRequestForTransport(
1871 TYPE_NONE, NetworkRequest.Type.REQUEST);
1872 }
1873
lucaslin3ba7cc22022-12-19 02:35:33 +00001874 private NetworkRequest createVpnRequest() {
1875 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1876 .withoutDefaultCapabilities()
1877 .addTransportType(TRANSPORT_VPN)
1878 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1879 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1880 .build();
1881 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1882 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1883 }
1884
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001885 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001886 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001887 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001888 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001889 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001890 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001891 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001892 netCap.addTransportType(transportType);
1893 }
James Mattis45d81842021-01-10 14:24:24 -08001894 return createNetworkRequest(type, netCap);
1895 }
1896
1897 private NetworkRequest createNetworkRequest(
1898 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001899 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001900 }
1901
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001902 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1903 NetworkRequest.Type type) {
1904 final NetworkCapabilities netCap = new NetworkCapabilities();
1905 netCap.clearAll();
1906 netCap.addCapability(capability);
1907 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1908 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1909 }
1910
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001911 // Used only for testing.
1912 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001913 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001914 // changing ContentResolver to make registerContentObserver non-final).
1915 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1916 // by subclassing SettingsObserver.
1917 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001918 void updateAlwaysOnNetworks() {
1919 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001920 }
1921
Erik Kline9a62f012018-03-21 07:18:33 -07001922 // See FakeSettingsProvider comment above.
1923 @VisibleForTesting
1924 void updatePrivateDnsSettings() {
1925 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1926 }
1927
paulhu51f77dc2021-06-07 02:34:20 +00001928 @VisibleForTesting
1929 void updateMobileDataPreferredUids() {
1930 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1931 }
1932
Patrick Rohr2857ac42022-01-21 14:58:16 +01001933 @VisibleForTesting
1934 void updateIngressRateLimit() {
1935 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1936 }
1937
Aaron Huang40b52442021-06-08 04:34:24 +08001938 @VisibleForTesting
1939 void simulateUpdateProxyInfo(@Nullable final Network network,
1940 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001941 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08001942 new Pair<>(network, proxyInfo)).sendToTarget();
1943 }
1944
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001945 private void handleAlwaysOnNetworkRequest(
1946 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001947 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001948 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001949 handleAlwaysOnNetworkRequest(networkRequest, enable);
1950 }
1951
1952 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001953 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001954 if (enable == isEnabled) {
1955 return; // Nothing to do.
1956 }
1957
1958 if (enable) {
1959 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001960 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001961 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001962 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001963 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001964 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1965 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001966 }
1967 }
1968
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001969 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001970 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1971 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1972 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1973 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001974 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1975 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001976 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001977 }
1978
paulhu51f77dc2021-06-07 02:34:20 +00001979 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001980 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001981 private void registerSettingsCallbacks() {
1982 // Watch for global HTTP proxy changes.
1983 mSettingsObserver.observe(
1984 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1985 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1986
Chalard Jean46bfbf02022-02-02 00:56:25 +09001987 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001988 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001989 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001990 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1991
Chalard Jean46bfbf02022-02-02 00:56:25 +09001992 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001993 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001994 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001995 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001996
1997 // Watch for mobile data preferred uids changes.
1998 mSettingsObserver.observe(
1999 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
2000 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002001
2002 // Watch for ingress rate limit changes.
2003 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002004 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002005 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2006 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002007 }
2008
Erik Kline31b4a9e2018-01-11 21:07:29 +09002009 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002010 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2011 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002012 }
2013 }
2014
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002015 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002016 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2017 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002018 return mNextNetworkRequestId++;
2019 }
2020
junyulai74f9a8b2018-06-13 15:00:37 +08002021 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002022 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002023 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002024 if (network == null) {
2025 return null;
2026 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002027 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002028 }
2029
2030 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002031 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002032 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002033 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002034 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002035
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002036 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002037 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002038 private NetworkAgentInfo getVpnForUid(int uid) {
2039 synchronized (mNetworkForNetId) {
2040 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2041 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002042 if (nai.isVPN() && nai.everConnected()
2043 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002044 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002045 }
2046 }
2047 }
2048 return null;
2049 }
2050
Chalard Jean46bfbf02022-02-02 00:56:25 +09002051 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002052 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002053 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002054 final NetworkAgentInfo nai = getVpnForUid(uid);
2055 if (nai != null) return nai.declaredUnderlyingNetworks;
2056 return null;
2057 }
2058
Lorenzo Colittia7574052021-01-19 01:33:05 +09002059 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002060 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002061
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002062 final Network[] networks = getVpnUnderlyingNetworks(uid);
2063 if (networks != null) {
2064 // getUnderlyingNetworks() returns:
2065 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2066 // empty array => the VPN explicitly said "no default network".
2067 // non-empty array => the VPN specified one or more default networks; we use the
2068 // first one.
2069 if (networks.length > 0) {
2070 nai = getNetworkAgentInfoForNetwork(networks[0]);
2071 } else {
2072 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002073 }
2074 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002075 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002076 }
2077
2078 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002079 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002080 */
paulhu7aeba372020-12-30 00:42:19 +08002081 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2082 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002083 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002084 if (ignoreBlocked) {
2085 return false;
2086 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002087 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002088 final long ident = Binder.clearCallingIdentity();
2089 try {
2090 final boolean metered = nc == null ? true : nc.isMetered();
2091 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2092 } finally {
2093 Binder.restoreCallingIdentity(ident);
2094 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002095 }
2096
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002097 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002098 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2099 return;
2100 }
Hugo Benichi47011212017-03-30 10:46:05 +09002101 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002102 synchronized (mBlockedAppUids) {
2103 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002104 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002105 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002106 blocked = false;
2107 } else {
2108 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002109 }
2110 }
Hugo Benichi47011212017-03-30 10:46:05 +09002111 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2112 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2113 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002114 }
2115
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002116 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002117 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2118 return;
2119 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002120 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002121 final int requestId = nri.getActiveRequest() != null
2122 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002123 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002124 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002125 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002126 }
2127
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002128 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002129 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002130 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002131 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002132 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002133 @NonNull
2134 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2135 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002136 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2137 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2138 // but only exists if an app asks about them or requests them. Ensure the requesting app
2139 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002140 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002141 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2142 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2143 null /* extraInfo */);
2144 }
2145 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002146 return filtered;
2147 }
2148
2149 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2150 boolean ignoreBlocked) {
2151 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2152 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002153 }
2154
2155 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002156 * Return NetworkInfo for the active (i.e., connected) network interface.
2157 * It is assumed that at most one network is active at a time. If more
2158 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002159 * @return the info for the active network, or {@code null} if none is
2160 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002161 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002162 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002163 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002164 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002165 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002166 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002167 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2168 if (nai == null) return null;
2169 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2170 maybeLogBlockedNetworkInfo(networkInfo, uid);
2171 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002172 }
2173
Paul Jensen1f567382015-02-13 14:18:39 -05002174 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002175 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002176 public Network getActiveNetwork() {
2177 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002178 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002179 }
2180
2181 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002182 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002183 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002184 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002185 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002186 }
2187
Chalard Jean46bfbf02022-02-02 00:56:25 +09002188 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002189 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002190 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2191 if (vpnNai != null) {
2192 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2193 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2194 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002195 }
Paul Jensen1f567382015-02-13 14:18:39 -05002196 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002197
James Mattis2516da32021-01-31 17:06:19 -08002198 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002199 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2200 ignoreBlocked)) {
2201 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002202 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002203 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002204 }
2205
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002206 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002207 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002208 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002209 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002210 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2211 if (nai == null) return null;
2212 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002213 }
2214
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002215 /** Returns a NetworkInfo object for a network that doesn't exist. */
2216 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2217 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2218 getNetworkTypeName(networkType), "" /* subtypeName */);
2219 info.setIsAvailable(true);
2220 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2221 // background data is restricted.
2222 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2223 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2224 ? DetailedState.BLOCKED
2225 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002226 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2227 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002228 return info;
2229 }
2230
Lorenzo Colittia7574052021-01-19 01:33:05 +09002231 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002232 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2233 return null;
2234 }
2235 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002236 if (nai == null) {
2237 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002238 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002239 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2240 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002241 }
2242
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002243 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002244 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002245 public NetworkInfo getNetworkInfo(int networkType) {
2246 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002247 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002248 if (getVpnUnderlyingNetworks(uid) != null) {
2249 // A VPN is active, so we may need to return one of its underlying networks. This
2250 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002251 // getNetworkAgentInfoForUid.
2252 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2253 if (nai == null) return null;
2254 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2255 if (networkInfo.getType() == networkType) {
2256 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002257 }
2258 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002259 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002260 }
2261
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002262 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002263 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002264 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002265 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002266 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002267 if (nai == null) return null;
2268 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002269 }
2270
2271 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002272 public NetworkInfo[] getAllNetworkInfo() {
2273 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002274 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002275 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2276 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002277 NetworkInfo info = getNetworkInfo(networkType);
2278 if (info != null) {
2279 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002280 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002281 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002282 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002283 }
2284
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002285 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002286 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002287 public Network getNetworkForType(int networkType) {
2288 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002289 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2290 return null;
2291 }
2292 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2293 if (nai == null) {
2294 return null;
2295 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002296 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002297 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2298 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002299 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002300 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002301 }
2302
2303 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002304 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002305 public Network[] getAllNetworks() {
2306 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002307 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002308 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002309 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002310 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002311 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002312 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002313 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002314 }
2315
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002316 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002317 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002318 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002319 // The basic principle is: if an app's traffic could possibly go over a
2320 // network, without the app doing anything multinetwork-specific,
2321 // (hence, by "default"), then include that network's capabilities in
2322 // the array.
2323 //
2324 // In the normal case, app traffic only goes over the system's default
2325 // network connection, so that's the only network returned.
2326 //
2327 // With a VPN in force, some app traffic may go into the VPN, and thus
2328 // over whatever underlying networks the VPN specifies, while other app
2329 // traffic may go over the system default network (e.g.: a split-tunnel
2330 // VPN, or an app disallowed by the VPN), so the set of networks
2331 // returned includes the VPN's underlying networks and the system
2332 // default.
2333 enforceAccessPermission();
2334
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002335 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002336
James Mattis2516da32021-01-31 17:06:19 -08002337 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2338 if (!nri.isBeingSatisfied()) {
2339 continue;
2340 }
2341 final NetworkAgentInfo nai = nri.getSatisfier();
2342 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2343 if (null != nc
2344 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2345 && !result.containsKey(nai.network)) {
2346 result.put(
2347 nai.network,
2348 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002349 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002350 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2351 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002352 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002353 }
2354
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002355 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002356 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002357 if (null != networks) {
2358 for (final Network network : networks) {
2359 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2360 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002361 result.put(
2362 network,
2363 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002364 nc,
2365 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002366 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002367 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002368 }
2369 }
2370 }
2371
2372 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2373 out = result.values().toArray(out);
2374 return out;
2375 }
2376
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002377 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2378 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2379 // can call sampleConnectivityState and make the checks on it.
2380 @NonNull
2381 private StatsEvent sampleConnectivityStateToStatsEvent() {
2382 final ConnectivityStateSample sample = sampleConnectivityState();
2383 return ConnectivityStatsLog.buildStatsEvent(
2384 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2385 sample.getNetworkCountPerTransports().toByteArray(),
2386 sample.getConnectionDurationPerTransports().toByteArray(),
2387 sample.getNetworkRequestCount().toByteArray(),
2388 sample.getNetworks().toByteArray());
2389 }
2390
2391 /**
2392 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2393 *
2394 * This is used for metrics. These snapshots will be sampled and constitute a base for
2395 * statistics about connectivity state of devices.
2396 */
2397 @VisibleForTesting
2398 @NonNull
2399 public ConnectivityStateSample sampleConnectivityState() {
2400 ensureRunningOnConnectivityServiceThread();
2401 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2402 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2403 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2404 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2405 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2406 return builder.build();
2407 }
2408
2409 private static NetworkCountPerTransports sampleNetworkCount(
2410 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2411 final SparseIntArray countPerTransports = new SparseIntArray();
2412 for (final NetworkAgentInfo nai : nais) {
2413 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2414 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2415 }
2416 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2417 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2418 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2419 c.setTransportTypes(countPerTransports.keyAt(i));
2420 c.setNetworkCount(countPerTransports.valueAt(i));
2421 builder.addNetworkCountForTransports(c);
2422 }
2423 return builder.build();
2424 }
2425
2426 private static ConnectionDurationPerTransports sampleConnectionDuration(
2427 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2428 final ConnectionDurationPerTransports.Builder builder =
2429 ConnectionDurationPerTransports.newBuilder();
2430 for (final NetworkAgentInfo nai : nais) {
2431 final ConnectionDurationForTransports.Builder c =
2432 ConnectionDurationForTransports.newBuilder();
2433 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2434 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2435 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2436 // Add millisPerSecond/2 to round up or down to the nearest value
2437 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2438 builder.addConnectionDurationForTransports(c);
2439 }
2440 return builder.build();
2441 }
2442
2443 private static NetworkRequestCount sampleNetworkRequestCount(
2444 @NonNull final Collection<NetworkRequestInfo> nris) {
2445 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2446 final SparseIntArray countPerType = new SparseIntArray();
2447 for (final NetworkRequestInfo nri : nris) {
2448 final int type;
2449 if (Process.SYSTEM_UID == nri.mAsUid) {
2450 // The request is filed "as" the system, so it's the system on its own behalf.
2451 type = RequestType.RT_SYSTEM.getNumber();
2452 } else if (Process.SYSTEM_UID == nri.mUid) {
2453 // The request is filed by the system as some other app, so it's the system on
2454 // behalf of an app.
2455 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2456 } else {
2457 // Not the system, so it's an app requesting on its own behalf.
2458 type = RequestType.RT_APP.getNumber();
2459 }
2460 countPerType.put(type, countPerType.get(type, 0));
2461 }
2462 for (int i = countPerType.size() - 1; i >= 0; --i) {
2463 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2464 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2465 r.setRequestCount(countPerType.valueAt(i));
2466 builder.addRequestCountForType(r);
2467 }
2468 return builder.build();
2469 }
2470
2471 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2472 final NetworkList.Builder builder = NetworkList.newBuilder();
2473 for (final NetworkAgentInfo nai : nais) {
2474 final NetworkCapabilities nc = nai.networkCapabilities;
2475 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2476 d.setTransportTypes((int) nc.getTransportTypesInternal());
2477 final MeteredState meteredState;
2478 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2479 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2480 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2481 meteredState = MeteredState.METERED_NO;
2482 } else {
2483 meteredState = MeteredState.METERED_YES;
2484 }
2485 d.setMeteredState(meteredState);
2486 final ValidatedState validatedState;
2487 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2488 validatedState = ValidatedState.VS_PORTAL;
2489 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2490 validatedState = ValidatedState.VS_PARTIAL;
2491 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2492 validatedState = ValidatedState.VS_VALID;
2493 } else {
2494 validatedState = ValidatedState.VS_INVALID;
2495 }
2496 d.setValidatedState(validatedState);
2497 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2498 d.setCapabilities(nc.getCapabilitiesInternal());
2499 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2500 builder.addNetworkDescription(d);
2501 }
2502 return builder.build();
2503 }
2504
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002505 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002506 public boolean isNetworkSupported(int networkType) {
2507 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002508 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002509 }
2510
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002511 /**
2512 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002513 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002514 * @return the ip properties for the active network, or {@code null} if
2515 * none is active
2516 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002517 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002518 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002519 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002520 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002521 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2522 if (nai == null) return null;
2523 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002524 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002525 }
2526
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002527 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002528 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002529 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002530 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002531 final LinkProperties lp = getLinkProperties(nai);
2532 if (lp == null) return null;
2533 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002534 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002535 }
2536
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002537 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002538 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002539 public LinkProperties getLinkProperties(Network network) {
2540 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002541 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2542 if (lp == null) return null;
2543 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002544 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002545 }
2546
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002547 @Nullable
2548 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002549 if (nai == null) {
2550 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002551 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002552 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002553 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002554 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002555 }
2556
lucaslinc582d502022-01-27 09:07:00 +08002557 @Override
2558 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002559 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002560 @NonNull String packageName, @Nullable String callingAttributionTag) {
2561 Objects.requireNonNull(packageName);
2562 Objects.requireNonNull(lp);
2563 enforceNetworkStackOrSettingsPermission();
2564 if (!checkAccessPermission(-1 /* pid */, uid)) {
2565 return null;
2566 }
2567 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2568 }
2569
Qingxi Lib2748102020-01-08 12:51:49 -08002570 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2571 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2572 }
2573
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002574 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002575 if (nai == null) return null;
2576 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002577 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002578 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002579 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002580 }
2581
2582 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002583 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2584 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002585 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002586 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002587 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002588 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002589 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002590 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002591 }
2592
lucaslinc582d502022-01-27 09:07:00 +08002593 @Override
lucaslind2b06132022-03-02 10:56:57 +08002594 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2595 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2596 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002597 Objects.requireNonNull(nc);
2598 Objects.requireNonNull(packageName);
2599 enforceNetworkStackOrSettingsPermission();
2600 if (!checkAccessPermission(-1 /* pid */, uid)) {
2601 return null;
2602 }
2603 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2604 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2605 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2606 callingAttributionTag);
2607 }
2608
lucaslin69e1aa92022-03-22 18:15:09 +08002609 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2610 if (nc.getUnderlyingNetworks() != null
2611 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2612 nc.setUnderlyingNetworks(null);
2613 }
2614 }
2615
Qingxi Libb8da982020-01-17 17:54:27 -08002616 @VisibleForTesting
2617 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002618 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002619 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2620 // this would be expensive (one more permission check every time any NC callback is
2621 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2622 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2623 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002624 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002625 if (!checkSettingsPermission(callerPid, callerUid)) {
2626 newNc.setUids(null);
2627 newNc.setSSID(null);
2628 }
Etan Cohen107ae952018-12-30 17:59:59 -08002629 if (newNc.getNetworkSpecifier() != null) {
2630 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2631 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002632 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2633 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002634 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2635 newNc.setAdministratorUids(new int[0]);
2636 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002637 if (!checkAnyPermissionOf(mContext,
Benedict Wong53de25f2021-03-24 14:01:51 -07002638 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002639 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002640 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002641 }
lucaslin69e1aa92022-03-22 18:15:09 +08002642 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002643
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002644 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002645 }
2646
Roshan Pius98f59ec2021-02-23 08:47:39 -08002647 /**
2648 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002649 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002650 * NetworkCapabilities.
2651 * Note: This wrapper does not support any sort of invalidation and thus must not be
2652 * persistent or long-lived. It may only be used for the time necessary to
2653 * compute the redactions required by one particular NetworkCallback or
2654 * synchronous call.
2655 */
2656 private class RedactionPermissionChecker {
2657 private final int mCallingPid;
2658 private final int mCallingUid;
2659 @NonNull private final String mCallingPackageName;
2660 @Nullable private final String mCallingAttributionTag;
2661
2662 private Boolean mHasLocationPermission = null;
2663 private Boolean mHasLocalMacAddressPermission = null;
2664 private Boolean mHasSettingsPermission = null;
2665
2666 RedactionPermissionChecker(int callingPid, int callingUid,
2667 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2668 mCallingPid = callingPid;
2669 mCallingUid = callingUid;
2670 mCallingPackageName = callingPackageName;
2671 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002672 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002673
2674 private boolean hasLocationPermissionInternal() {
2675 final long token = Binder.clearCallingIdentity();
2676 try {
2677 return mLocationPermissionChecker.checkLocationPermission(
2678 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2679 null /* message */);
2680 } finally {
2681 Binder.restoreCallingIdentity(token);
2682 }
2683 }
2684
2685 /**
2686 * Returns whether the app holds location permission or not (might return cached result
2687 * if the permission was already checked before).
2688 */
2689 public boolean hasLocationPermission() {
2690 if (mHasLocationPermission == null) {
2691 // If there is no cached result, perform the check now.
2692 mHasLocationPermission = hasLocationPermissionInternal();
2693 }
2694 return mHasLocationPermission;
2695 }
2696
2697 /**
2698 * Returns whether the app holds local mac address permission or not (might return cached
2699 * result if the permission was already checked before).
2700 */
2701 public boolean hasLocalMacAddressPermission() {
2702 if (mHasLocalMacAddressPermission == null) {
2703 // If there is no cached result, perform the check now.
2704 mHasLocalMacAddressPermission =
2705 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2706 }
2707 return mHasLocalMacAddressPermission;
2708 }
2709
2710 /**
2711 * Returns whether the app holds settings permission or not (might return cached
2712 * result if the permission was already checked before).
2713 */
2714 public boolean hasSettingsPermission() {
2715 if (mHasSettingsPermission == null) {
2716 // If there is no cached result, perform the check now.
2717 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2718 }
2719 return mHasSettingsPermission;
2720 }
2721 }
2722
2723 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2724 @NetworkCapabilities.NetCapability long redaction) {
2725 return (redactions & redaction) != 0;
2726 }
2727
2728 /**
2729 * Use the provided |applicableRedactions| to check the receiving app's
2730 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2731 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2732 * before being sent to the corresponding app.
2733 */
2734 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2735 @NetworkCapabilities.RedactionType long applicableRedactions,
2736 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2737 boolean includeLocationSensitiveInfo) {
2738 long redactions = applicableRedactions;
2739 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2740 if (includeLocationSensitiveInfo
2741 && redactionPermissionChecker.hasLocationPermission()) {
2742 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2743 }
2744 }
2745 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2746 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2747 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2748 }
2749 }
2750 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2751 if (redactionPermissionChecker.hasSettingsPermission()) {
2752 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2753 }
2754 }
2755 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002756 }
2757
Qingxi Lib2748102020-01-08 12:51:49 -08002758 @VisibleForTesting
2759 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002760 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002761 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002762 int callingPid, int callingUid, @NonNull String callingPkgName,
2763 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002764 if (nc == null) {
2765 return null;
2766 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002767 // Avoid doing location permission check if the transport info has no location sensitive
2768 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002769 final RedactionPermissionChecker redactionPermissionChecker =
2770 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2771 callingAttributionTag);
2772 final long redactions = retrieveRequiredRedactions(
2773 nc.getApplicableRedactions(), redactionPermissionChecker,
2774 includeLocationSensitiveInfo);
2775 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002776 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002777 // TODO : calling UID is redacted because apps should generally not know what UID is
2778 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002779 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002780 newNc.setOwnerUid(INVALID_UID);
2781 return newNc;
2782 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002783 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2784 if (nc.hasTransport(TRANSPORT_VPN)) {
2785 // Owner UIDs already checked above. No need to re-check.
2786 return newNc;
2787 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002788 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2789 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002790 // compatibility for older apps.
2791 if (!includeLocationSensitiveInfo
2792 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002793 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002794 newNc.setOwnerUid(INVALID_UID);
2795 return newNc;
2796 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002797 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002798 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002799 newNc.setOwnerUid(INVALID_UID);
2800 }
Qingxi Lib2748102020-01-08 12:51:49 -08002801 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002802 }
2803
lucaslinc582d502022-01-27 09:07:00 +08002804 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002805 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2806 LinkProperties lp, int callerPid, int callerUid) {
2807 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002808 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2809 // this would be expensive (one more permission check every time any LP callback is
2810 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2811 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2812 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002813
2814 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2815 final boolean needsSanitization =
2816 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2817 if (!needsSanitization) {
2818 return new LinkProperties(lp);
2819 }
2820
2821 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002822 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002823 }
2824
2825 final LinkProperties newLp = new LinkProperties(lp);
2826 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2827 // object gets parceled.
2828 newLp.setCaptivePortalApiUrl(null);
2829 newLp.setCaptivePortalData(null);
2830 return newLp;
2831 }
2832
Roshan Pius08c94fb2020-01-16 12:17:17 -08002833 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2834 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002835 // There is no need to track the effective UID of the request here. If the caller
2836 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002837 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002838 // Unprivileged apps can only pass in null or their own UID.
2839 if (nc.getUids() == null) {
2840 // If the caller passes in null, the callback will also match networks that do not
2841 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2842 // In this case, redact everything in the request immediately. This ensures that the
2843 // app is not able to get any redacted information by filing an unredacted request
2844 // and observing whether the request matches something.
2845 if (nc.getNetworkSpecifier() != null) {
2846 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2847 }
2848 } else {
2849 nc.setSingleUid(callerUid);
2850 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002851 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002852 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002853 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002854
2855 // Clear owner UID; this can never come from an app.
2856 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002857 }
2858
Chalard Jean38354d12018-03-20 19:13:57 +09002859 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002860 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002861 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2862 }
2863 }
2864
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002865 @Override
2866 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2867 enforceAccessPermission();
2868 final int callerUid = Binder.getCallingUid();
2869 final long token = Binder.clearCallingIdentity();
2870 try {
2871 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2872 } finally {
2873 Binder.restoreCallingIdentity(token);
2874 }
2875 }
2876
junyulaiebd15162021-03-03 12:09:05 +08002877 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002878 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002879 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002880 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002881 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002882
Serik Beketayev05130302021-01-15 16:47:25 -08002883 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002884 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002885 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2886 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002887 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002888 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002889 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002890 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2891 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002892 }
2893 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002894 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002895 }
2896
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002897 @Override
junyulaiebd15162021-03-03 12:09:05 +08002898 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002899 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002900 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002901 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002902
2903 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2904 for (Network network : getAllNetworks()) {
2905 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09002906 final boolean includeNetwork = (nai != null) && nai.isCreated();
2907 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002908 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2909 // NetworkCapabilities, which may contain UIDs of apps to which the
2910 // network applies. Should the UIDs be cleared so as not to leak or
2911 // interfere ?
2912 result.add(nai.getNetworkStateSnapshot());
2913 }
2914 }
2915 return result;
2916 }
2917
2918 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002919 public boolean isActiveNetworkMetered() {
2920 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002921
Qingxi Lib2748102020-01-08 12:51:49 -08002922 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002923 if (caps != null) {
2924 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2925 } else {
2926 // Always return the most conservative value
2927 return true;
2928 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002929 }
2930
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002931 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002932 * Ensures that the system cannot call a particular method.
2933 */
2934 private boolean disallowedBecauseSystemCaller() {
2935 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002936 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2937 // for devices launched with Q and above. However, existing devices upgrading to Q and
2938 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002939 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002940 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002941 log("This method exists only for app backwards compatibility"
2942 + " and must not be called by system services.");
2943 return true;
2944 }
2945 return false;
2946 }
2947
paulhub2c28682021-08-18 18:35:54 +08002948 private int getAppUid(final String app, final UserHandle user) {
2949 final PackageManager pm =
2950 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2951 final long token = Binder.clearCallingIdentity();
2952 try {
2953 return pm.getPackageUid(app, 0 /* flags */);
2954 } catch (PackageManager.NameNotFoundException e) {
2955 return -1;
2956 } finally {
2957 Binder.restoreCallingIdentity(token);
2958 }
2959 }
2960
2961 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2962 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2963 if (getAppUid(packageName, user) != callingUid) {
2964 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2965 }
2966 }
2967
Lorenzo Colitti23862912018-09-28 11:31:55 +09002968 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002969 * Ensure that a network route exists to deliver traffic to the specified
2970 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002971 * @param networkType the type of the network over which traffic to the
2972 * specified host is to be routed
2973 * @param hostAddress the IP address of the host to which the route is
2974 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002975 * @return {@code true} on success, {@code false} on failure
2976 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002977 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002978 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2979 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002980 if (disallowedBecauseSystemCaller()) {
2981 return false;
2982 }
paulhub2c28682021-08-18 18:35:54 +08002983 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002984 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002985 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002986 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002987 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002988
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002989 InetAddress addr;
2990 try {
2991 addr = InetAddress.getByAddress(hostAddress);
2992 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002993 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002994 return false;
2995 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002996
The Android Open Source Project28527d22009-03-03 19:31:44 -08002997 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002998 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002999 return false;
3000 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003001
3002 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3003 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003004 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003005 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3006 } else {
3007 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3008 }
3009 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003010 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003011
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003012 DetailedState netState;
3013 synchronized (nai) {
3014 netState = nai.networkInfo.getDetailedState();
3015 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003016
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003017 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003018 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003019 log("requestRouteToHostAddress on down network "
3020 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003021 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003022 }
3023 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003024 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003025
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003026 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003027 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003028 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003029 LinkProperties lp;
3030 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003031 synchronized (nai) {
3032 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003033 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003034 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003035 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003036 if (DBG) {
3037 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3038 }
Wink Saville32506bc2013-06-29 21:10:57 -07003039 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003040 } finally {
3041 Binder.restoreCallingIdentity(token);
3042 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003043 }
3044
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003045 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003046 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003047 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003048 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003049 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003050 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003051 if (bestRoute.getGateway().equals(addr)) {
3052 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003053 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003054 } else {
3055 // if we will connect to this through another route, add a direct route
3056 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003057 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003058 }
3059 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003060 if (DBG) log("Adding legacy route " + bestRoute +
3061 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003062
3063 final String dst = bestRoute.getDestinationLinkAddress().toString();
3064 final String nextHop = bestRoute.hasGateway()
3065 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003066 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003067 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3068 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003069 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003070 return false;
3071 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003072 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003073 }
3074
paulhu7c0a2e62021-01-08 00:51:49 +08003075 class DnsResolverUnsolicitedEventCallback extends
3076 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003077 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003078 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003079 try {
3080 mHandler.sendMessage(mHandler.obtainMessage(
3081 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003082 new PrivateDnsValidationUpdate(event.netId,
3083 InetAddresses.parseNumericAddress(event.ipAddress),
3084 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003085 } catch (IllegalArgumentException e) {
3086 loge("Error parsing ip address in validation event");
3087 }
3088 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003089
3090 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003091 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3092 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003093 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3094 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3095 // event callback for certain nai. e.g. cellular. Register here to pass to
3096 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003097 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003098 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3099 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003100 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003101 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003102 }
3103 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003104
3105 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003106 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3107 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3108 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003109 }
dalyk1720e542018-03-05 12:42:22 -05003110
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003111 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003112 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003113 return this.VERSION;
3114 }
3115
3116 @Override
3117 public String getInterfaceHash() {
3118 return this.HASH;
3119 }
paulhu7c0a2e62021-01-08 00:51:49 +08003120 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003121
3122 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003123 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3124 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003125
paulhu7c0a2e62021-01-08 00:51:49 +08003126 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003127 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003128 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003129 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003130 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003131 }
3132 }
3133
Sudheer Shanka9967d462021-03-18 19:09:25 +00003134 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003135 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003136 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003137 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3138 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003139 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003140 };
3141
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003142 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003143 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003144 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003145 }
3146
Mark Fasheh7c999d82023-05-04 20:23:11 +00003147 static final class UidFrozenStateChangedArgs {
3148 final int[] mUids;
3149 final int[] mFrozenStates;
3150
3151 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3152 mUids = uids;
3153 mFrozenStates = frozenStates;
3154 }
3155 }
3156
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003157 /**
3158 * Check if the cell network is idle.
3159 * @return true if the cell network state is idle
3160 * false if the cell network state is active or unknown
3161 */
3162 private boolean isCellNetworkIdle() {
3163 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3164 if (defaultNai == null
3165 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3166 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3167 // cell network is not the default network, cell network state is unknown.
3168 // TODO(b/279380356): Track cell network state when the cell is not the default network
3169 return false;
3170 }
3171
3172 return !mNetworkActivityTracker.isDefaultNetworkActive();
3173 }
3174
Mark Fasheh7c999d82023-05-04 20:23:11 +00003175 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003176 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003177
3178 for (int i = 0; i < uids.length; i++) {
3179 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003180 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003181 } else {
3182 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003183 }
3184 }
3185
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003186 if (ownerUids.isEmpty()) {
3187 return;
3188 }
3189
3190 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3191 // Delay closing sockets to avoid waking the cell modem up.
3192 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3193 // than waking cell modem up.
3194 mPendingFrozenUids.addAll(ownerUids);
3195 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003196 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003197 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003198 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003199 loge("Exception in socket destroy: " + e);
3200 }
3201 }
3202 }
3203
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003204 private void closePendingFrozenSockets() {
3205 ensureRunningOnConnectivityServiceThread();
3206
3207 try {
3208 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3209 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3210 loge("Failed to close pending frozen app sockets: " + e);
3211 }
3212 mPendingFrozenUids.clear();
3213 }
3214
3215 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3216 mNetworkActivityTracker.handleReportNetworkActivity(params);
3217
3218 if (mDelayDestroyFrozenSockets
3219 && params.isActive
3220 && params.label == TRANSPORT_CELLULAR
3221 && !mPendingFrozenUids.isEmpty()) {
3222 closePendingFrozenSockets();
3223 }
3224 }
3225
3226 /**
3227 * If the cellular network is no longer the default network, close pending frozen sockets.
3228 *
3229 * @param newNetwork new default network
3230 * @param oldNetwork old default network
3231 */
3232 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3233 NetworkAgentInfo oldNetwork) {
3234 final boolean isOldNetworkCellular = oldNetwork != null
3235 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3236 final boolean isNewNetworkCellular = newNetwork != null
3237 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3238
3239 if (isOldNetworkCellular
3240 && !isNewNetworkCellular
3241 && !mPendingFrozenUids.isEmpty()) {
3242 closePendingFrozenSockets();
3243 }
3244 }
3245
3246 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3247 pw.println("CloseFrozenAppSockets:");
3248 pw.increaseIndent();
3249 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3250 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3251 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3252 pw.decreaseIndent();
3253 }
3254
Mark Fasheh7c999d82023-05-04 20:23:11 +00003255 @VisibleForTesting
3256 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003257 @VisibleForTesting
3258 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3259 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003260
Paul Jensen83f5d572014-08-29 09:54:01 -04003261 private void enforceInternetPermission() {
3262 mContext.enforceCallingOrSelfPermission(
3263 android.Manifest.permission.INTERNET,
3264 "ConnectivityService");
3265 }
3266
The Android Open Source Project28527d22009-03-03 19:31:44 -08003267 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003268 mContext.enforceCallingOrSelfPermission(
3269 android.Manifest.permission.ACCESS_NETWORK_STATE,
3270 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003271 }
3272
lucaslinc582d502022-01-27 09:07:00 +08003273 private boolean checkAccessPermission(int pid, int uid) {
3274 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3275 == PERMISSION_GRANTED;
3276 }
3277
paulhua6ee2122021-02-22 15:40:43 +08003278 /**
3279 * Performs a strict and comprehensive check of whether a calling package is allowed to
3280 * change the state of network, as the condition differs for pre-M, M+, and
3281 * privileged/preinstalled apps. The caller is expected to have either the
3282 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3283 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3284 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3285 * permission and cannot be revoked. See http://b/23597341
3286 *
3287 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3288 * of this app will be updated to the current time.
3289 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003290 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003291 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3292 == PackageManager.PERMISSION_GRANTED) {
3293 return;
3294 }
3295
3296 if (callingPkg == null) {
3297 throw new SecurityException("Calling package name is null.");
3298 }
3299
3300 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3301 final int uid = mDeps.getCallingUid();
3302 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3303 callingPkg, callingAttributionTag, null /* message */);
3304
3305 if (mode == AppOpsManager.MODE_ALLOWED) {
3306 return;
3307 }
3308
3309 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3310 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3311 return;
3312 }
3313
3314 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3315 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3316 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003317 }
3318
Charles He9369e612017-05-15 17:07:18 +01003319 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003320 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003321 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003322 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003323 }
3324
Quang Luong98858d62023-02-11 00:25:24 +00003325 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003326 enforceAnyPermissionOf(mContext,
3327 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003328 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003329 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3330 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3331 }
3332
paulhu8e96a752019-08-12 16:25:11 +08003333 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003334 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003335 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003336 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003337 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003338 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003339 }
3340
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003341 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003342 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003343 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003344 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003345 android.Manifest.permission.NETWORK_SETTINGS,
3346 android.Manifest.permission.NETWORK_FACTORY,
3347 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3348 }
3349
3350 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003351 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003352 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003353 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003354 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3355 android.Manifest.permission.NETWORK_FACTORY,
3356 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3357 }
3358
lucaslin69e1aa92022-03-22 18:15:09 +08003359 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3360 return PERMISSION_GRANTED == mContext.checkPermission(
3361 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3362 || PERMISSION_GRANTED == mContext.checkPermission(
3363 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3364 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003365 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003366 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003367 }
3368
Chalard Jean9a396cc2018-02-21 18:43:54 +09003369 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003370 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003371 android.Manifest.permission.NETWORK_SETTINGS,
3372 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003373 }
3374
3375 private boolean checkSettingsPermission(int pid, int uid) {
3376 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003377 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3378 || PERMISSION_GRANTED == mContext.checkPermission(
3379 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003380 }
3381
paulhu8e96a752019-08-12 16:25:11 +08003382 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003383 enforceNetworkStackPermissionOr(mContext,
3384 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003385 }
3386
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003387 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003388 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003389 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003390 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003391 }
3392
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003393 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003394 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003395 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3396 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003397 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003398 }
3399
James Mattis8378aec2021-01-26 14:05:36 -08003400 private void enforceOemNetworkPreferencesPermission() {
3401 mContext.enforceCallingOrSelfPermission(
3402 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3403 "ConnectivityService");
3404 }
3405
James Mattisfa270db2021-05-31 17:11:10 -07003406 private void enforceManageTestNetworksPermission() {
3407 mContext.enforceCallingOrSelfPermission(
3408 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3409 "ConnectivityService");
3410 }
3411
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003412 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003413 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003414 android.Manifest.permission.NETWORK_STACK,
3415 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003416 }
3417
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003418 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003419 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003420 android.Manifest.permission.NETWORK_STACK,
3421 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3422 }
3423
paulhu1a407652019-03-22 16:35:06 +08003424 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003425 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003426 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003427 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3428 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003429 }
3430
Paul Hu8fc2a552022-05-04 18:44:42 +08003431 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3432 boolean checkUidsAllowedList) {
3433 if (PermissionUtils.checkAnyPermissionOf(mContext,
3434 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3435 return true;
3436 }
3437
3438 // fallback to ConnectivityInternalPermission
3439 // TODO: Remove this fallback check after all apps have declared
3440 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3441 if (PermissionUtils.checkAnyPermissionOf(mContext,
3442 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3443 return true;
3444 }
3445
3446 // Check whether uid is in allowed on restricted networks list.
3447 if (checkUidsAllowedList
3448 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3449 return true;
3450 }
3451 return false;
3452 }
3453
3454 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3455 final int callingUid = mDeps.getCallingUid();
3456 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3457 throw new SecurityException("ConnectivityService: user " + callingUid
3458 + " has no permission to access restricted network.");
3459 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003460 }
3461
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003462 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003463 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003464 }
3465
Roshan Pius98f59ec2021-02-23 08:47:39 -08003466 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3467 return PERMISSION_GRANTED == mContext.checkPermission(
3468 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3469 }
3470
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003471 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003472 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003473 }
3474
3475 private void sendInetConditionBroadcast(NetworkInfo info) {
3476 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3477 }
3478
Wink Saville4f0de1e2011-08-04 15:01:58 -07003479 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003480 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003481 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003482 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003483 if (info.isFailover()) {
3484 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3485 info.setFailover(false);
3486 }
3487 if (info.getReason() != null) {
3488 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3489 }
3490 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003491 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3492 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003493 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003494 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003495 return intent;
3496 }
3497
3498 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3499 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3500 }
3501
Michael Groover73f69482023-01-27 11:01:25 -06003502 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3503 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003504 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3505 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003506 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003507 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003508 if (!mSystemReady
3509 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003510 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003511 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003512 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003513 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003514 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003515 }
3516
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003517 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003518 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003519 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003520 final NetworkInfo ni = intent.getParcelableExtra(
3521 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003522 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3523 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003524 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003525 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003526 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003527 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003528 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003529 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003530 } finally {
3531 Binder.restoreCallingIdentity(ident);
3532 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003533 }
3534 }
3535
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003536 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3537 NetworkInfo info) {
3538 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003539 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003540
3541 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3542 try {
3543 // This allows us to discard older broadcasts still waiting to be delivered
3544 // which have the same namespace and key.
3545 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3546 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3547 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003548 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003549 } catch (UnsupportedApiLevelException e) {
3550 Log.wtf(TAG, "Using unsupported API" + e);
3551 }
3552 }
3553
3554 @VisibleForTesting
3555 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3556 final StringBuilder sb = new StringBuilder();
3557 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3558 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3559 sb.append(info.getExtraInfo());
3560 return sb.toString();
3561 }
3562
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003563 /**
Aaron Huang96011892020-06-27 07:18:23 +08003564 * Called by SystemServer through ConnectivityManager when the system is ready.
3565 */
3566 @Override
3567 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003568 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003569 throw new SecurityException("Calling Uid is not system uid.");
3570 }
3571 systemReadyInternal();
3572 }
3573
3574 /**
3575 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003576 */
3577 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003578 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003579 // Load flags after PackageManager is ready to query module version
3580 mFlags.loadFlags(mDeps, mContext);
3581
Aaron Huang9a57acf2020-12-08 10:03:29 +08003582 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3583 // listening network request which is sent by MultipathPolicyTracker won't be added
3584 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3585 // be called after PermissionMonitor#startMonitoring().
3586 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3587 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3588 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003589 final ConditionVariable startMonitoringDone = new ConditionVariable();
3590 mHandler.post(() -> {
3591 mPermissionMonitor.startMonitoring();
3592 startMonitoringDone.open();
3593 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003594 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003595 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003596
Hugo Benichie5220992017-04-26 14:53:28 +09003597 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003598 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003599 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003600 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003601 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003602 }
3603 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003604
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003605 // Create network requests for always-on networks.
3606 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003607
3608 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003609 // Note that updating can be skipped here if the list is empty only because no uid
3610 // rules are applied before system ready. Normally, the empty uid list means to clear
3611 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003612 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3613 updateMobileDataPreferredUids();
3614 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003615
3616 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003617 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003618 mBpfNetMaps.setPullAtomCallback(mContext);
3619 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003620 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3621 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003622 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3623 // have permission problem. While CV#block() is unbounded in time and can in principle block
3624 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3625 // could have blocked forever too.
3626 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003627 }
3628
The Android Open Source Project28527d22009-03-03 19:31:44 -08003629 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003630 * Start listening for default data network activity state changes.
3631 */
3632 @Override
3633 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003634 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003635 }
3636
3637 /**
3638 * Stop listening for default data network activity state changes.
3639 */
3640 @Override
3641 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003642 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003643 }
3644
3645 /**
3646 * Check whether the default network radio is currently active.
3647 */
3648 @Override
3649 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003650 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003651 }
3652
3653 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003654 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003655 * and set it on it's iface.
3656 */
Junyu Lai970963e2022-10-25 15:46:47 +08003657 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003658 final String iface = newLp.getInterfaceName();
3659 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003660 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003661 // Silently ignore unset MTU value.
3662 return;
3663 }
Hansen Kurli04252032022-12-07 11:21:49 +00003664 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3665 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3666 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003667 return;
3668 }
Hansen Kurli04252032022-12-07 11:21:49 +00003669 // Cannot set MTU without interface name
3670 if (TextUtils.isEmpty(iface)) {
3671 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003672 return;
3673 }
sy.yun4aa73922013-09-02 05:24:09 +09003674
Hansen Kurli04252032022-12-07 11:21:49 +00003675 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3676 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003677 return;
3678 }
3679
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003680 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003681 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003682 mNetd.interfaceSetMtu(iface, mtu);
3683 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003684 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003685 }
3686 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003687
Chenbo Feng15416292018-11-08 17:36:21 -08003688 @VisibleForTesting
3689 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003690
Junyu Lai970963e2022-10-25 15:46:47 +08003691 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003692 String[] values = null;
3693 if (tcpBufferSizes != null) {
3694 values = tcpBufferSizes.split(",");
3695 }
3696
3697 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003698 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003699 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3700 values = tcpBufferSizes.split(",");
3701 }
3702
3703 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3704
3705 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003706 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003707
Chenbo Feng15416292018-11-08 17:36:21 -08003708 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3709 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3710 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003711 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003712 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003713 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003714 }
3715 }
3716
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003717 @Override
3718 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003719 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003720 NETWORK_RESTORE_DELAY_PROP_NAME);
3721 if(restoreDefaultNetworkDelayStr != null &&
3722 restoreDefaultNetworkDelayStr.length() != 0) {
3723 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003724 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003725 } catch (NumberFormatException e) {
3726 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003727 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003728 // if the system property isn't set, use the value for the apn type
3729 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3730
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003731 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3732 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003733 }
3734 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003735 }
3736
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003737 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003738 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003739 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003740 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003741 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003742 // Start gathering diagnostic information.
3743 netDiags.add(new NetworkDiagnostics(
3744 nai.network,
3745 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003746 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003747 DIAG_TIME_MS));
3748 }
3749
3750 for (NetworkDiagnostics netDiag : netDiags) {
3751 pw.println();
3752 netDiag.waitForMeasurements();
3753 netDiag.dump(pw);
3754 }
3755 }
3756
The Android Open Source Project28527d22009-03-03 19:31:44 -08003757 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003758 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3759 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003760 if (!checkDumpPermission(mContext, TAG, writer)) return;
3761
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003762 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003763 }
3764
lucaslin99473f62020-12-10 15:10:54 +08003765 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3766 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3767 != PackageManager.PERMISSION_GRANTED) {
3768 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003769 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003770 + " due to missing android.permission.DUMP permission");
3771 return false;
3772 } else {
3773 return true;
3774 }
3775 }
3776
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003777 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003778 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003779
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003780 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003781 dumpNetworkDiagnostics(pw);
3782 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003783 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003784 dumpNetworks(pw);
3785 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003786 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003787 dumpNetworkRequests(pw);
3788 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003789 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3790 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3791 dumpTrafficController(pw, fd, verbose);
3792 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003793 }
Erik Kline9647f382015-06-05 17:47:34 +09003794
Junyu Lai0da479b2022-04-20 15:06:29 +08003795 pw.println("NetworkProviders for:");
3796 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003797 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003798 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003799 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003800 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003801 pw.println();
3802
Chalard Jean5b409c72021-02-04 13:12:59 +09003803 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003804 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003805 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003806 pw.println("none");
3807 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003808 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003809 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003810 pw.println();
3811
James Mattis8b298a02021-06-01 22:34:04 -07003812 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003813 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003814 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003815 pw.decreaseIndent();
3816 pw.println();
3817
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003818 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003819 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003820 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003821 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003822 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003823
junyulaif2c67e42018-08-07 19:50:45 +08003824 pw.println("Status for known UIDs:");
3825 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003826 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003827 for (int i = 0; i < size; i++) {
3828 // Don't crash if the array is modified while dumping in bugreports.
3829 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003830 final int uid = mUidBlockedReasons.keyAt(i);
3831 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3832 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003833 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003834 } catch (ArrayIndexOutOfBoundsException e) {
3835 pw.println(" ArrayIndexOutOfBoundsException");
3836 } catch (ConcurrentModificationException e) {
3837 pw.println(" ConcurrentModificationException");
3838 }
3839 }
3840 pw.println();
3841 pw.decreaseIndent();
3842
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003843 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003844 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003845 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003846 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003847 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003848
Junyu Lai0da479b2022-04-20 15:06:29 +08003849 pw.println("Network Offers:");
3850 pw.increaseIndent();
3851 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3852 pw.println(offerInfo.offer);
3853 }
3854 pw.decreaseIndent();
3855 pw.println();
3856
Robert Greenwalt94e22142014-07-30 16:31:24 -07003857 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003858
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003859 pw.println();
markchien5e866652019-09-30 14:40:57 +08003860 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003861
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003862 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003863 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003864
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003865 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003866 dumpCloseFrozenAppSockets(pw);
3867
3868 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003869
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003870 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003871 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003872 pw.println("mNetworkRequestInfoLogs (most recent first):");
3873 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003874 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003875 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003876
3877 pw.println();
3878 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3879 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003880 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003881 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003882
3883 pw.println();
3884 pw.println("NetTransition WakeLock activity (most recent first):");
3885 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003886 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3887 pw.println("total releases: " + mTotalWakelockReleases);
3888 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3889 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3890 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3891 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3892 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3893 }
James Mattiscb1e0362021-04-06 17:07:42 -07003894 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003895
3896 pw.println();
3897 pw.println("bandwidth update requests (by uid):");
3898 pw.increaseIndent();
3899 synchronized (mBandwidthRequests) {
3900 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3901 pw.println("[" + mBandwidthRequests.keyAt(i)
3902 + "]: " + mBandwidthRequests.valueAt(i));
3903 }
3904 }
3905 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003906 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003907
James Mattiscb1e0362021-04-06 17:07:42 -07003908 pw.println();
3909 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3910 pw.increaseIndent();
3911 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003912 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003913 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003914
3915 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003916
3917 pw.println();
3918 pw.println("Permission Monitor:");
3919 pw.increaseIndent();
3920 mPermissionMonitor.dump(pw);
3921 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003922
3923 pw.println();
3924 pw.println("Legacy network activity:");
3925 pw.increaseIndent();
3926 mNetworkActivityTracker.dump(pw);
3927 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003928 }
3929
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003930 private void dumpNetworks(IndentingPrintWriter pw) {
3931 for (NetworkAgentInfo nai : networksSortedById()) {
3932 pw.println(nai.toString());
3933 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003934 pw.println("Nat464Xlat:");
3935 pw.increaseIndent();
3936 nai.dumpNat464Xlat(pw);
3937 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003938 pw.println(String.format(
3939 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3940 nai.numForegroundNetworkRequests(),
3941 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3942 nai.numBackgroundNetworkRequests(),
3943 nai.numNetworkRequests()));
3944 pw.increaseIndent();
3945 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3946 pw.println(nai.requestAt(i).toString());
3947 }
3948 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003949 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003950 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003951 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003952 pw.decreaseIndent();
3953 pw.decreaseIndent();
3954 }
3955 }
3956
James Mattis8b298a02021-06-01 22:34:04 -07003957 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3958 if (!mProfileNetworkPreferences.isEmpty()) {
3959 pw.println("Profile preferences:");
3960 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09003961 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07003962 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003963 }
James Mattis8b298a02021-06-01 22:34:04 -07003964 if (!mOemNetworkPreferences.isEmpty()) {
3965 pw.println("OEM preferences:");
3966 pw.increaseIndent();
3967 pw.println(mOemNetworkPreferences);
3968 pw.decreaseIndent();
3969 }
3970 if (!mMobileDataPreferredUids.isEmpty()) {
3971 pw.println("Mobile data preferred UIDs:");
3972 pw.increaseIndent();
3973 pw.println(mMobileDataPreferredUids);
3974 pw.decreaseIndent();
3975 }
James Mattis45d81842021-01-10 14:24:24 -08003976
James Mattis8b298a02021-06-01 22:34:04 -07003977 pw.println("Default requests:");
3978 pw.increaseIndent();
3979 dumpPerAppDefaultRequests(pw);
3980 pw.decreaseIndent();
3981 }
3982
3983 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003984 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3985 if (mDefaultRequest == defaultRequest) {
3986 continue;
3987 }
3988
James Mattis8b298a02021-06-01 22:34:04 -07003989 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3990 final String networkOutput;
3991 if (null == satisfier) {
3992 networkOutput = "null";
3993 } else if (mNoServiceNetwork.equals(satisfier)) {
3994 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003995 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003996 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003997 }
James Mattis8b298a02021-06-01 22:34:04 -07003998 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3999 ? "" : " asUid: " + defaultRequest.mAsUid;
4000 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
4001 + defaultRequest.mPid + asUidString + "]";
4002 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4003 + " Preference order: " + defaultRequest.mPreferenceOrder
4004 + " Tracked UIDs: " + defaultRequest.getUids();
4005 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004006 }
4007 }
4008
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004009 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004010 NetworkRequestInfo[] infos = null;
4011 while (infos == null) {
4012 try {
4013 infos = requestsSortedById();
4014 } catch (ConcurrentModificationException e) {
4015 // mNetworkRequests should only be accessed from handler thread, except dump().
4016 // As dump() is never called in normal usage, it would be needlessly expensive
4017 // to lock the collection only for its benefit. Instead, retry getting the
4018 // requests if ConcurrentModificationException is thrown during dump().
4019 }
4020 }
4021 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004022 pw.println(nri.toString());
4023 }
4024 }
4025
Ken Chene6d511f2022-01-25 11:10:42 +08004026 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4027 boolean verbose) {
4028 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004029 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004030 } catch (ServiceSpecificException e) {
4031 pw.println(e.getMessage());
4032 } catch (IOException e) {
4033 loge("Dump BPF maps failed, " + e);
4034 }
4035 }
4036
Chalard Jean524f0b12021-10-25 21:11:56 +09004037 private void dumpAllRequestInfoLogsToLogcat() {
4038 try (PrintWriter logPw = new PrintWriter(new Writer() {
4039 @Override
4040 public void write(final char[] cbuf, final int off, final int len) {
4041 // This method is called with 0-length and 1-length arrays for empty strings
4042 // or strings containing only the DEL character.
4043 if (len <= 1) return;
4044 Log.e(TAG, new String(cbuf, off, len));
4045 }
4046 @Override public void flush() {}
4047 @Override public void close() {}
4048 })) {
4049 mNetworkRequestInfoLogs.dump(logPw);
4050 }
4051 }
4052
Hugo Benichia480ba52018-09-03 08:19:02 +09004053 /**
4054 * Return an array of all current NetworkAgentInfos sorted by network id.
4055 */
4056 private NetworkAgentInfo[] networksSortedById() {
4057 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004058 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004059 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004060 return networks;
4061 }
4062
4063 /**
4064 * Return an array of all current NetworkRequest sorted by request id.
4065 */
James Mattis258ea3c2020-11-15 15:04:40 -08004066 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004067 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004068 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004069 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004070 // Sort the array based off the NRI containing the min requestId in its requests.
4071 Arrays.sort(requests,
4072 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4073 Comparator.comparingInt(req -> req.requestId)).requestId
4074 )
4075 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004076 return requests;
4077 }
4078
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004079 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004080 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004081 if (officialNai != null && officialNai.equals(nai)) return true;
4082 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004083 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004084 " - " + nai);
4085 }
4086 return false;
4087 }
4088
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004089 private boolean isDisconnectRequest(Message msg) {
4090 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4091 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4092 return info.getState() == NetworkInfo.State.DISCONNECTED;
4093 }
4094
Robert Greenwalt2034b912009-08-12 16:08:25 -07004095 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004096 private class NetworkStateTrackerHandler extends Handler {
4097 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004098 super(looper);
4099 }
4100
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004101 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004102 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4103 final NetworkAgentInfo nai = arg.first;
4104 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004105 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004106 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004107 }
4108 return;
4109 }
4110
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004111 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004112 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004113 return;
4114 }
4115
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004116 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004117 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09004118 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
4119 final NetworkCapabilities sanitized =
4120 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004121 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004122 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004123 break;
4124 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004125 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004126 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004127 processLinkPropertiesFromAgent(nai, newLp);
4128 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004129 break;
4130 }
4131 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004132 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004133 updateNetworkInfo(nai, info);
4134 break;
4135 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004136 case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
4137 final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
4138 updateLocalNetworkConfig(nai, config);
4139 break;
4140 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004141 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004142 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004143 break;
4144 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004145 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004146 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004147 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004148 // Note that if the NAI had been connected, this would affect the
4149 // score, and therefore would require re-mixing the score and performing
4150 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004151 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004152 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4153 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004154 // Mark the network as temporarily accepting partial connectivity so that it
4155 // will be validated (and possibly become default) even if it only provides
4156 // partial internet access. Note that if user connects to partial connectivity
4157 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4158 // out of wifi coverage) and if the same wifi is available again, the device
4159 // will auto connect to this wifi even though the wifi has "no internet".
4160 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004161 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004162 break;
4163 }
junyulai011b1f12019-01-03 18:50:15 +08004164 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004165 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004166 break;
4167 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004168 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004169 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004170 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004171
4172 if (isLegacyLockdownNai(nai)
4173 && (underlying == null || underlying.size() != 1)) {
4174 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4175 + " must have exactly one underlying network: " + underlying);
4176 }
4177
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004178 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4179 nai.declaredUnderlyingNetworks = (underlying != null)
4180 ? underlying.toArray(new Network[0]) : null;
4181
4182 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4183 if (DBG) {
4184 log(nai.toShortString() + " changed underlying networks to "
4185 + Arrays.toString(nai.declaredUnderlyingNetworks));
4186 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004187 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004188 notifyIfacesChangedForNetworkStats();
4189 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004190 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004191 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004192 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4193 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4194 nai.teardownDelayMs = msg.arg1;
4195 } else {
4196 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4197 }
Chalard Jean550b5212021-03-05 23:07:53 +09004198 break;
4199 }
4200 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4201 nai.setLingerDuration((int) arg.second);
4202 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004203 }
Tyler Wear72388212021-09-09 14:49:02 -07004204 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4205 DscpPolicy policy = (DscpPolicy) arg.second;
4206 if (mDscpPolicyTracker != null) {
4207 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4208 }
4209 break;
4210 }
4211 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4212 if (mDscpPolicyTracker != null) {
4213 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4214 }
4215 break;
4216 }
4217 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4218 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004219 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004220 }
4221 break;
4222 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004223 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004224 if (!nai.everConnected()) {
4225 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4226 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004227 teardownUnneededNetwork(nai);
4228 break;
4229 }
4230
4231 if (nai.isDestroyed()) {
4232 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4233 + ", ignoring");
4234 break;
4235 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004236
4237 final int timeoutMs = (int) arg.second;
4238 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4239 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4240 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4241 }
4242
4243 // Marking a network awaiting replacement is used to ensure that any requests
4244 // satisfied by the network do not switch to another network until a
4245 // replacement is available or the wait for a replacement times out.
4246 // If the network is inactive (i.e., nascent or lingering), then there are no
4247 // such requests, and there is no point keeping it. Just tear it down.
4248 // Note that setLingerDuration(0) cannot be used to do this because the network
4249 // could be nascent.
4250 nai.clearInactivityState();
4251 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4252 Log.d(TAG, nai.toShortString()
4253 + " marked awaiting replacement is unneeded, tearing down instead");
4254 teardownUnneededNetwork(nai);
4255 break;
4256 }
4257
4258 Log.d(TAG, "Marking " + nai.toShortString()
4259 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4260 destroyNativeNetwork(nai);
4261
4262 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4263 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4264 // consider the fact that the network could already have disconnected or been
4265 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4266 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4267 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4268 mKeepaliveTracker.handleStopAllKeepalives(nai,
4269 SocketKeepalive.ERROR_INVALID_NETWORK);
4270
4271 nai.updateScoreForNetworkAgentUpdate();
4272 // This rematch is almost certainly not going to result in any changes, because
4273 // the destroyed flag is only just above the "current satisfier wins"
4274 // tie-breaker. But technically anything that affects scoring should rematch.
4275 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004276 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004277 break;
4278 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004279 }
4280 }
4281
4282 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004283 final int netId = msg.arg2;
4284 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004285 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004286 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004287 switch (msg.what) {
4288 default:
4289 return false;
lucasline117e2e2019-10-22 18:27:33 +08004290 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004291 if (nai == null) {
4292 break;
4293 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004294 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4295 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004296 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004297 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004298 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004299 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004300 if (probePrivateDnsCompleted) {
4301 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4302 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004303 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004304 }
4305 // Only show the notification when the private DNS is broken and the
4306 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004307 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004308 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4309 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004310 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004311 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4312 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4313 // private DNS is broken, it means this network is being reevaluated.
4314 // Either probing private DNS is not necessary any more or it hasn't been
4315 // done yet. In either case, the networkCapabilities should be updated to
4316 // reflect the new status.
4317 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004318 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004319 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004320 }
4321 break;
4322 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004323 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004324 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4325
Erik Kline31b4a9e2018-01-11 21:07:29 +09004326 if (nai == null) break;
4327
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004328 handleNetworkTested(nai, results.mTestResult,
4329 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004330 break;
4331 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004332 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004333 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004334 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004335 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004336 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004337 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004338 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4339 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004340 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004341 if (nai == null) {
4342 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4343 break;
4344 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004345 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004346 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004347 (PendingIntent) msg.obj,
4348 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004349 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004350 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004351 break;
4352 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004353 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004354 if (nai == null) break;
4355
Erik Kline9a62f012018-03-21 07:18:33 -07004356 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004357 break;
4358 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004359 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004360 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004361 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004362 break;
4363 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004364 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004365 return true;
4366 }
4367
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004368 private void handleNetworkTested(
4369 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004370 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4371 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004372 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004373
4374 // If there is any kind of working networking, then the NAI has been evaluated
4375 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4376 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004377 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004378 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004379 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4380 // any callback that receives onAvailable for that rematch receives an extra caps
4381 // callback. To prevent that, update the score in the agent so the updates below won't
4382 // see an update to both caps and score at the same time.
4383 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004384 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4385
he_won.hwang881307a2022-03-15 21:23:52 +09004386 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4387 // Assume the validation failure is due to a temporary failure after roaming
4388 // and ignore it. NetworkMonitor will continue to retry validation. If it
4389 // continues to fail after the block timeout expires, the network will be
4390 // marked unvalidated. If it succeeds, then validation state will not change.
4391 return;
4392 }
4393
Chalard Jean254bd162022-08-25 13:04:51 +09004394 final boolean wasValidated = nai.isValidated();
4395 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004396 final boolean wasPortal = nai.captivePortalDetected();
4397 nai.setPartialConnectivity(partial);
4398 nai.setCaptivePortalDetected(portal);
4399 nai.updateScoreForNetworkAgentUpdate();
4400 final boolean partialConnectivityChanged = (wasPartial != partial);
4401 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004402
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004403 if (DBG) {
4404 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4405 ? " with redirect to " + redirectUrl
4406 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004407 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004408 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004409 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004410 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004411 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004412 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004413 if (valid) {
4414 handleFreshlyValidatedNetwork(nai);
4415 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4416 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004417 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004418 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004419 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004420 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004421 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004422 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004423 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004424 NotificationType.PRIVATE_DNS_BROKEN);
4425 // If network becomes valid, the hasShownBroken should be reset for
4426 // that network so that the notification will be fired when the private
4427 // DNS is broken again.
4428 nai.networkAgentConfig.hasShownBroken = false;
4429 }
4430 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004431 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004432 } else if (portalChanged) {
4433 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004434 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004435 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4436 nai.onPreventAutomaticReconnect();
4437 teardownUnneededNetwork(nai);
4438 return;
4439 } else {
4440 updateCapabilitiesForNetwork(nai);
4441 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004442 } else if (becameEvaluated) {
4443 // If valid or partial connectivity changed, updateCapabilities* has
4444 // done the rematch.
4445 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004446 }
4447 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004448
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004449 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004450 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004451 nai.onValidationStatusChanged(
4452 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4453 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004454
4455 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004456 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004457 // immediately. Re-notify partial connectivity silently if no internet
4458 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004459 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004460 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004461 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4462 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004463 }
4464
Chalard Jean254bd162022-08-25 13:04:51 +09004465 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004466 handleNetworkUnvalidated(nai);
4467 }
4468 }
4469
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004470 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4471 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4472 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4473 // Do not avoid captive portal when network is wear proxy.
4474 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4475 }
4476
Calvin Ondada1452016-10-11 15:10:46 -07004477 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004478 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4479 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004480 }
4481
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004482 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4483 switch (msg.what) {
4484 default:
4485 return false;
4486 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4487 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4488 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4489 handleLingerComplete(nai);
4490 }
4491 break;
4492 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004493 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4494 handleNetworkAgentRegistered(msg);
4495 break;
4496 }
4497 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4498 handleNetworkAgentDisconnected(msg);
4499 break;
4500 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004501 }
4502 return true;
4503 }
4504
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004505 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004506 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004507 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004508 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004509 maybeHandleNetworkAgentMessage(msg);
4510 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004511 }
4512 }
4513
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004514 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004515 private final int mNetId;
4516 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004517
4518 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004519 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004520 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004521 }
4522
4523 @Override
4524 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4525 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004526 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004527 }
4528
4529 @Override
4530 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004531 // Legacy version of notifyNetworkTestedWithExtras.
4532 // Would only be called if the system has a NetworkStack module older than the
4533 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004534 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004535 }
4536
4537 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004538 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004539 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4540 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004541 final Message msg = mTrackerHandler.obtainMessage(
4542 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004543 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004544 new NetworkTestedResults(
4545 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004546 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004547
4548 // Invoke ConnectivityReport generation for this Network test event.
4549 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4550 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004551
Cody Kestingf1120be2020-08-03 18:01:40 -07004552 // NetworkMonitor reports the network validation result as a bitmask while
4553 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4554 // logical value for ConnectivityDiagnostics.
4555 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4556 p.result);
4557
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004558 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004559 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004560 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4561 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4562
Aaron Huang959d3642021-01-21 15:47:41 +08004563 ConnectivityReportEvent reportEvent =
4564 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4565 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004566 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004567 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004568 }
4569
4570 @Override
4571 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4572 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4573 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004574 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004575 }
4576
4577 @Override
lucasline117e2e2019-10-22 18:27:33 +08004578 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4579 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4580 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004581 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004582 }
4583
4584 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004585 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4586 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4587 EVENT_CAPPORT_DATA_CHANGED,
4588 0, mNetId, data));
4589 }
4590
4591 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004592 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004593 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004594 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004595
4596 final PendingIntent pendingIntent;
4597 // Only the system server can register notifications with package "android"
4598 final long token = Binder.clearCallingIdentity();
4599 try {
paulhu7746e4e2020-06-09 19:07:03 +08004600 pendingIntent = PendingIntent.getBroadcast(
4601 mContext,
4602 0 /* requestCode */,
4603 intent,
4604 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004605 } finally {
4606 Binder.restoreCallingIdentity(token);
4607 }
4608 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4609 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004610 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004611 }
4612
4613 @Override
4614 public void hideProvisioningNotification() {
4615 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004616 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004617 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004618
4619 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004620 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004621 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004622 }
4623
4624 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004625 public int getInterfaceVersion() {
4626 return this.VERSION;
4627 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004628
4629 @Override
4630 public String getInterfaceHash() {
4631 return this.HASH;
4632 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004633 }
4634
Cody Kestingf1120be2020-08-03 18:01:40 -07004635 /**
4636 * Converts the given NetworkMonitor-specific validation result bitmask to a
4637 * ConnectivityDiagnostics-specific validation result int.
4638 */
4639 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4640 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4641 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4642 }
4643 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4644 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4645 }
4646 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4647 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4648 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4649 }
4650
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004651 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004652 log("Data stall detected with methods: " + p.detectionMethod);
4653
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004654 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004655 int detectionMethod = 0;
4656 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4657 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4658 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4659 }
4660 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4661 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4662 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4663 p.tcpMetricsCollectionPeriodMillis);
4664 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004665 }
4666
Cody Kestingf53a0752020-04-15 12:33:28 -07004667 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004668 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004669 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004670
4671 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4672 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4673 // the cost of going through two handlers.
4674 mConnectivityDiagnosticsHandler.sendMessage(msg);
4675 }
4676
Cody Kestingb37958e2020-05-15 10:36:01 -07004677 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4678 return (p.detectionMethod & detectionMethod) != 0;
4679 }
4680
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004681 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4682 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004683 }
4684
Erik Klinea73af002018-06-26 18:53:43 +09004685 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4686 if (nai == null) return;
4687 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4688 // in order to restart a validation pass from within netd.
4689 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4690 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004691 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004692 }
4693 }
4694
Erik Kline31b4a9e2018-01-11 21:07:29 +09004695 private void handlePrivateDnsSettingsChanged() {
4696 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4697
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004698 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004699 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004700 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004701 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4702 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004703 }
4704 }
4705
Erik Kline9a62f012018-03-21 07:18:33 -07004706 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4707 // Private DNS only ever applies to networks that might provide
4708 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004709 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004710
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004711 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004712 // schedule DNS resolutions. If a DNS resolution is required the
4713 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004714 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004715
4716 // With Private DNS bypass support, we can proceed to update the
4717 // Private DNS config immediately, even if we're in strict mode
4718 // and have not yet resolved the provider name into a set of IPs.
4719 updatePrivateDns(nai, cfg);
4720 }
4721
4722 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4723 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004724 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004725 }
4726
dalyk1720e542018-03-05 12:42:22 -05004727 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4728 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4729 if (nai == null) {
4730 return;
4731 }
4732 mDnsManager.updatePrivateDnsValidation(update);
4733 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4734 }
4735
paulhu7c0a2e62021-01-08 00:51:49 +08004736 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004737 int prefixLength) {
4738 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4739 if (nai == null) return;
4740
paulhu7c0a2e62021-01-08 00:51:49 +08004741 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4742 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004743
4744 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004745 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004746 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004747 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004748 prefixLength);
4749 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004750 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004751 return;
4752 }
4753 }
4754
Lorenzo Colittid523d142020-04-01 20:16:30 +09004755 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004756 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4757 }
4758
Hai Shalome58bdc62021-01-11 18:45:34 -08004759 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004760 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004761 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004762 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4763 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4764 }
4765
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004766 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004767 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004768 * @param nai the agent info to update
4769 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004770 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004771 */
junyulai2b6f0c22021-02-03 20:15:30 +08004772 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4773 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4774 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004775 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004776 // one lingered request, set inactive.
4777 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004778 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004779 if (DBG) log("Unsetting inactive " + nai.toShortString());
4780 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004781 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004782 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004783 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004784 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4785 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004786 }
junyulai2b6f0c22021-02-03 20:15:30 +08004787 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004788 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004789 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004790 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004791 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004792 }
4793
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004794 private void handleNetworkAgentRegistered(Message msg) {
4795 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4796 if (!mNetworkAgentInfos.contains(nai)) {
4797 return;
4798 }
4799
4800 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4801 if (VDBG) log("NetworkAgent registered");
4802 } else {
4803 loge("Error connecting NetworkAgent");
4804 mNetworkAgentInfos.remove(nai);
4805 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004806 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004807 synchronized (mNetworkForNetId) {
4808 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004809 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004810 mNetIdManager.releaseNetId(nai.network.getNetId());
4811 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004812 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004813 }
4814 }
4815 }
Paul Jensend5f53392014-11-25 15:26:53 -05004816
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004817 @VisibleForTesting
4818 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09004819 // The feature of creating the networks immediately was slated for U, but race conditions
4820 // detected late required this was flagged off.
4821 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
4822 // in NetworkAgentTest.
4823 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004824 }
4825
4826 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4827 @NonNull NetworkInfo.State state) {
4828 if (nai.isCreated()) return false;
4829 if (state == NetworkInfo.State.CONNECTED) return true;
4830 if (state != NetworkInfo.State.CONNECTING) {
4831 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09004832 if (shouldCreateNetworksImmediately()) {
4833 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4834 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004835 return false;
4836 }
4837 return nai.isVPN() || shouldCreateNetworksImmediately();
4838 }
4839
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004840 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004841 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004842 }
4843
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004844 @VisibleForTesting
4845 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004846 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09004847 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004848
4849 // If the network never roamed, return false. The check below is not sufficient if time
4850 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4851 if (nai.lastRoamTime == 0) return false;
4852
he_won.hwang881307a2022-03-15 21:23:52 +09004853 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4854 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004855 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004856 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004857 final long currentTimeMs = SystemClock.elapsedRealtime();
4858 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004859 if (timeSinceLastRoam <= blockTimeOut) {
4860 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4861 return true;
4862 }
4863 }
4864 return false;
4865 }
4866
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004867 private void handleNetworkAgentDisconnected(Message msg) {
4868 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004869 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004870 }
4871
Chalard Jeand9fffc32018-05-11 20:19:20 +09004872 // Destroys a network, remove references to it from the internal state managed by
4873 // ConnectivityService, free its interfaces and clean up.
4874 // Must be called on the Handler thread.
4875 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004876 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004877
4878 if (!mNetworkAgentInfos.contains(nai)) return;
4879
Chalard Jeand9fffc32018-05-11 20:19:20 +09004880 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004881 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004882 }
lucaslinb25c9a62019-02-12 15:30:13 +08004883 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004884 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004885 // A network agent has disconnected.
4886 // TODO - if we move the logic to the network agent (have them disconnect
4887 // because they lost all their requests or because their score isn't good)
4888 // then they would disconnect organically, report their new state and then
4889 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08004890 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004891 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4892 null, null);
4893 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004894 final boolean wasDefault = isDefaultNetwork(nai);
4895 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004896 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004897 }
4898 notifyIfacesChangedForNetworkStats();
4899 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4900 // by other networks that are already connected. Perhaps that can be done by
4901 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4902 // of rematchAllNetworksAndRequests
4903 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004904 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004905
4906 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004907 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4908 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08004909 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004910 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004911 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004912 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004913 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004914 synchronized (mNetworkForNetId) {
4915 // Remove the NetworkAgent, but don't mark the netId as
4916 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004917 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004918 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004919 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08004920 // Update allowed network lists in netd. This should be called after removing nai
4921 // from mNetworkAgentInfos.
4922 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004923 // Remove all previously satisfied requests.
4924 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004925 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004926 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004927 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004928 if (currentNetwork != null
4929 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004930 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004931 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4932 // rematch not to keep disconnected agents instead of setting it here ; this
4933 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004934 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004935 for (final NetworkOfferInfo noi : mNetworkOffers) {
4936 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004937 }
James Mattise3ef1912020-12-20 11:09:58 -08004938
Chalard Jean5b409c72021-02-04 13:12:59 +09004939 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004940 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004941 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004942 // network, because while incorrect this is the closest to the old (also
4943 // incorrect) behavior.
4944 mNetworkActivityTracker.updateDataActivityTracking(
4945 null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004946 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004947 ensureNetworkTransitionWakelock(nai.toShortString());
4948 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004949 }
4950 }
junyulai2b6f0c22021-02-03 20:15:30 +08004951 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004952 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004953 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004954 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004955 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004956 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004957 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004958
Aaron Huang9fe47be2021-06-08 13:11:45 +08004959 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
4960 // The obvious place to do this would be in makeDefault(), however makeDefault() is
4961 // not called by the rematch in this case. This is because the code above unset
4962 // this network from the default request's satisfier, and that is what the rematch
4963 // is using as its source data to know what the old satisfier was. So as far as the
4964 // rematch above is concerned, the old default network was null.
4965 // Therefore if there is no new default, the default network was null and is still
4966 // null, thus there was no change so makeDefault() is not called. So if the old
4967 // network had a proxy and there is no new default, the proxy tracker should be told
4968 // that there is no longer a default proxy.
4969 // Strictly speaking this is not essential because having a proxy setting when
4970 // there is no network is harmless, but it's still counter-intuitive so reset to null.
4971 mProxyTracker.setDefaultProxy(null);
4972 }
4973
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004974 // Immediate teardown.
4975 if (nai.teardownDelayMs == 0) {
4976 destroyNetwork(nai);
4977 return;
4978 }
4979
4980 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004981 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304982 try {
4983 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4984 } catch (RemoteException e) {
4985 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4986 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004987 }
4988 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4989 }
4990
4991 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004992 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004993 // Tell netd to clean up the configuration for this network
4994 // (routing rules, DNS, etc).
4995 // This may be slow as it requires a lot of netd shelling out to ip and
4996 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004997 // after we've rematched networks with requests (which might change the default
4998 // network or service a new request from an app), so network traffic isn't interrupted
4999 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08005000 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005001 }
Chalard Jeandf29a852023-05-29 17:02:43 +09005002 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005003 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
5004 // This can never run if the code above runs because shouldDestroyNativeNetwork is
5005 // false if the network was never created.
5006 // TODO: delete when S is no longer supported.
5007 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005008 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08005009 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005010 }
5011
Ken Chen6df7a902021-04-09 15:08:42 +08005012 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08005013 try {
5014 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005015 final NativeNetworkConfig config;
5016 if (nai.isVPN()) {
5017 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005018 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005019 return false;
5020 }
5021 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5022 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005023 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005024 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005025 } else {
Chalard Jeane0aaca52023-10-17 13:23:07 +09005026 final boolean hasLocalCap =
5027 nai.networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
5028 config = new NativeNetworkConfig(nai.network.getNetId(),
5029 hasLocalCap ? NativeNetworkType.PHYSICAL_LOCAL : NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005030 getNetworkPermission(nai.networkCapabilities),
5031 false /* secure */,
5032 VpnManager.TYPE_VPN_NONE,
5033 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005034 }
Ken Chen6df7a902021-04-09 15:08:42 +08005035 mNetd.networkCreate(config);
5036 mDnsResolver.createNetworkCache(nai.network.getNetId());
5037 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
5038 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08005039 return true;
5040 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005041 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005042 return false;
5043 }
5044 }
5045
Ken Chen6df7a902021-04-09 15:08:42 +08005046 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005047 if (mDscpPolicyTracker != null) {
5048 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5049 }
Luke Huangfdd11f82019-04-09 18:41:49 +08005050 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005051 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005052 } catch (RemoteException | ServiceSpecificException e) {
5053 loge("Exception destroying network(networkDestroy): " + e);
5054 }
5055 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005056 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005057 } catch (RemoteException | ServiceSpecificException e) {
5058 loge("Exception destroying network: " + e);
5059 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005060 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5061 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5062 // gets created, could add data to DnsManager data structures that will never get deleted.
5063 mDnsManager.removeNetwork(nai.network);
5064
5065 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005066 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005067 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5068 }
5069
Chalard Jean254bd162022-08-25 13:04:51 +09005070 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005071 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005072 }
5073
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005074 // If this method proves to be too slow then we can maintain a separate
5075 // pendingIntent => NetworkRequestInfo map.
5076 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5077 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005078 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5079 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5080 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005081 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005082 return entry.getValue();
5083 }
5084 }
5085 return null;
5086 }
5087
Chalard Jean524f0b12021-10-25 21:11:56 +09005088 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005089 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005090 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5091 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5092 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5093 // bug is fixed.
5094 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005095 throw new IllegalStateException("This NRI is already registered. New : " + nri
5096 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005097 }
5098 }
5099 }
5100 }
5101
Chalard Jeanac9ace02022-01-26 16:54:05 +09005102 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5103 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005104 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09005105 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
5106 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005107 }
5108 return false;
5109 }
5110
James Mattisf7027322020-12-13 16:28:14 -08005111 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005112 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005113 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5114 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5115 final NetworkRequestInfo existingRequest =
5116 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005117 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005118 if (DBG) {
5119 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5120 + nri.mRequests.get(0) + " because their intents matched.");
5121 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005122 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005123 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005124 }
Erik Kline05f2b402015-04-30 12:58:40 +09005125 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005126 }
5127
James Mattisf7027322020-12-13 16:28:14 -08005128 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005129 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005130 }
5131
James Mattis3ce3d3c2021-02-09 18:18:28 -08005132 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005133 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005134 for (final NetworkRequestInfo nri : nris) {
5135 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005136 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005137 for (final NetworkRequest req : nri.mRequests) {
5138 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005139 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005140 if (req.isListen()) {
5141 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5142 if (req.networkCapabilities.hasSignalStrength()
5143 && network.satisfiesImmutableCapabilitiesOf(req)) {
5144 updateSignalStrengthThresholds(network, "REGISTER", req);
5145 }
James Mattisf7027322020-12-13 16:28:14 -08005146 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005147 }
5148 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005149
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005150 // If this NRI has a satisfier already, it is replacing an older request that
5151 // has been removed. Track it.
5152 final NetworkRequest activeRequest = nri.getActiveRequest();
5153 if (null != activeRequest) {
5154 // If there is an active request, then for sure there is a satisfier.
5155 nri.getSatisfier().addRequest(activeRequest);
5156 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005157 }
James Mattisf7027322020-12-13 16:28:14 -08005158
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005159 if (mFlags.noRematchAllRequestsOnRegister()) {
5160 rematchNetworksAndRequests(nris);
5161 } else {
5162 rematchAllNetworksAndRequests();
5163 }
James Mattis45d81842021-01-10 14:24:24 -08005164
Chalard Jean0354d8c2021-01-12 10:58:56 +09005165 // Requests that have not been matched to a network will not have been sent to the
5166 // providers, because the old satisfier and the new satisfier are the same (null in this
5167 // case). Send these requests to the providers.
5168 for (final NetworkRequestInfo nri : nris) {
5169 for (final NetworkOfferInfo noi : mNetworkOffers) {
5170 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005171 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005172 }
5173 }
5174
James Mattisf7027322020-12-13 16:28:14 -08005175 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5176 final int callingUid) {
5177 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005178 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005179 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5180 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5181 handleReleaseNetworkRequest(
5182 nri.mRequests.get(0),
5183 callingUid,
5184 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005185 }
5186 }
5187
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005188 // Determines whether the network is the best (or could become the best, if it validated), for
5189 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5190 // on the value of reason:
5191 //
5192 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5193 // then it should be torn down.
5194 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5195 // then it should be lingered.
5196 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005197 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005198
Chalard Jean254bd162022-08-25 13:04:51 +09005199 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005200 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5201 return false;
5202 }
5203
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005204 final int numRequests;
5205 switch (reason) {
5206 case TEARDOWN:
5207 numRequests = nai.numRequestNetworkRequests();
5208 break;
5209 case LINGER:
5210 numRequests = nai.numForegroundNetworkRequests();
5211 break;
5212 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005213 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005214 return true;
5215 }
5216
Chalard Jean947acd42021-03-08 22:29:27 +09005217 if (numRequests > 0) return false;
5218
Paul Jensende49eb12015-06-25 15:30:08 -04005219 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005220 if (reason == UnneededFor.LINGER
5221 && !nri.isMultilayerRequest()
5222 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005223 // Background requests don't affect lingering.
5224 continue;
5225 }
5226
James Mattis3d229892020-11-16 16:46:28 -08005227 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005228 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005229 }
5230 }
Paul Jensende49eb12015-06-25 15:30:08 -04005231 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005232 }
5233
James Mattis3d229892020-11-16 16:46:28 -08005234 private boolean isNetworkPotentialSatisfier(
5235 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
5236 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005237 // request, return immediately. For multilayer requests, check to see if any of the
5238 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005239 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5240 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005241 return false;
5242 }
5243 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005244 // This multilayer listen request is satisfied therefore no further requests need to be
5245 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005246 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005247 return false;
5248 }
James Mattis3d229892020-11-16 16:46:28 -08005249 // As non-multilayer listen requests have already returned, the below would only happen
5250 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005251 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005252 continue;
5253 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09005254 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08005255 // there is hope for it to become one if it validated, then it is needed.
5256 if (candidate.satisfies(req)) {
5257 // As soon as a network is found that satisfies a request, return. Specifically for
5258 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5259 // is important so as to not evaluate lower priority requests further in
5260 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005261 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5262 ? nri.getSatisfier() : null;
5263 // Note that this catches two important cases:
5264 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5265 // is currently satisfying the request. This is desirable when
5266 // cellular ends up validating but WiFi does not.
5267 // 2. Unvalidated WiFi will not be reaped when validated cellular
5268 // is currently satisfying the request. This is desirable when
5269 // WiFi ends up validating and out scoring cellular.
5270 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005271 }
5272 }
5273
5274 return false;
5275 }
5276
Erik Kline0c04b742016-07-07 16:50:58 +09005277 private NetworkRequestInfo getNriForAppRequest(
5278 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005279 // Looking up the app passed param request in mRequests isn't possible since it may return
5280 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5281 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005282 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5283 // to avoid potential race conditions when validating a package->uid mapping when sending
5284 // the callback on the very low-chance that an application shuts down prior to the callback
5285 // being sent.
5286 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5287 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005288
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005289 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005290 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005291 log(String.format("UID %d attempted to %s for unowned request %s",
5292 callingUid, requestedOperation, nri));
5293 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005294 }
Erik Kline0c04b742016-07-07 16:50:58 +09005295 }
5296
5297 return nri;
5298 }
5299
James Mattisf7027322020-12-13 16:28:14 -08005300 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5301 final String callingMethod) {
5302 if (nri.isMultilayerRequest()) {
5303 throw new IllegalStateException(
5304 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005305 }
5306 }
5307
James Mattisf7027322020-12-13 16:28:14 -08005308 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005309 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005310 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5311 // single NetworkRequest and thus does not apply to multilayer requests.
5312 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5313 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005314 return;
5315 }
James Mattis2516da32021-01-31 17:06:19 -08005316 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005317 return;
5318 }
James Mattisf7027322020-12-13 16:28:14 -08005319 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5320 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005321 }
5322 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005323 callCallbackForRequest(
5324 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005325 }
5326
James Mattisf7027322020-12-13 16:28:14 -08005327 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5328 final int callingUid,
5329 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005330 final NetworkRequestInfo nri =
5331 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5332 if (nri == null) {
5333 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005334 }
James Mattisf7027322020-12-13 16:28:14 -08005335 if (VDBG || (DBG && request.isRequest())) {
5336 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005337 }
5338 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005339 if (callOnUnavailable) {
5340 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5341 }
Erik Kline155a59a2015-11-25 12:49:38 +09005342 }
Erik Kline0c04b742016-07-07 16:50:58 +09005343
James Mattisa076c532020-12-02 14:12:41 -08005344 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005345 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005346 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005347 if (null == mNetworkRequests.remove(req)) {
5348 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5349 continue;
5350 }
James Mattisa076c532020-12-02 14:12:41 -08005351 if (req.isListen()) {
5352 removeListenRequestFromNetworks(req);
5353 }
5354 }
James Mattis8f036802021-06-20 16:26:01 -07005355 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005356 if (mDefaultNetworkRequests.remove(nri)) {
5357 // If this request was one of the defaults, then the UID rules need to be updated
5358 // WARNING : if the app(s) for which this network request is the default are doing
5359 // traffic, this will kill their connected sockets, even if an equivalent request
5360 // is going to be reinstated right away ; unconnected traffic will go on the default
5361 // until the new default is set, which will happen very soon.
5362 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5363 // remove ranges for those requests that won't have a replacement
5364 final NetworkAgentInfo satisfier = nri.getSatisfier();
5365 if (null != satisfier) {
5366 try {
paulhu0e79d952021-06-09 16:11:35 +08005367 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5368 satisfier.network.getNetId(),
5369 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005370 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005371 } catch (RemoteException e) {
5372 loge("Exception setting network preference default network", e);
5373 }
5374 }
5375 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005376
Junyu Lai00d92df2022-07-05 11:01:52 +08005377 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005378 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005379 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005380
5381 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005382 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005383 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005384 }
5385 }
5386
Chalard Jean0354d8c2021-01-12 10:58:56 +09005387 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5388 // needed for this offer.
5389 for (final NetworkOfferInfo noi : mNetworkOffers) {
5390 for (final NetworkRequest req : nri.mRequests) {
5391 if (req.isRequest() && noi.offer.neededFor(req)) {
5392 noi.offer.onNetworkUnneeded(req);
5393 }
5394 }
5395 }
James Mattisa076c532020-12-02 14:12:41 -08005396 }
5397
James Mattis3ce3d3c2021-02-09 18:18:28 -08005398 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5399 for (final NetworkRequestInfo nri : nris) {
5400 if (mDefaultRequest == nri) {
5401 // Make sure we never remove the default request.
5402 continue;
5403 }
5404 handleRemoveNetworkRequest(nri);
5405 }
5406 }
5407
James Mattisa076c532020-12-02 14:12:41 -08005408 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5409 // listens don't have a singular affected Network. Check all networks to see
5410 // if this listen request applies and remove it.
5411 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5412 nai.removeRequest(req.requestId);
5413 if (req.networkCapabilities.hasSignalStrength()
5414 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5415 updateSignalStrengthThresholds(nai, "RELEASE", req);
5416 }
5417 }
5418 }
5419
5420 /**
5421 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5422 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5423 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5424 */
5425 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5426 boolean wasKept = false;
5427 final NetworkAgentInfo nai = nri.getSatisfier();
5428 if (nai != null) {
5429 final int requestLegacyType = nri.getActiveRequest().legacyType;
5430 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5431 nai.removeRequest(nri.getActiveRequest().requestId);
5432 if (VDBG || DDBG) {
5433 log(" Removing from current network " + nai.toShortString()
5434 + ", leaving " + nai.numNetworkRequests() + " requests.");
5435 }
5436 // If there are still lingered requests on this network, don't tear it down,
5437 // but resume lingering instead.
5438 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005439 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005440 notifyNetworkLosing(nai, now);
5441 }
5442 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5443 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5444 teardownUnneededNetwork(nai);
5445 } else {
5446 wasKept = true;
5447 }
James Mattisa076c532020-12-02 14:12:41 -08005448 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5449 // Went from foreground to background.
5450 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005451 }
5452
Erik Kline0c04b742016-07-07 16:50:58 +09005453 // Maintain the illusion. When this request arrived, we might have pretended
5454 // that a network connected to serve it, even though the network was already
5455 // connected. Now that this request has gone away, we might have to pretend
5456 // that the network disconnected. LegacyTypeTracker will generate that
5457 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005458 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005459 boolean doRemove = true;
5460 if (wasKept) {
5461 // check if any of the remaining requests for this network are for the
5462 // same legacy type - if so, don't remove the nai
5463 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5464 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005465 if (otherRequest.legacyType == requestLegacyType
5466 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005467 if (DBG) log(" still have other legacy request - leaving");
5468 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005469 }
5470 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005471 }
5472
Erik Kline0c04b742016-07-07 16:50:58 +09005473 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005474 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005475 }
5476 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005477 }
5478 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005479
Junyu Lai00d92df2022-07-05 11:01:52 +08005480 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005481 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005482 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5483 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5484 }
5485
Lorenzo Colittid6459092016-07-04 12:55:44 +09005486 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005487 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005488 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005489 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005490 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005491 }
5492
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005493 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005494 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5495 enforceNetworkStackSettingsOrSetup();
5496 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5497 encodeBool(accept), encodeBool(always), network));
5498 }
5499
5500 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005501 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005502 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005503 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5504 }
5505
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005506 @Override
5507 public void setTestAllowBadWifiUntil(long timeMs) {
5508 enforceSettingsPermission();
5509 if (!Build.isDebuggable()) {
5510 throw new IllegalStateException("Does not support in non-debuggable build");
5511 }
5512
5513 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5514 throw new IllegalArgumentException("It should not exceed "
5515 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5516 }
5517
5518 mHandler.sendMessage(
5519 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5520 }
5521
chiachangwange0192a72023-02-06 13:25:01 +00005522 @Override
5523 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5524 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005525
5526 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5527 throw new IllegalArgumentException("Argument should not exceed "
5528 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5529 }
5530
5531 mHandler.sendMessage(
5532 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5533 }
5534
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005535 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5536 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5537 " accept=" + accept + " always=" + always);
5538
5539 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5540 if (nai == null) {
5541 // Nothing to do.
5542 return;
5543 }
5544
Chalard Jean254bd162022-08-25 13:04:51 +09005545 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005546 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005547 return;
5548 }
5549
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005550 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005551 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005552 }
5553
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005554 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5555 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005556 // If network becomes partial connectivity and user already accepted to use this
5557 // network, we should respect the user's option and don't need to popup the
5558 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005559 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005560 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005561 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005562 }
5563
5564 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005565 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005566 }
5567
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005568 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005569 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005570 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005571 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005572 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005573 }
5574
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005575 }
5576
lucaslin2240ef62019-03-12 13:08:03 +08005577 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5578 boolean always) {
5579 if (DBG) {
5580 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5581 + " always=" + always);
5582 }
5583
5584 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5585 if (nai == null) {
5586 // Nothing to do.
5587 return;
5588 }
5589
Chalard Jean254bd162022-08-25 13:04:51 +09005590 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005591 // The network validated while the dialog box was up. Take no action.
5592 return;
5593 }
5594
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005595 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5596 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005597 }
5598
5599 // TODO: Use the current design or save the user choice into IpMemoryStore.
5600 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005601 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005602 }
5603
5604 if (!accept) {
5605 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005606 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005607 // Tear down the network.
5608 teardownUnneededNetwork(nai);
5609 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005610 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5611 // result in a partial connectivity result which will be processed by
5612 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005613 //
5614 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5615 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005616 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005617 }
5618 }
5619
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005620 private void handleSetAvoidUnvalidated(Network network) {
5621 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005622 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005623 // Nothing to do. The network either disconnected or revalidated.
5624 return;
5625 }
Chalard Jean254bd162022-08-25 13:04:51 +09005626 if (0L == nai.getAvoidUnvalidated()) {
5627 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005628 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005629 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005630 }
5631 }
5632
Chalard Jean5fb43c72022-09-08 19:03:14 +09005633 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005634 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005635 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005636 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005637 }
5638
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005639 @Override
5640 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005641 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005642 mHandler.post(() -> {
5643 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5644 if (nai == null) return;
5645 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005646 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005647 });
5648 }
5649
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005650 /**
5651 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5652 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005653 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005654 * @param appExtras Bundle to use as intent extras for the captive portal application.
5655 * Must be treated as opaque to avoid preventing the captive portal app to
5656 * update its arguments.
5657 */
5658 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005659 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005660 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5661 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005662
5663 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5664 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005665 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5666 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005667 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5668
lucaslin75ff7022020-12-17 04:14:35 +08005669 final long token = Binder.clearCallingIdentity();
5670 try {
5671 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5672 } finally {
5673 Binder.restoreCallingIdentity(token);
5674 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005675 }
5676
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005677 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5678 private final Network mNetwork;
5679
5680 private CaptivePortalImpl(Network network) {
5681 mNetwork = network;
5682 }
5683
5684 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005685 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005686 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5687 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005688 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5689 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5690 // Since the network will be disconnected, skip notifying NetworkMonitor
5691 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005692 }
5693
Chiachang Wang938bfba2020-01-09 13:50:55 +08005694 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005695 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005696 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005697 }
5698
5699 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005700 public void appRequest(final int request) {
5701 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5702 if (nm == null) return;
5703
5704 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005705 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005706 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005707 }
5708 }
5709
5710 @Nullable
5711 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5712 // getNetworkAgentInfoForNetwork is thread-safe
5713 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5714 if (nai == null) return null;
5715
5716 // nai.networkMonitor() is thread-safe
5717 return nai.networkMonitor();
5718 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005719 }
5720
Hugo Benichic9048bc2016-09-14 23:23:08 +00005721 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005722 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005723 }
5724
Chalard Jean020b93a2022-09-01 13:20:14 +09005725 private boolean activelyPreferBadWifi() {
5726 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5727 }
5728
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005729 /**
5730 * Return whether the device should maintain continuous, working connectivity by switching away
5731 * from WiFi networks having no connectivity.
5732 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5733 */
5734 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005735 if (!checkNetworkStackPermission()) {
5736 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5737 }
5738 return avoidBadWifi();
5739 }
5740
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005741 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005742 ensureRunningOnConnectivityServiceThread();
5743 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005744 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005745 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005746 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005747 if (avoidBadWifi) {
5748 // If the device is now avoiding bad wifi, remove notifications that might have
5749 // been put up when the device didn't.
5750 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5751 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005752 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005753 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5754 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5755 for (final NetworkOfferInfo noi : offersToUpdate) {
5756 updateOfferScore(noi.offer);
5757 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005758 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005759 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005760 }
5761
Erik Kline95ecfee2016-10-02 18:02:14 +09005762 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005763 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005764 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005765 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005766 if (!configRestrict) {
5767 pw.println("Bad Wi-Fi avoidance: unrestricted");
5768 return;
5769 }
5770
5771 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5772 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005773 pw.println("Config restrict: " + configRestrict);
5774 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005775
Chalard Jeane0fdea32022-09-14 21:44:22 +09005776 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005777 String description;
5778 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005779 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005780 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005781 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005782 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005783 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005784 description = "avoid";
5785 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005786 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005787 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005788 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005789
5790 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5791 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005792 if (null == configValue) {
5793 description = "unset";
5794 } else if (configValue) {
5795 description = "force true";
5796 } else {
5797 description = "force false";
5798 }
5799 pw.println("Actively prefer bad wifi conf: " + description);
5800 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005801 pw.println("Network overrides:");
5802 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005803 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005804 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005805 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005806 }
5807 }
5808 pw.decreaseIndent();
5809 pw.decreaseIndent();
5810 }
5811
paulhu7746e4e2020-06-09 19:07:03 +08005812 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5813 // unify the method.
5814 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5815 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5816 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5817 return settingsComponent != null
5818 ? settingsComponent.getPackageName() : "com.android.settings";
5819 }
5820
lucaslinb1e8e382019-01-24 15:55:30 +08005821 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005822 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005823 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005824 switch (type) {
5825 case NO_INTERNET:
5826 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005827 // High priority because it is only displayed for explicitly selected networks.
5828 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005829 break;
lucasline117e2e2019-10-22 18:27:33 +08005830 case PRIVATE_DNS_BROKEN:
5831 action = Settings.ACTION_WIRELESS_SETTINGS;
5832 // High priority because we should let user know why there is no internet.
5833 highPriority = true;
5834 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005835 case LOST_INTERNET:
5836 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005837 // High priority because it could help the user avoid unexpected data usage.
5838 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005839 break;
lucaslin2240ef62019-03-12 13:08:03 +08005840 case PARTIAL_CONNECTIVITY:
5841 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005842 // Don't bother the user with a high-priority notification if the network was not
5843 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005844 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005845 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005846 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005847 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005848 return;
5849 }
5850
5851 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005852 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005853 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005854 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005855 // Some OEMs have their own Settings package. Thus, need to get the current using
5856 // Settings package name instead of just use default name "com.android.settings".
5857 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5858 intent.setClassName(settingsPkgName,
5859 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005860 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005861
paulhu2af50222020-10-11 22:52:27 +08005862 PendingIntent pendingIntent = PendingIntent.getActivity(
5863 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005864 0 /* requestCode */,
5865 intent,
paulhu2af50222020-10-11 22:52:27 +08005866 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005867
Serik Beketayevec8ad212020-12-07 22:43:07 -08005868 mNotifier.showNotification(
5869 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005870 }
5871
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005872 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5873 // Don't prompt if the network is validated, and don't prompt on captive portals
5874 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005875 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005876 return false;
5877 }
5878
5879 // If a network has partial connectivity, always prompt unless the user has already accepted
5880 // partial connectivity and selected don't ask again. This ensures that if the device
5881 // automatically connects to a network that has partial Internet access, the user will
5882 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005883 // because we have prompted them.
5884 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005885 return true;
5886 }
5887
5888 // If a network has no Internet access, only prompt if the network was explicitly selected
5889 // and if the user has not already told us to use the network regardless of whether it
5890 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005891 if (nai.networkAgentConfig.explicitlySelected
5892 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005893 return true;
5894 }
5895
5896 return false;
5897 }
5898
Chalard Jean5fb43c72022-09-08 19:03:14 +09005899 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5900 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005901
Chalard Jean5fb43c72022-09-08 19:03:14 +09005902 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5903 if (null == nai) return;
5904
5905 if (nai.setEvaluated()) {
5906 // If setEvaluated() returned true, the network never had any form of connectivity.
5907 // This may have an impact on request matching if bad WiFi avoidance is off and the
5908 // network was found not to have Internet access.
5909 nai.updateScoreForNetworkAgentUpdate();
5910 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005911
5912 // Also, if this is WiFi and it should be preferred actively, now is the time to
5913 // prompt the user that they walked past and connected to a bad WiFi.
5914 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5915 && !avoidBadWifi()
5916 && activelyPreferBadWifi()) {
5917 // The notification will be removed if the network validates or disconnects.
5918 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5919 return;
5920 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005921 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005922
Chalard Jean5fb43c72022-09-08 19:03:14 +09005923 if (!shouldPromptUnvalidated(nai)) return;
5924
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005925 // Stop automatically reconnecting to this network in the future. Automatically connecting
5926 // to a network that provides no or limited connectivity is not useful, because the user
5927 // cannot use that network except through the notification shown by this method, and the
5928 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005929 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005930
Chalard Jean254bd162022-08-25 13:04:51 +09005931 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005932 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005933 } else {
5934 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5935 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005936 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005937
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005938 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5939 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005940 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005941
lucaslin2240ef62019-03-12 13:08:03 +08005942 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5943 return;
5944 }
5945
5946 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005947 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005948 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005949 }
5950
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005951 @Override
5952 public int getMultipathPreference(Network network) {
5953 enforceAccessPermission();
5954
5955 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005956 if (nai != null && nai.networkCapabilities
5957 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005958 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5959 }
5960
Aaron Huang9a57acf2020-12-08 10:03:29 +08005961 final NetworkPolicyManager netPolicyManager =
5962 mContext.getSystemService(NetworkPolicyManager.class);
5963
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005964 final long token = Binder.clearCallingIdentity();
5965 final int networkPreference;
5966 try {
5967 networkPreference = netPolicyManager.getMultipathPreference(network);
5968 } finally {
5969 Binder.restoreCallingIdentity(token);
5970 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005971 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005972 return networkPreference;
5973 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005974 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5975 }
5976
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005977 @Override
5978 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005979 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005980 }
5981
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005982 private class InternalHandler extends Handler {
5983 public InternalHandler(Looper looper) {
5984 super(looper);
5985 }
5986
5987 @Override
5988 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005989 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005990 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005991 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005992 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005993 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005994 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005995 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005996 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005997 break;
5998 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08005999 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08006000 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08006001 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04006002 break;
6003 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006004 case EVENT_REGISTER_NETWORK_PROVIDER: {
6005 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006006 break;
6007 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006008 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
6009 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006010 break;
6011 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006012 case EVENT_REGISTER_NETWORK_OFFER: {
6013 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
6014 break;
6015 }
6016 case EVENT_UNREGISTER_NETWORK_OFFER: {
6017 final NetworkOfferInfo offer =
6018 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6019 if (null != offer) {
6020 handleUnregisterNetworkOffer(offer);
6021 }
6022 break;
6023 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006024 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006025 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6026 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6027 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006028 break;
6029 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006030 case EVENT_REGISTER_NETWORK_REQUEST:
6031 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006032 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006033 break;
6034 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006035 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6036 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006037 handleRegisterNetworkRequestWithIntent(msg);
6038 break;
6039 }
Erik Kline155a59a2015-11-25 12:49:38 +09006040 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6041 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6042 handleTimedOutNetworkRequest(nri);
6043 break;
6044 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006045 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6046 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6047 break;
6048 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006049 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006050 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6051 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006052 break;
6053 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006054 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006055 Network network = (Network) msg.obj;
6056 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006057 break;
6058 }
lucaslin2240ef62019-03-12 13:08:03 +08006059 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6060 Network network = (Network) msg.obj;
6061 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6062 toBool(msg.arg2));
6063 break;
6064 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006065 case EVENT_SET_AVOID_UNVALIDATED: {
6066 handleSetAvoidUnvalidated((Network) msg.obj);
6067 break;
6068 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006069 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6070 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006071 break;
6072 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006073 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6074 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006075 break;
6076 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006077 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6078 // handler thread.
6079 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006080 mKeepaliveTracker.handleStartKeepalive(msg);
6081 break;
6082 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006083 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006084 final AutomaticOnOffKeepalive ki =
6085 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6086 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006087
chiachangwang676c84e2023-02-14 09:22:05 +00006088 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006089 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006090 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006091 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006092 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6093 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006094 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6095 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006096 }
6097 }
6098
6099 // If the network no longer exists, then the keepalive should have been
6100 // cleaned up already. There is no point trying to resume keepalives.
6101 if (!networkFound) return;
6102
chiachangwang676c84e2023-02-14 09:22:05 +00006103 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006104 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang676c84e2023-02-14 09:22:05 +00006105 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006106 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006107 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006108 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006109 }
6110 break;
6111 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006112 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006113 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006114 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6115 (IBinder) msg.obj);
6116 if (ki == null) {
6117 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006118 return;
6119 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006120 final int reason = msg.arg2;
6121 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006122 break;
6123 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006124 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6125 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6126 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006127 break;
6128 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006129 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6130 handlePrivateDnsSettingsChanged();
6131 break;
dalyk1720e542018-03-05 12:42:22 -05006132 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6133 handlePrivateDnsValidationUpdate(
6134 (PrivateDnsValidationUpdate) msg.obj);
6135 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006136 case EVENT_UID_BLOCKED_REASON_CHANGED:
6137 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006138 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006139 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6140 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6141 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006142 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006143 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6144 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006145 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006146 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006147 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006148 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006149 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6150 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006151 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006152 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006153 }
lucaslin1193a5d2021-01-21 02:04:15 +08006154 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006155 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006156 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006157 break;
paulhu51f77dc2021-06-07 02:34:20 +00006158 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6159 handleMobileDataPreferredUidsChanged();
6160 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006161 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6162 final long timeMs = ((Long) msg.obj).longValue();
6163 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6164 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006165 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6166 handleIngressRateLimitChanged();
6167 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006168 case EVENT_USER_DOES_NOT_WANT:
6169 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6170 if (nai == null) break;
6171 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006172 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006173 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006174 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6175 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6176 break;
chiachangwange0192a72023-02-06 13:25:01 +00006177 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6178 final long time = ((Long) msg.obj).longValue();
6179 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6180 break;
6181 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006182 case EVENT_UID_FROZEN_STATE_CHANGED:
6183 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6184 handleFrozenUids(args.mUids, args.mFrozenStates);
6185 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006186 }
6187 }
6188 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006189
Lorenzo Colittid6459092016-07-04 12:55:44 +09006190 @Override
markchien5776f962019-12-16 20:15:20 +08006191 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006192 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006193 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006194 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6195 Context.TETHERING_SERVICE);
6196 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006197 }
6198
Lorenzo Colittid6459092016-07-04 12:55:44 +09006199 @Override
markchien5776f962019-12-16 20:15:20 +08006200 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006201 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006202 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006203 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6204 Context.TETHERING_SERVICE);
6205 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006206 }
6207
Lorenzo Colittid6459092016-07-04 12:55:44 +09006208 @Override
markchien5776f962019-12-16 20:15:20 +08006209 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006210 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006211 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006212 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6213 Context.TETHERING_SERVICE);
6214 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006215 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006216
markchien5776f962019-12-16 20:15:20 +08006217
Lorenzo Colittid6459092016-07-04 12:55:44 +09006218 @Override
markchien5776f962019-12-16 20:15:20 +08006219 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006220 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006221 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006222 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6223 Context.TETHERING_SERVICE);
6224
6225 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006226 }
6227
Lorenzo Colittid6459092016-07-04 12:55:44 +09006228 @Override
markchien5776f962019-12-16 20:15:20 +08006229 @Deprecated
6230 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006231 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006232 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6233 Context.TETHERING_SERVICE);
6234
6235 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006236 }
6237
Udam Saini8f7d6a72017-06-07 12:06:28 -07006238 @Override
markchien5776f962019-12-16 20:15:20 +08006239 @Deprecated
6240 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006241 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006242 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6243 Context.TETHERING_SERVICE);
6244 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006245 }
6246
Robert Greenwalte0b00512014-07-02 09:59:16 -07006247 // Called when we lose the default network and have no replacement yet.
6248 // This will automatically be cleared after X seconds or a new default network
6249 // becomes CONNECTED, whichever happens first. The timer is started by the
6250 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006251 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006252 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006253 if (mNetTransitionWakeLock.isHeld()) {
6254 return;
6255 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006256 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006257 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6258 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006259 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006260 mWakelockLogs.log("ACQUIRE for " + forWhom);
6261 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006262 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006263 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006264 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006265 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006266
Hugo Benichi471b62a2017-03-30 23:18:10 +09006267 // Called when we gain a new default network to release the network transition wakelock in a
6268 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6269 // message is cancelled.
6270 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006271 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006272 if (!mNetTransitionWakeLock.isHeld()) {
6273 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006274 }
6275 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006276 // Cancel self timeout on wakelock hold.
6277 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6278 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6279 mHandler.sendMessageDelayed(msg, 1000);
6280 }
6281
6282 // Called when either message of ensureNetworkTransitionWakelock or
6283 // scheduleReleaseNetworkTransitionWakelock is processed.
6284 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6285 String event = eventName(eventId);
6286 synchronized (this) {
6287 if (!mNetTransitionWakeLock.isHeld()) {
6288 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006289 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006290 return;
6291 }
6292 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006293 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6294 mTotalWakelockDurationMs += lockDuration;
6295 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6296 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006297 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006298 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006299 }
6300
Robert Greenwalt986c7412010-09-08 15:24:47 -07006301 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006302 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006303 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006304 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006305 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006306 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006307 }
6308
Lorenzo Colittid6459092016-07-04 12:55:44 +09006309 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006310 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006311 enforceAccessPermission();
6312 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006313 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006314 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006315
6316 final NetworkAgentInfo nai;
6317 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006318 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006319 } else {
6320 nai = getNetworkAgentInfoForNetwork(network);
6321 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006322
6323 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006324 mHandler.obtainMessage(
6325 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006326 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006327
Hugo Benichid6b510a2017-04-06 17:22:18 +09006328 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006329 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006330 if (nai == null
6331 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006332 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006333 return;
6334 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006335 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006336 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006337 mConnectivityDiagnosticsHandler.sendMessage(
6338 mConnectivityDiagnosticsHandler.obtainMessage(
6339 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6340 new ReportedNetworkConnectivityInfo(
6341 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006342 return;
6343 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006344 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006345 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006346 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006347 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006348 // Validating a network that has not yet connected could result in a call to
6349 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006350 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006351 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006352 }
paulhu7aeba372020-12-30 00:42:19 +08006353 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6354 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006355 return;
6356 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006357
6358 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6359 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6360 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6361 // completed.
6362 mConnectivityDiagnosticsHandler.sendMessage(
6363 mConnectivityDiagnosticsHandler.obtainMessage(
6364 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6365 new ReportedNetworkConnectivityInfo(
6366 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006367 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006368 }
6369
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006370 // TODO: call into netd.
6371 private boolean queryUserAccess(int uid, Network network) {
6372 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6373 if (nai == null) return false;
6374
6375 // Any UID can use its default network.
6376 if (nai == getDefaultNetworkForUid(uid)) return true;
6377
6378 // Privileged apps can use any network.
6379 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6380 return true;
6381 }
6382
6383 // An unprivileged UID can use a VPN iff the VPN applies to it.
6384 if (nai.isVPN()) {
6385 return nai.networkCapabilities.appliesToUid(uid);
6386 }
6387
6388 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6389 // sockets, i.e., if it is the owner.
6390 final NetworkAgentInfo vpn = getVpnForUid(uid);
6391 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6392 && uid != vpn.networkCapabilities.getOwnerUid()) {
6393 return false;
6394 }
6395
6396 // The UID's permission must be at least sufficient for the network. Since the restricted
6397 // permission was already checked above, that just leaves background networks.
6398 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6399 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6400 }
6401
6402 // Unrestricted network. Anyone gets to use it.
6403 return true;
6404 }
6405
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006406 /**
6407 * Returns information about the proxy a certain network is using. If given a null network, it
6408 * it will return the proxy for the bound network for the caller app or the default proxy if
6409 * none.
6410 *
6411 * @param network the network we want to get the proxy information for.
6412 * @return Proxy information if a network has a proxy configured, or otherwise null.
6413 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006414 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006415 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006416 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006417 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006418 if (network == null) {
6419 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006420 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006421 true);
6422 if (activeNetwork == null) {
6423 return null;
6424 }
6425 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006426 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006427 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6428 // caller may not have.
6429 return getLinkPropertiesProxyInfo(network);
6430 }
6431 // No proxy info available if the calling UID does not have network access.
6432 return null;
6433 }
6434
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006435
6436 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006437 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6438 if (nai == null) return null;
6439 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006440 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6441 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006442 }
6443 }
6444
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006445 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006446 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006447 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006448 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006449 }
6450
Chalard Jean777e2e52018-06-07 18:02:37 +09006451 @Override
6452 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006453 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006454 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006455 }
6456
Aaron Huang9fe47be2021-06-08 13:11:45 +08006457 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006458 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006459 final NetworkAgentInfo nai = getDefaultNetwork();
6460 // TODO : this method should check that net == nai.network, unfortunately at this point
6461 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6462 // is only ever installed on the default network so in practice this is okay.
6463 if (null == nai) return;
6464 // PAC proxies only work on the default network. Therefore, only the default network
6465 // should have its link properties fixed up for PAC proxies.
6466 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6467 if (nai.everConnected()) {
6468 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6469 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006470 }
6471
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006472 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6473 // when any network changes proxy.
6474 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6475 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006476 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6477 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006478 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6479
Chalard Jean7d97afc2018-06-07 17:41:29 +09006480 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006481 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006482 }
6483 }
6484
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006485 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006486 final private HashMap<Uri, Integer> mUriEventMap;
6487 final private Context mContext;
6488 final private Handler mHandler;
6489
6490 SettingsObserver(Context context, Handler handler) {
6491 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006492 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006493 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006494 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006495 }
6496
Erik Kline05f2b402015-04-30 12:58:40 +09006497 void observe(Uri uri, int what) {
6498 mUriEventMap.put(uri, what);
6499 final ContentResolver resolver = mContext.getContentResolver();
6500 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006501 }
6502
6503 @Override
6504 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006505 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006506 }
6507
6508 @Override
6509 public void onChange(boolean selfChange, Uri uri) {
6510 final Integer what = mUriEventMap.get(uri);
6511 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006512 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006513 } else {
6514 loge("No matching event to send for URI=" + uri);
6515 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006516 }
6517 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006518
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006519 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006520 Log.d(TAG, s);
6521 }
6522
6523 private static void logw(String s) {
6524 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006525 }
6526
Daniel Brightf9e945b2020-06-15 16:10:01 -07006527 private static void logwtf(String s) {
6528 Log.wtf(TAG, s);
6529 }
6530
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006531 private static void logwtf(String s, Throwable t) {
6532 Log.wtf(TAG, s, t);
6533 }
6534
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006535 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006536 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006537 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006538
Hugo Benichi39621362017-02-11 17:04:43 +09006539 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006540 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006541 }
6542
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006543 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006544 * Return the information of all ongoing VPNs.
6545 *
6546 * <p>This method is used to update NetworkStatsService.
6547 *
6548 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006549 */
junyulai2050bed2021-01-23 09:46:34 +08006550 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006551 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006552 if (mLockdownEnabled) {
6553 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006554 }
junyulai2050bed2021-01-23 09:46:34 +08006555 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006556 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006557 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006558 if (info != null) {
6559 infoList.add(info);
6560 }
6561 }
junyulai2050bed2021-01-23 09:46:34 +08006562 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006563 }
6564
6565 /**
6566 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006567 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006568 */
junyulai2050bed2021-01-23 09:46:34 +08006569 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006570 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006571 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6572 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006573 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6574 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6575 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006576 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6577 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006578 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006579 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006580 }
6581 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006582
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006583 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006584
6585 List<String> interfaces = new ArrayList<>();
6586 for (Network network : underlyingNetworks) {
6587 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6588 if (underlyingNai == null) continue;
6589 LinkProperties lp = underlyingNai.linkProperties;
6590 for (String iface : lp.getAllInterfaceNames()) {
6591 if (!TextUtils.isEmpty(iface)) {
6592 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006593 }
6594 }
Benedict Wong34857f82019-06-12 17:46:15 +00006595 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006596
6597 if (interfaces.isEmpty()) return null;
6598
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006599 // Must be non-null or NetworkStatsService will crash.
6600 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6601 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006602 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006603 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006604
junyulai2050bed2021-01-23 09:46:34 +08006605 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6606 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006607 }
6608
James Mattisd31bdfa2020-12-23 16:37:26 -08006609 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006610 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6611 Network[] underlyingNetworks) {
6612 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006613 if (underlyingNetworks == null && defaultNetwork != null) {
6614 // null underlying networks means to track the default.
6615 underlyingNetworks = new Network[] { defaultNetwork };
6616 }
6617 return underlyingNetworks;
6618 }
6619
6620 // Returns true iff |network| is an underlying network of |nai|.
6621 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6622 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6623 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006624 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006625 final Network[] underlying = underlyingNetworksOrDefault(
6626 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006627 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006628 }
6629
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006630 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006631 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006632 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006633 * When underlying networks change, such networks may have to update capabilities to reflect
6634 * things like the metered bit, their transports, and so on. The capabilities are calculated
6635 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006636 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006637 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006638 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006639 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006640 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006641 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006642 }
6643 }
6644 }
6645
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006646 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6647 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6648 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6649 // a VPN is not up.
6650 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6651 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6652 for (UidRange range : blockedUidRanges) {
6653 if (range.contains(uid)) return true;
6654 }
6655 return false;
6656 }
6657
6658 @Override
6659 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006660 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006661 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6662 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6663 }
6664
6665 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6666 if (DBG) {
6667 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6668 + Arrays.toString(ranges));
6669 }
6670 // Cannot use a Set since the list of UID ranges might contain duplicates.
6671 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6672 for (int i = 0; i < ranges.length; i++) {
6673 if (requireVpn) {
6674 newVpnBlockedUidRanges.add(ranges[i]);
6675 } else {
6676 newVpnBlockedUidRanges.remove(ranges[i]);
6677 }
6678 }
6679
6680 try {
6681 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6682 } catch (RemoteException | ServiceSpecificException e) {
6683 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6684 + Arrays.toString(ranges) + "): netd command failed: " + e);
6685 }
6686
Chalard Jeandf29a852023-05-29 17:02:43 +09006687 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006688 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6689 }
6690
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006691 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6692 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006693 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6694 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006695 }
6696
6697 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6698 }
6699
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006700 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006701 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006702 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006703 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006704 }
6705
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006706 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6707 return mLockdownEnabled
6708 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6709 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006710 }
6711
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006712 private NetworkAgentInfo getLegacyLockdownNai() {
6713 if (!mLockdownEnabled) {
6714 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006715 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006716 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006717 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6718 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006719
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006720 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006721 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6722 // a local variable. There is no need to make a copy because its contents cannot change.
6723 final Network[] underlying = nai.declaredUnderlyingNetworks;
6724 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006725 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006726 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006727
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006728 // The legacy lockdown VPN always uses the default network.
6729 // If the VPN's underlying network is no longer the current default network, it means that
6730 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006731 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6732 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006733 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006734 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006735 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006736 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006737
6738 return nai;
6739 };
6740
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006741 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6742 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6743 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006744 private DetailedState getLegacyLockdownState(DetailedState origState) {
6745 if (origState != DetailedState.CONNECTED) {
6746 return origState;
6747 }
6748 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6749 ? DetailedState.CONNECTING
6750 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006751 }
6752
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006753 private void filterForLegacyLockdown(NetworkInfo ni) {
6754 if (!mLockdownEnabled || !ni.isConnected()) return;
6755 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6756 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6757 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6758 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6759 // network, this time with a state of CONNECTED.
6760 //
6761 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6762 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6763 // is not too far off the truth, since an always-on VPN, when not connected, is always
6764 // trying to reconnect.
6765 if (getLegacyLockdownNai() == null) {
6766 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6767 }
6768 }
6769
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006770 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006771 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006772 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006773 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006774 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6775 return;
6776 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006777 final long ident = Binder.clearCallingIdentity();
6778 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006779 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006780 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006781 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006782 } finally {
6783 Binder.restoreCallingIdentity(ident);
6784 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006785 }
Wink Savillecb117d32013-08-29 14:57:08 -07006786
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006787 @Override
6788 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006789 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006790 final long ident = Binder.clearCallingIdentity();
6791 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006792 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006793 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006794 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6795 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006796 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006797 } finally {
6798 Binder.restoreCallingIdentity(ident);
6799 }
6800 }
6801
James Mattis02220e22021-03-13 19:27:21 -08006802 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006803 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6804 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6805 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006806 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006807 }
6808
James Mattis02220e22021-03-13 19:27:21 -08006809 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006810 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006811 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006812 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6813 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006814 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006815 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6816 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6817 }
junyulaid91e7052020-08-28 13:44:33 +08006818 }
6819
James Mattis02220e22021-03-13 19:27:21 -08006820 private void onPackageChanged(@NonNull final String packageName) {
6821 // This is necessary in case a package is added or removed, but also when it's replaced to
6822 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6823 // as one in the preferences, then it should follow the same routing as that other package,
6824 // which means updating the rules is never to be needed in this case (whether it joins or
6825 // leaves a UID with a preference).
6826 if (isMappedInOemNetworkPreference(packageName)) {
6827 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6828 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006829
6830 // Invalidates cache entry when the package is updated.
6831 synchronized (mSelfCertifiedCapabilityCache) {
6832 mSelfCertifiedCapabilityCache.remove(packageName);
6833 }
James Mattis02220e22021-03-13 19:27:21 -08006834 }
6835
6836 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006837 @Override
6838 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006839 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006840 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006841 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006842
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006843 // User should be filled for below intents, check the existence.
6844 if (user == null) {
6845 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6846 return;
6847 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006848
Lorenzo Colitticd675292021-02-04 17:32:07 +09006849 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006850 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006851 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006852 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006853 } else {
junyulaid91e7052020-08-28 13:44:33 +08006854 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006855 }
6856 }
6857 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006858
James Mattis02220e22021-03-13 19:27:21 -08006859 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6860 @Override
6861 public void onReceive(Context context, Intent intent) {
6862 ensureRunningOnConnectivityServiceThread();
6863 switch (intent.getAction()) {
6864 case Intent.ACTION_PACKAGE_ADDED:
6865 case Intent.ACTION_PACKAGE_REMOVED:
6866 case Intent.ACTION_PACKAGE_REPLACED:
6867 onPackageChanged(intent.getData().getSchemeSpecificPart());
6868 break;
6869 default:
6870 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6871 }
6872 }
6873 };
6874
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006875 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006876 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006877
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006878 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006879 public final String name;
6880 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006881 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006882 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006883
lifraf3a3492021-03-10 13:58:14 +08006884 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6885 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006886 this.name = name;
6887 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006888 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006889 mDeathRecipient = deathRecipient;
6890
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006891 if (mDeathRecipient == null) {
6892 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006893 }
6894 }
6895
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006896 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006897 try {
6898 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6899 } catch (RemoteException e) {
6900 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006901 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006902 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006903 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006904
James Mattis4fce5d12020-11-12 15:53:42 -08006905 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6906 for (int i = 0; i < requests.size(); i++) {
6907 ensureNetworkRequestHasType(requests.get(i));
6908 }
6909 }
6910
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006911 private void ensureNetworkRequestHasType(NetworkRequest request) {
6912 if (request.type == NetworkRequest.Type.NONE) {
6913 throw new IllegalArgumentException(
6914 "All NetworkRequests in ConnectivityService must have a type");
6915 }
6916 }
6917
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006918 /**
6919 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006920 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006921 */
James Mattis258ea3c2020-11-15 15:04:40 -08006922 @VisibleForTesting
6923 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006924 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6925 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006926 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006927
James Mattisa076c532020-12-02 14:12:41 -08006928 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6929 void setSatisfier(
6930 @Nullable final NetworkAgentInfo satisfier,
6931 @Nullable final NetworkRequest activeRequest) {
6932 mSatisfier = satisfier;
6933 mActiveRequest = activeRequest;
6934 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006935
James Mattisd31bdfa2020-12-23 16:37:26 -08006936 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006937 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006938 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006939 private NetworkAgentInfo mSatisfier;
6940 NetworkAgentInfo getSatisfier() {
6941 return mSatisfier;
6942 }
6943
6944 // The request in mRequests assigned to a network agent. This is null if none of the
6945 // requests in mRequests can be satisfied. This member has the constraint of only being
6946 // accessible on the handler thread.
6947 @Nullable
6948 private NetworkRequest mActiveRequest;
6949 NetworkRequest getActiveRequest() {
6950 return mActiveRequest;
6951 }
6952
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006953 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006954 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006955 @Nullable
6956 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006957
6958 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006959 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006960 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006961 final int mPid;
6962 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006963 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006964 @Nullable
6965 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006966
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006967 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006968 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006969
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006970 // Effective UID of this request. This is different from mUid when a privileged process
6971 // files a request on behalf of another UID. This UID is used to determine blocked status,
6972 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6973 // maximum limit of registered callbacks per UID.
6974 final int mAsUid;
6975
paulhu48291862021-07-14 14:53:57 +08006976 // Preference order of this request.
6977 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006978
James Mattis3ce3d3c2021-02-09 18:18:28 -08006979 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6980 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6981 // maintained for keying off of. This is only a concern when the original nri
6982 // mNetworkRequests changes which happens currently for apps that register callbacks to
6983 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6984 // that match the per-app default nri that currently tracks the calling app's uid so that
6985 // callbacks are fired at the appropriate time. When the callbacks fire,
6986 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6987 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6988 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6989 @NonNull
6990 private final NetworkRequest mNetworkRequestForCallback;
6991 NetworkRequest getNetworkRequestForCallback() {
6992 return mNetworkRequestForCallback;
6993 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006994
James Mattisd31bdfa2020-12-23 16:37:26 -08006995 /**
6996 * Get the list of UIDs this nri applies to.
6997 */
6998 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006999 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08007000 // networkCapabilities.getUids() returns a defensive copy.
7001 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007002 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
7003 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08007004 }
7005
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007006 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
7007 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08007008 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08007009 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007010 }
7011
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007012 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007013 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007014 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007015 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007016 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007017 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007018 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007019 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007020 mBinder = null;
7021 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007022 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007023 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007024 mPerUidCounter = getRequestCounter(this);
7025 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007026 /**
7027 * Location sensitive data not included in pending intent. Only included in
7028 * {@link NetworkCallback}.
7029 */
7030 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007031 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007032 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007033 }
7034
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007035 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007036 @Nullable final IBinder binder,
7037 @NetworkCallback.Flag int callbackFlags,
7038 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007039 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7040 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007041 }
7042
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007043 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007044 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007045 @Nullable final IBinder binder,
7046 @NetworkCallback.Flag int callbackFlags,
7047 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007048 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007049 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007050 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007051 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007052 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007053 mBinder = binder;
7054 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007055 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007056 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007057 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007058 mPerUidCounter = getRequestCounter(this);
7059 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007060 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007061 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007062 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007063 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007064 }
7065
James Mattis3ce3d3c2021-02-09 18:18:28 -08007066 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7067 @NonNull final List<NetworkRequest> r) {
7068 super();
7069 ensureAllNetworkRequestsHaveType(r);
7070 mRequests = initializeRequests(r);
7071 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007072 final NetworkAgentInfo satisfier = nri.getSatisfier();
7073 if (null != satisfier) {
7074 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7075 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007076 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007077 // As this code creates a new NRI with a new set of requests, figure out which of
7078 // the list of requests should be the active request. It is always the first
7079 // request of the list that can be satisfied by the satisfier since the order of
7080 // requests is a priority order.
7081 // Note even in the presence of a satisfier there may not be an active request,
7082 // when the satisfier is the no-service network.
7083 NetworkRequest activeRequest = null;
7084 for (final NetworkRequest candidate : r) {
7085 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7086 activeRequest = candidate;
7087 break;
7088 }
7089 }
7090 setSatisfier(satisfier, activeRequest);
7091 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007092 mMessenger = nri.mMessenger;
7093 mBinder = nri.mBinder;
7094 mPid = nri.mPid;
7095 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007096 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007097 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007098 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007099 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007100 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007101 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007102 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007103 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007104 }
7105
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007106 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007107 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007108 }
7109
paulhue9913722021-05-26 15:19:20 +08007110 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007111 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007112 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007113 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007114 }
7115
James Mattis2516da32021-01-31 17:06:19 -08007116 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7117 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7118 // false.
7119 boolean isBeingSatisfied() {
7120 return (null != mSatisfier && null != mActiveRequest);
7121 }
7122
James Mattis3d229892020-11-16 16:46:28 -08007123 boolean isMultilayerRequest() {
7124 return mRequests.size() > 1;
7125 }
7126
James Mattis45d81842021-01-10 14:24:24 -08007127 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7128 // Creating a defensive copy to prevent the sender from modifying the list being
7129 // reflected in the return value of this method.
7130 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007131 return Collections.unmodifiableList(tempRequests);
7132 }
7133
James Mattisb1392002021-03-31 13:57:52 -07007134 void linkDeathRecipient() {
7135 if (null != mBinder) {
7136 try {
7137 mBinder.linkToDeath(this, 0);
7138 } catch (RemoteException e) {
7139 binderDied();
7140 }
7141 }
7142 }
7143
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007144 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007145 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007146 try {
7147 mBinder.unlinkToDeath(this, 0);
7148 } catch (NoSuchElementException e) {
7149 // Temporary workaround for b/194394697 pending analysis of additional logs
7150 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7151 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007152 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007153 }
7154
paulhu48291862021-07-14 14:53:57 +08007155 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7156 // Compare two preference orders.
7157 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007158 }
7159
paulhu48291862021-07-14 14:53:57 +08007160 int getPreferenceOrderForNetd() {
7161 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7162 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7163 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007164 }
paulhu48291862021-07-14 14:53:57 +08007165 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007166 }
7167
James Mattis4fce5d12020-11-12 15:53:42 -08007168 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007169 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007170 // As an immutable collection, mRequests cannot change by the time the
7171 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7172 // is acceptable. Use handleReleaseNetworkRequest and not directly
7173 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7174 // the app already unregistered the request.
7175 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7176 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007177 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007178
James Mattis4fce5d12020-11-12 15:53:42 -08007179 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007180 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007181 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7182 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007183 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007184 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007185 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007186 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007187 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007188 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007189 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007190 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007191 }
7192
Junyu Lai00d92df2022-07-05 11:01:52 +08007193 // Keep backward compatibility since the ServiceSpecificException is used by
7194 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7195 public static class RequestInfoPerUidCounter extends PerUidCounter {
7196 RequestInfoPerUidCounter(int maxCountPerUid) {
7197 super(maxCountPerUid);
7198 }
7199
7200 @Override
7201 public synchronized void incrementCountOrThrow(int uid) {
7202 try {
7203 super.incrementCountOrThrow(uid);
7204 } catch (IllegalStateException e) {
7205 throw new ServiceSpecificException(
7206 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7207 "Uid " + uid + " exceeded its allotted requests limit");
7208 }
7209 }
7210
7211 @Override
7212 public synchronized void decrementCountOrThrow(int uid) {
7213 throw new UnsupportedOperationException("Use decrementCount instead.");
7214 }
7215
7216 public synchronized void decrementCount(int uid) {
7217 try {
7218 super.decrementCountOrThrow(uid);
7219 } catch (IllegalStateException e) {
7220 logwtf("Exception when decrement per uid request count: ", e);
7221 }
7222 }
7223 }
7224
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007225 // This checks that the passed capabilities either do not request a
7226 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007227 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007228 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007229 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007230 throw new SecurityException("Insufficient permissions to request a specific SSID");
7231 }
paulhu1a407652019-03-22 16:35:06 +08007232
7233 if (nc.hasSignalStrength()
7234 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7235 throw new SecurityException(
7236 "Insufficient permissions to request a specific signal strength");
7237 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007238 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007239
junyulai2217bec2021-04-14 23:33:31 +08007240 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007241 enforceNetworkFactoryPermission();
7242 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007243 }
7244
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007245 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007246 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007247 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007248 // mNetworkRequests may contain the same value multiple times in case of
7249 // multilayer requests. It won't matter in this case because the thresholds
7250 // will then be the same and be deduplicated as they enter the `thresholds` set.
7251 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007252 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7253 for (final NetworkRequest req : nri.mRequests) {
7254 if (req.networkCapabilities.hasSignalStrength()
7255 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7256 thresholds.add(req.networkCapabilities.getSignalStrength());
7257 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007258 }
7259 }
7260 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007261 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007262 }
7263
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007264 private void updateSignalStrengthThresholds(
7265 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007266 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007267
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007268 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007269 String detail;
7270 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7271 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7272 } else {
7273 detail = reason;
7274 }
7275 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007276 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007277 }
7278
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007279 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007280 }
7281
Chalard Jeandd421992021-12-16 23:16:02 +09007282 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007283 if (nc == null) {
7284 return;
7285 }
7286 NetworkSpecifier ns = nc.getNetworkSpecifier();
7287 if (ns == null) {
7288 return;
7289 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007290 if (ns instanceof MatchAllNetworkSpecifier) {
7291 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7292 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007293 }
7294
Chalard Jeandd421992021-12-16 23:16:02 +09007295 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007296 ensureValidNetworkSpecifier(nc);
7297 if (nc.isPrivateDnsBroken()) {
7298 throw new IllegalArgumentException("Can't request broken private DNS");
7299 }
Chalard Jeande665262022-02-25 16:12:12 +09007300 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007301 throw new IllegalArgumentException("Can't request access UIDs");
7302 }
lucasline117e2e2019-10-22 18:27:33 +08007303 }
7304
Chalard Jeandd421992021-12-16 23:16:02 +09007305 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7306 ensureListenableCapabilities(nc);
7307 final String badCapability = nc.describeFirstNonRequestableCapability();
7308 if (badCapability != null) {
7309 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7310 }
7311 }
7312
Chiachang Wang3bc52762021-11-25 14:17:57 +08007313 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7314 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007315 private boolean isTargetSdkAtleast(int version, int callingUid,
7316 @NonNull String callingPackageName) {
7317 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007318 final PackageManager pm =
7319 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007320 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007321 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007322 if (callingVersion < version) return false;
7323 } catch (PackageManager.NameNotFoundException e) { }
7324 return true;
7325 }
7326
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007327 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007328 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007329 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007330 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007331 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007332 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007333 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7334 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007335 throw new SecurityException("Insufficient permissions to specify legacy type");
7336 }
markchienfac84a22020-03-18 21:16:15 +08007337 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007338 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007339 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007340 // Privileged callers can track the default network of another UID by passing in a UID.
7341 if (asUid != Process.INVALID_UID) {
7342 enforceSettingsPermission();
7343 } else {
7344 asUid = callingUid;
7345 }
junyulaiad010792021-01-11 16:53:38 +08007346 final NetworkRequest.Type reqType;
7347 try {
7348 reqType = NetworkRequest.Type.values()[reqTypeInt];
7349 } catch (ArrayIndexOutOfBoundsException e) {
7350 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7351 }
7352 switch (reqType) {
7353 case TRACK_DEFAULT:
7354 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007355 // is unused and will be replaced by ones appropriate for the UID (usually, the
7356 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007357 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007358 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007359 enforceAccessPermission();
7360 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007361 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007362 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007363 networkCapabilities = new NetworkCapabilities(defaultNc);
7364 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007365 case BACKGROUND_REQUEST:
7366 enforceNetworkStackOrSettingsPermission();
7367 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007368 case REQUEST:
7369 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7370 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007371 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007372 // TODO: this is incorrect. We mark the request as metered or not depending on
7373 // the state of the app when the request is filed, but we never change the
7374 // request if the app changes network state. http://b/29964605
7375 enforceMeteredApnPolicy(networkCapabilities);
7376 break;
junyulai1b1c8742021-03-12 20:05:08 +08007377 case LISTEN_FOR_BEST:
7378 enforceAccessPermission();
7379 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7380 break;
junyulaiad010792021-01-11 16:53:38 +08007381 default:
7382 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007383 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007384 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007385 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007386 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007387
junyulai1b1c8742021-03-12 20:05:08 +08007388 // Enforce FOREGROUND if the caller does not have permission to use background network.
7389 if (reqType == LISTEN_FOR_BEST) {
7390 restrictBackgroundRequestForCaller(networkCapabilities);
7391 }
7392
7393 // Set the UID range for this request to the single UID of the requester, unless the
7394 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007395 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7396 // are no visible methods to set the UIDs, an app could use reflection to try and get
7397 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007398 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007399 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7400 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007401
Etan Cohen85000162017-02-05 10:42:27 -08007402 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007403 throw new IllegalArgumentException("Bad timeout specified");
7404 }
Etan Cohen9786d922015-11-18 10:56:15 -08007405
James Mattis3ce3d3c2021-02-09 18:18:28 -08007406 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007407 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007408 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007409 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007410 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007411 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007412
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007413 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7414 // copied from the default request above. (This is necessary to ensure, for example, that
7415 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7416 // changes don't alter request matching.
7417 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7418 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007419 throw new IllegalStateException(
7420 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007421 + networkCapabilities + " vs. " + defaultNc);
7422 }
7423
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007424 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007425 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007426 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007427 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007428 }
7429 return networkRequest;
7430 }
7431
James Mattis3ce3d3c2021-02-09 18:18:28 -08007432 /**
7433 * Return the nri to be used when registering a network request. Specifically, this is used with
7434 * requests registered to track the default request. If there is currently a per-app default
7435 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7436 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007437 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7438 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007439 * @param nr the network request for the nri.
7440 * @param msgr the messenger for the nri.
7441 * @param binder the binder for the nri.
7442 * @param callingAttributionTag the calling attribution tag for the nri.
7443 * @return the nri to register.
7444 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007445 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007446 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007447 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007448 @Nullable String callingAttributionTag) {
7449 final List<NetworkRequest> requests;
7450 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7451 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007452 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007453 } else {
7454 requests = Collections.singletonList(nr);
7455 }
Roshan Pius951c0032020-12-22 15:10:42 -08007456 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007457 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007458 }
7459
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007460 private boolean shouldCheckCapabilitiesDeclaration(
7461 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7462 @NonNull final String callingPackageName) {
7463 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7464 // Only run the check if the change is enabled.
7465 if (!mDeps.isChangeEnabled(
7466 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7467 callingPackageName, user)) {
7468 return false;
7469 }
7470
7471 return networkCapabilities.hasCapability(
7472 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7473 || networkCapabilities.hasCapability(
7474 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7475 }
7476
7477 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
7478 @NonNull final NetworkCapabilities networkCapabilities) {
7479 // This check is added to fix the linter error for "current min is 30", which is not going
7480 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007481 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007482 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7483 return;
7484 }
7485 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007486 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007487 try {
7488 synchronized (mSelfCertifiedCapabilityCache) {
7489 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7490 callerPackageName);
7491 if (applicationNetworkCapabilities == null) {
7492 final PackageManager packageManager = mContext.getPackageManager();
7493 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7494 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7495 callerPackageName
7496 );
7497 final XmlResourceParser parser = packageManager
7498 .getResourcesForApplication(callerPackageName)
7499 .getXml(networkSliceProperty.getResourceId());
7500 applicationNetworkCapabilities =
7501 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7502 mSelfCertifiedCapabilityCache.put(callerPackageName,
7503 applicationNetworkCapabilities);
7504 }
7505
7506 }
7507 } catch (PackageManager.NameNotFoundException ne) {
7508 throw new SecurityException(
7509 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7510 + " property");
7511 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7512 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007513 } finally {
7514 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007515 }
7516
7517 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7518 networkCapabilities);
7519 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007520 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007521 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007522 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7523 callingPackageName)) {
7524 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7525 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007526 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007527 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7528 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7529 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7530 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007531 }
junyulai96bd9fe2022-03-08 17:36:42 +08007532 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007533 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007534 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007535 }
7536 }
7537
fenglu3f357402015-03-20 11:29:56 -07007538 @Override
fenglub00f4882015-04-21 17:12:05 -07007539 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007540 enforceAccessPermission();
7541 NetworkAgentInfo nai = null;
7542 if (network == null) {
7543 return false;
7544 }
7545 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007546 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007547 }
7548 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007549 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007550 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007551 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007552 Integer uidReqs = mBandwidthRequests.get(uid);
7553 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007554 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007555 }
7556 mBandwidthRequests.put(uid, ++uidReqs);
7557 }
fenglu3f357402015-03-20 11:29:56 -07007558 return true;
7559 }
7560 return false;
7561 }
7562
Felipe Leme0a5ae422016-06-20 16:36:29 -07007563 private boolean isSystem(int uid) {
7564 return uid < Process.FIRST_APPLICATION_UID;
7565 }
fenglu3f357402015-03-20 11:29:56 -07007566
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007567 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007568 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007569 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007570 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007571 return;
7572 }
Hugo Benichi39621362017-02-11 17:04:43 +09007573 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7574 // Policy already enforced.
7575 return;
7576 }
paulhuaf50d7d2020-12-24 19:47:34 +08007577 final long ident = Binder.clearCallingIdentity();
7578 try {
7579 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7580 // If UID is restricted, don't allow them to bring up metered APNs.
7581 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7582 }
7583 } finally {
7584 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007585 }
7586 }
7587
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007588 @Override
7589 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007590 PendingIntent operation, @NonNull String callingPackageName,
7591 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007592 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007593 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007594 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007595 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007596 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007597 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007598 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007599 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007600 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007601 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7602 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007603
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007604 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007605 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007606 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7607 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007608 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007609 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7610 nri));
7611 return networkRequest;
7612 }
7613
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007614 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7615 mHandler.sendMessageDelayed(
7616 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007617 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007618 }
7619
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007620 @Override
7621 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007622 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007623 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007624 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007625 }
7626
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007627 // In order to implement the compatibility measure for pre-M apps that call
7628 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7629 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7630 // This ensures it has permission to do so.
7631 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7632 if (nc == null) {
7633 return false;
7634 }
7635 int[] transportTypes = nc.getTransportTypes();
7636 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7637 return false;
7638 }
7639 try {
7640 mContext.enforceCallingOrSelfPermission(
7641 android.Manifest.permission.ACCESS_WIFI_STATE,
7642 "ConnectivityService");
7643 } catch (SecurityException e) {
7644 return false;
7645 }
7646 return true;
7647 }
7648
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007649 @Override
7650 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007651 Messenger messenger, IBinder binder,
7652 @NetworkCallback.Flag int callbackFlags,
7653 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007654 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007655 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7656 enforceAccessPermission();
7657 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007658
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007659 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007660 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007661 Binder.getCallingPid(), callingUid, callingPackageName);
7662 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007663 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7664 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7665 // onLost and onAvailable callbacks when networks move in and out of the background.
7666 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7667 // can't request networks.
7668 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007669 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007670
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007671 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007672 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007673 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007674 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007675 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007676 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007677
7678 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7679 return networkRequest;
7680 }
7681
7682 @Override
7683 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007684 PendingIntent operation, @NonNull String callingPackageName,
7685 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007686 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007687 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007688 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7689 enforceAccessPermission();
7690 }
Chalard Jeandd421992021-12-16 23:16:02 +09007691 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007692 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007693 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007694 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007695 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007696
7697 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007698 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007699 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7700 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007701 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007702
WeiZhang1cc3f172021-06-03 19:02:04 -05007703 mHandler.sendMessage(mHandler.obtainMessage(
7704 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007705 }
7706
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007707 /** Returns the next Network provider ID. */
7708 public final int nextNetworkProviderId() {
7709 return mNextNetworkProviderId.getAndIncrement();
7710 }
7711
Erik Kline0c04b742016-07-07 16:50:58 +09007712 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007713 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007714 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007715 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007716 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007717 }
7718
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007719 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7720 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007721 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7722 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7723 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007724 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007725 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007726 return;
7727 }
7728
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007729 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7730 mNetworkProviderInfos.put(npi.messenger, npi);
7731 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007732 }
7733
7734 @Override
7735 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007736 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007737 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007738 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007739 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007740 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7741 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007742 }
7743
7744 @Override
7745 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007746 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007747 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007748 }
7749
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007750 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007751 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007752 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7753 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007754 Objects.requireNonNull(score);
7755 Objects.requireNonNull(caps);
7756 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007757 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007758 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007759 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7760 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007761 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7762 }
7763
Chalard Jeanbb902a52021-08-18 01:35:19 +09007764 private void updateOfferScore(final NetworkOffer offer) {
7765 final boolean yieldToBadWiFi =
7766 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7767 final NetworkOffer newOffer = new NetworkOffer(
7768 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7769 offer.caps, offer.callback, offer.providerId);
7770 if (offer.equals(newOffer)) return;
7771 handleRegisterNetworkOffer(newOffer);
7772 }
7773
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007774 @Override
7775 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007776 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007777 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7778 }
7779
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007780 private void handleUnregisterNetworkProvider(Messenger messenger) {
7781 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7782 if (npi == null) {
7783 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007784 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007785 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007786 // Unregister all the offers from this provider
7787 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7788 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007789 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007790 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7791 toRemove.add(noi);
7792 }
7793 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007794 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007795 handleUnregisterNetworkOffer(noi);
7796 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007797 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007798 }
7799
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007800 @Override
James Mattisf7027322020-12-13 16:28:14 -08007801 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007802 if (request.hasTransport(TRANSPORT_TEST)) {
7803 enforceNetworkFactoryOrTestNetworksPermission();
7804 } else {
7805 enforceNetworkFactoryPermission();
7806 }
James Mattisf7027322020-12-13 16:28:14 -08007807 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7808 if (nri != null) {
7809 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7810 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7811 mHandler.post(() -> handleReleaseNetworkRequest(
7812 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7813 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007814 }
7815
Paul Jensen1f567382015-02-13 14:18:39 -05007816 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7817 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007818 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007819 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007820 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007821 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007822 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007823
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007824 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007825 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007826 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007827
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007828 // UID ranges for users that are currently blocked by VPNs.
7829 // This array is accessed and iterated on multiple threads without holding locks, so its
7830 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7831 // (on the handler thread).
7832 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7833
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007834 // Must only be accessed on the handler thread
7835 @NonNull
7836 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7837
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007838 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007839 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007840
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007841 // Current OEM network preferences. This object must only be written to on the handler thread.
7842 // Since it is immutable and always non-null, other threads may read it if they only care
7843 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007844 @NonNull
7845 private OemNetworkPreferences mOemNetworkPreferences =
7846 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007847 // Current per-profile network preferences. This object follows the same threading rules as
7848 // the OEM network preferences above.
7849 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007850 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7851 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007852
lucaslin3ba7cc22022-12-19 02:35:33 +00007853 // Current VPN network preferences. This object follows the same threading rules as the OEM
7854 // network preferences above.
7855 @NonNull
7856 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7857 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7858
paulhu51f77dc2021-06-07 02:34:20 +00007859 // A set of UIDs that should use mobile data preferentially if available. This object follows
7860 // the same threading rules as the OEM network preferences above.
7861 @NonNull
7862 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7863
James Mattiscb1e0362021-04-06 17:07:42 -07007864 // OemNetworkPreferences activity String log entries.
7865 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7866 @NonNull
7867 private final LocalLog mOemNetworkPreferencesLogs =
7868 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7869
James Mattis02220e22021-03-13 19:27:21 -08007870 /**
7871 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7872 * @param packageName the package name to check existence of a mapping for.
7873 * @return true if a mapping exists, false otherwise
7874 */
7875 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7876 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7877 }
7878
James Mattise3ef1912020-12-20 11:09:58 -08007879 // The always-on request for an Internet-capable network that apps without a specific default
7880 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007881 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007882 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007883 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007884 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007885 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007886 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007887 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007888
James Mattisd31bdfa2020-12-23 16:37:26 -08007889 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7890 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7891 }
7892
7893 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007894 * Return the default network request currently tracking the given uid.
7895 * @param uid the uid to check.
7896 * @return the NetworkRequestInfo tracking the given uid.
7897 */
7898 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007899 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007900 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007901 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007902 // Checking the first request is sufficient as only multilayer requests will have more
7903 // than one request and for multilayer, all requests will track the same uids.
7904 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007905 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007906 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007907 highestPriorityNri = nri;
7908 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007909 }
7910 }
paulhuaa0743d2021-05-26 21:56:03 +08007911 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007912 }
7913
7914 /**
7915 * Get a copy of the network requests of the default request that is currently tracking the
7916 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007917 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7918 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007919 * @param requestorUid the uid to check the default for.
7920 * @param requestorPackageName the requestor's package name.
7921 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7922 */
7923 @NonNull
7924 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007925 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007926 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007927 getDefaultRequestTrackingUid(asUid).mRequests,
7928 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007929 }
7930
7931 /**
7932 * Copy the given nri's NetworkRequest collection.
7933 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007934 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7935 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007936 * @param requestorUid the uid to set on the copied collection.
7937 * @param requestorPackageName the package name to set on the copied collection.
7938 * @return the copied NetworkRequest collection.
7939 */
7940 @NonNull
7941 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007942 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7943 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007944 final List<NetworkRequest> requests = new ArrayList<>();
7945 for (final NetworkRequest nr : requestsToCopy) {
7946 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007947 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007948 nr.legacyType, nextNetworkRequestId(), nr.type));
7949 }
7950 return requests;
7951 }
7952
7953 @NonNull
7954 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007955 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7956 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007957 // These capabilities are for a TRACK_DEFAULT callback, so:
7958 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7959 // mDefaultRequest and a per-UID default request.
7960 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007961 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007962 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007963 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7964 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007965 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007966 restrictRequestUidsForCallerAndSetRequestorInfo(
7967 netCap, requestorUid, requestorPackageName);
7968 return netCap;
7969 }
7970
7971 /**
7972 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7973 * @param nr the network request to check for equality against.
7974 * @return the nri if one exists, null otherwise.
7975 */
7976 @Nullable
7977 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7978 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7979 if (nri.getNetworkRequestForCallback().equals(nr)) {
7980 return nri;
7981 }
7982 }
7983 return null;
7984 }
7985
7986 /**
7987 * Check if an nri is currently being managed by per-app default networking.
7988 * @param nri the nri to check.
7989 * @return true if this nri is currently being managed by per-app default networking.
7990 */
7991 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7992 // nri.mRequests.get(0) is only different from the original request filed in
7993 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7994 // functionality therefore if these two don't match, it means this particular nri is
7995 // currently being managed by a per-app default.
7996 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7997 }
7998
7999 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008000 * Determine if an nri is a managed default request that disallows default networking.
8001 * @param nri the request to evaluate
8002 * @return true if device-default networking is disallowed
8003 */
8004 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
8005 // Check if this nri is a managed default that supports the default network at its
8006 // lowest priority request.
8007 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
8008 final NetworkCapabilities lowestPriorityNetCap =
8009 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
8010 return isPerAppDefaultRequest(nri)
8011 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8012 lowestPriorityNetCap));
8013 }
8014
Erik Kline05f2b402015-04-30 12:58:40 +09008015 // Request used to optionally keep mobile data active even when higher
8016 // priority networks like Wi-Fi are active.
8017 private final NetworkRequest mDefaultMobileDataRequest;
8018
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008019 // Request used to optionally keep wifi data active even when higher
8020 // priority networks like ethernet are active.
8021 private final NetworkRequest mDefaultWifiRequest;
8022
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008023 // Request used to optionally keep vehicle internal network always active
8024 private final NetworkRequest mDefaultVehicleRequest;
8025
James Mattisd31bdfa2020-12-23 16:37:26 -08008026 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8027 // network with no service. This NAI should never be matched against, nor should any public API
8028 // ever return the associated network. For this reason, this NAI is not in the list of available
8029 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8030 // default requests that don't support using the device default network which will ultimately
8031 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8032 @VisibleForTesting
8033 final NetworkAgentInfo mNoServiceNetwork;
8034
Chalard Jean5b409c72021-02-04 13:12:59 +09008035 // The NetworkAgentInfo currently satisfying the default request, if any.
8036 private NetworkAgentInfo getDefaultNetwork() {
8037 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008038 }
8039
James Mattis2516da32021-01-31 17:06:19 -08008040 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008041 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008042 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8043 // Currently, all network requests will have the same uids therefore checking the first
8044 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008045 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008046 if (null == uids) {
8047 continue;
8048 }
8049 for (final UidRange range : uids) {
8050 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008051 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008052 highestPriorityNri = nri;
8053 }
James Mattis2516da32021-01-31 17:06:19 -08008054 }
8055 }
8056 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008057 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008058 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008059 }
8060
Varun Ananddf569952019-02-06 10:13:38 -08008061 @Nullable
8062 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8063 return nai != null ? nai.network : null;
8064 }
8065
8066 private void ensureRunningOnConnectivityServiceThread() {
8067 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8068 throw new IllegalStateException(
8069 "Not running on ConnectivityService thread: "
8070 + Thread.currentThread().getName());
8071 }
8072 }
8073
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008074 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008075 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8076 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008077 }
8078
Chalard Jean29d06db2018-05-02 21:14:54 +09008079 /**
Chalard Jeane0aaca52023-10-17 13:23:07 +09008080 * Returns whether local agents are supported on this device.
8081 *
8082 * Local agents are supported from U on TVs, and from V on all devices.
8083 */
8084 @VisibleForTesting
8085 public boolean areLocalAgentsSupported() {
8086 final PackageManager pm = mContext.getPackageManager();
8087 // Local agents are supported starting on U on TVs and on V on everything else.
8088 return mDeps.isAtLeastV() || (mDeps.isAtLeastU() && pm.hasSystemFeature(FEATURE_LEANBACK));
8089 }
8090
8091 /**
Chalard Jean29d06db2018-05-02 21:14:54 +09008092 * Register a new agent with ConnectivityService to handle a network.
8093 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008094 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008095 * @param networkInfo the initial info associated with this network. It can be updated later :
8096 * see {@link #updateNetworkInfo}.
8097 * @param linkProperties the initial link properties of this network. They can be updated
8098 * later : see {@link #updateLinkProperties}.
8099 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008100 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008101 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008102 * @param localNetworkConfig config about this local network, or null if not a local network
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008103 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008104 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008105 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008106 */
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008107 public Network registerNetworkAgent(INetworkAgent na,
8108 NetworkInfo networkInfo,
8109 LinkProperties linkProperties,
8110 NetworkCapabilities networkCapabilities,
8111 @NonNull NetworkScore initialScore,
8112 @Nullable LocalNetworkConfig localNetworkConfig,
8113 NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09008114 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008115 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8116 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8117 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008118 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008119 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008120 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008121 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008122 } else {
8123 enforceNetworkFactoryPermission();
8124 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09008125 final boolean hasLocalCap =
8126 networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
8127 if (hasLocalCap && !areLocalAgentsSupported()) {
8128 // Before U, netd doesn't support PHYSICAL_LOCAL networks so this can't work.
8129 throw new IllegalArgumentException("Local agents are not supported in this version");
8130 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008131 final boolean hasLocalNetworkConfig = null != localNetworkConfig;
8132 if (hasLocalCap != hasLocalNetworkConfig) {
8133 throw new IllegalArgumentException(null != localNetworkConfig
8134 ? "Only local network agents can have a LocalNetworkConfig"
8135 : "Local network agents must have a LocalNetworkConfig"
8136 );
8137 }
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008138
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008139 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008140 final long token = Binder.clearCallingIdentity();
8141 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008142 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008143 networkCapabilities, initialScore, networkAgentConfig, localNetworkConfig,
8144 providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008145 } finally {
8146 Binder.restoreCallingIdentity(token);
8147 }
8148 }
8149
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008150 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008151 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008152 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig,
8153 @Nullable LocalNetworkConfig localNetworkConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09008154 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008155
Chalard Jeandbc46952022-02-02 00:14:18 +09008156 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8157 // and mutate them at any time.
8158 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8159 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8160 final LinkProperties lpCopy = new LinkProperties(linkProperties);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008161 // No need to copy |localNetworkConfiguration| as it is immutable.
Chalard Jeandbc46952022-02-02 00:14:18 +09008162
Chalard Jean366c5252022-01-25 18:27:53 +09008163 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008164 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008165 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8166 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008167 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008168 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008169 localNetworkConfig, currentScore, mContext, mTrackerHandler,
8170 new NetworkAgentConfig(networkAgentConfig), this, mNetd, mDnsResolver, providerId,
8171 uid, mLingerDelayMs, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008172
Chalard Jeandbc46952022-02-02 00:14:18 +09008173 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008174 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008175 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008176 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008177 mDeps.getNetworkStack().makeNetworkMonitor(
8178 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008179 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8180 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008181 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008182 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008183 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008184 }
8185
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008186 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008187 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008188 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008189 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008190 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008191 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8192 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8193 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008194
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008195 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008196
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008197 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008198 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008199 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008200 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008201
8202 try {
8203 networkMonitor.start();
8204 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008205 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008206 }
Chalard Jean366c5252022-01-25 18:27:53 +09008207
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008208 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008209 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008210 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008211 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008212 }
8213
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008214 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8215 @NonNull public final NetworkOffer offer;
8216
8217 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8218 this.offer = offer;
8219 }
8220
8221 @Override
8222 public void binderDied() {
8223 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8224 }
8225 }
8226
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008227 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8228 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8229 if (npi.providerId == providerId) return true;
8230 }
8231 return false;
8232 }
8233
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008234 /**
8235 * Register or update a network offer.
8236 * @param newOffer The new offer. If the callback member is the same as an existing
8237 * offer, it is an update of that offer.
8238 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008239 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008240 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8241 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008242 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008243 // This may actually happen if a provider updates its score or registers and then
8244 // immediately unregisters. The offer would still be in the handler queue, but the
8245 // provider would have been removed.
8246 if (DBG) log("Received offer from an unregistered provider");
8247 return;
8248 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008249 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8250 if (null != existingOffer) {
8251 handleUnregisterNetworkOffer(existingOffer);
8252 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008253 if (DBG) {
8254 // handleUnregisterNetworkOffer has already logged the old offer
8255 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8256 }
8257 } else {
8258 if (DBG) {
8259 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8260 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008261 }
8262 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8263 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008264 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008265 } catch (RemoteException e) {
8266 noi.binderDied();
8267 return;
8268 }
8269 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008270 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008271 }
8272
8273 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8274 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008275 if (DBG) {
8276 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8277 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008278
8279 // If the provider removes the offer and dies immediately afterwards this
8280 // function may be called twice in a row, but the array will no longer contain
8281 // the offer.
8282 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008283 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008284 }
8285
8286 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8287 @NonNull final INetworkOfferCallback callback) {
8288 ensureRunningOnConnectivityServiceThread();
8289 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008290 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008291 }
8292 return null;
8293 }
8294
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008295 /**
8296 * Called when receiving LinkProperties directly from a NetworkAgent.
8297 * Stores into |nai| any data coming from the agent that might also be written to the network's
8298 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8299 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008300 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008301 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008302 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8303 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008304 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008305 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008306 }
8307
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008308 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008309 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008310 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008311
Lorenzo Colittid523d142020-04-01 20:16:30 +09008312 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8313 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8314 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008315 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008316
Suprabh Shukla1e312032023-01-24 03:36:37 -08008317 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008318
8319 // update filtering rules, need to happen after the interface update so netd knows about the
8320 // new interface (the interface name -> index map becomes initialized)
8321 updateVpnFiltering(newLp, oldLp, networkAgent);
8322
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008323 updateMtu(newLp, oldLp);
8324 // TODO - figure out what to do for clat
8325// for (LinkProperties lp : newLp.getStackedLinks()) {
8326// updateMtu(lp, null);
8327// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008328 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008329 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008330 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8331 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008332
Erik Klineb9888902016-04-05 13:30:49 +09008333 updateRoutes(newLp, oldLp, netId);
8334 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008335 // Make sure LinkProperties represents the latest private DNS status.
8336 // This does not need to be done before updateDnses because the
8337 // LinkProperties are not the source of the private DNS configuration.
8338 // updateDnses will fetch the private DNS configuration from DnsManager.
8339 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008340
Chalard Jean5b409c72021-02-04 13:12:59 +09008341 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008342 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008343 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008344 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008345 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008346
8347 updateWakeOnLan(newLp);
8348
Hai Shalome58bdc62021-01-11 18:45:34 -08008349 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8350 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8351 // does, it needs to be merged here.
8352 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8353 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008354
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008355 // TODO - move this check to cover the whole function
8356 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008357 synchronized (networkAgent) {
8358 networkAgent.linkProperties = newLp;
8359 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008360 // Start or stop DNS64 detection and 464xlat according to network state.
8361 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008362 // Notify NSS when relevant events happened. Currently, NSS only cares about
8363 // interface changed to update clat interfaces accounting.
8364 final boolean interfacesChanged = oldLp == null
8365 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8366 if (interfacesChanged) {
8367 notifyIfacesChangedForNetworkStats();
8368 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008369 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8370 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008371 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008372 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008373
8374 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008375 }
8376
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008377 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8378 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8379 }
8380
Hai Shalome58bdc62021-01-11 18:45:34 -08008381 /**
8382 * @param naData captive portal data from NetworkAgent
8383 * @param apiData captive portal data from capport API
8384 */
8385 @Nullable
8386 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8387 CaptivePortalData apiData) {
8388 if (naData == null || apiData == null) {
8389 return naData == null ? apiData : naData;
8390 }
8391 final CaptivePortalData.Builder captivePortalBuilder =
8392 new CaptivePortalData.Builder(naData);
8393
8394 if (apiData.isCaptive()) {
8395 captivePortalBuilder.setCaptive(true);
8396 }
8397 if (apiData.isSessionExtendable()) {
8398 captivePortalBuilder.setSessionExtendable(true);
8399 }
8400 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8401 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8402 // otherwise data would be inconsistent. Prefer the capport API info if present,
8403 // as it can generally be refreshed more often.
8404 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8405 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8406 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8407 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8408 // No source has time / bytes remaining information: surface the newest refresh time
8409 // for other fields
8410 captivePortalBuilder.setRefreshTime(
8411 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8412 }
8413
Hai Shalom7c6ab402021-02-04 19:34:06 -08008414 // Prioritize the user portal URL from the network agent if the source is authenticated.
8415 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8416 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8417 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8418 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008419 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008420 // Prioritize the venue information URL from the network agent if the source is
8421 // authenticated.
8422 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8423 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8424 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8425 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008426 }
8427 return captivePortalBuilder.build();
8428 }
8429
Suprabh Shukla53e16392023-04-26 18:47:36 -07008430 @VisibleForTesting
8431 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008432 // This needs to be kept in sync and backwards compatible with the decoding logic in
8433 // NetdEventListenerService, which is non-mainline code.
8434 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8435 }
8436
Suprabh Shukla75642282023-04-25 23:15:43 -07008437 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8438 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8439 return true;
8440 }
8441 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8442 return true;
8443 }
8444 return false;
8445 }
8446
Suprabh Shukla1e312032023-01-24 03:36:37 -08008447 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008448 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008449 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008450 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008451 return;
8452 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008453
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008454 // Mask/mark of zero will not detect anything interesting.
8455 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008456 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008457 return;
8458 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008459
Suprabh Shukla1e312032023-01-24 03:36:37 -08008460 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008461 try {
8462 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008463 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008464 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008465 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008466 }
8467 } catch (Exception e) {
8468 loge("Exception modifying wakeup packet monitoring: " + e);
8469 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008470 }
8471
Junyu Lai970963e2022-10-25 15:46:47 +08008472 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008473 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008474 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008475 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008476 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008477 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008478 for (final String iface : interfaceDiff.added) {
8479 try {
8480 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008481 mNetd.networkAddInterface(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008482 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008483 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008484 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008485 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008486 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008487 }
Paul Jensenbff73492014-04-28 10:33:11 -04008488 }
8489 }
Chalard Jean9589e722019-11-19 19:03:53 +09008490 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008491 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008492 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008493 wakeupModifyInterface(iface, nai, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008494 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008495 } catch (Exception e) {
8496 loge("Exception removing interface: " + e);
8497 }
8498 }
8499 }
8500
Tyler Weare4314862019-12-05 14:55:30 -08008501 // TODO: move to frameworks/libs/net.
8502 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
8503 final String nextHop;
8504
8505 switch (route.getType()) {
8506 case RouteInfo.RTN_UNICAST:
8507 if (route.hasGateway()) {
8508 nextHop = route.getGateway().getHostAddress();
8509 } else {
8510 nextHop = INetd.NEXTHOP_NONE;
8511 }
8512 break;
8513 case RouteInfo.RTN_UNREACHABLE:
8514 nextHop = INetd.NEXTHOP_UNREACHABLE;
8515 break;
8516 case RouteInfo.RTN_THROW:
8517 nextHop = INetd.NEXTHOP_THROW;
8518 break;
8519 default:
8520 nextHop = INetd.NEXTHOP_NONE;
8521 break;
8522 }
8523
8524 final RouteInfoParcel rip = new RouteInfoParcel();
8525 rip.ifName = route.getInterface();
8526 rip.destination = route.getDestination().toString();
8527 rip.nextHop = nextHop;
8528 rip.mtu = route.getMtu();
8529
8530 return rip;
8531 }
8532
Paul Jensene0fd4a82014-08-06 15:51:33 -04008533 /**
8534 * Have netd update routes from oldLp to newLp.
8535 * @return true if routes changed between oldLp and newLp
8536 */
Junyu Lai970963e2022-10-25 15:46:47 +08008537 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8538 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008539 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008540 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8541 new CompareOrUpdateResult<>(
8542 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008543 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008544 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008545
8546 // add routes before removing old in case it helps with continuous connectivity
8547
Chalard Jean9dd11612018-06-04 16:52:49 +09008548 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008549 for (RouteInfo route : routeDiff.added) {
8550 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008551 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008552 try {
Tyler Weare4314862019-12-05 14:55:30 -08008553 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008554 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008555 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008556 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008557 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008558 }
8559 }
8560 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008561 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008562 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008563 try {
Tyler Weare4314862019-12-05 14:55:30 -08008564 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008565 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008566 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008567 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008568 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008569 }
8570 }
8571
8572 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008573 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008574 try {
Tyler Weare4314862019-12-05 14:55:30 -08008575 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008576 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08008577 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008578 }
8579 }
Tyler Weare4314862019-12-05 14:55:30 -08008580
8581 for (RouteInfo route : routeDiff.updated) {
8582 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8583 try {
8584 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
8585 } catch (Exception e) {
8586 loge("Exception in networkUpdateRouteParcel: " + e);
8587 }
8588 }
8589 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8590 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008591 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008592
Junyu Lai970963e2022-10-25 15:46:47 +08008593 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8594 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008595 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8596 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008597 }
Erik Klineb9888902016-04-05 13:30:49 +09008598
Erik Kline31b4a9e2018-01-11 21:07:29 +09008599 if (DBG) {
8600 final Collection<InetAddress> dnses = newLp.getDnsServers();
8601 log("Setting DNS servers for network " + netId + " to " + dnses);
8602 }
Erik Klineb9888902016-04-05 13:30:49 +09008603 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008604 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008605 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008606 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008607 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008608 }
Erik Kline54e35c02017-04-07 15:29:29 +09008609 }
8610
Junyu Lai970963e2022-10-25 15:46:47 +08008611 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8612 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008613 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8614 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008615 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8616 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008617
8618 if (!wasFiltering && !needsFiltering) {
8619 // Nothing to do.
8620 return;
8621 }
8622
8623 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8624 // Nothing changed.
8625 return;
8626 }
8627
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008628 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008629 if (ranges == null || ranges.isEmpty()) {
8630 return;
8631 }
8632
Qingxi Libb8da982020-01-17 17:54:27 -08008633 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008634 // TODO: this create a window of opportunity for apps to receive traffic between the time
8635 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008636 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008637 // old rules are being removed.
8638 if (wasFiltering) {
8639 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8640 }
8641 if (needsFiltering) {
8642 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8643 }
8644 }
8645
Valentin Iftime9fa35092019-09-24 13:32:13 +02008646 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008647 if (mWolSupportedInterfaces == null) {
8648 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008649 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008650 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008651 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8652 }
8653
Luke Huangb913c812018-08-24 20:33:16 +08008654 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008655 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008656 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008657 }
8658 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008659 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008660 }
Luke Huangb913c812018-08-24 20:33:16 +08008661 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008662 }
8663
Chalard Jean62edfd82019-12-02 18:39:29 +09008664 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8665 @NonNull final NetworkCapabilities newNc) {
8666 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8667 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008668 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008669 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008670 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008671 } catch (RemoteException | ServiceSpecificException e) {
8672 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008673 }
8674 }
8675 }
8676
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008677 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008678 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008679 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008680 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008681 underlyingNetworks = underlyingNetworksOrDefault(
8682 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008683 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008684 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8685 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008686 // metered if any underlying is metered, or originally declared metered by the agent.
8687 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008688 boolean roaming = false; // roaming if any underlying is roaming
8689 boolean congested = false; // congested if any underlying is congested
8690 boolean suspended = true; // suspended if all underlying are suspended
8691
8692 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008693 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008694 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008695 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008696 for (Network underlyingNetwork : underlyingNetworks) {
8697 final NetworkAgentInfo underlying =
8698 getNetworkAgentInfoForNetwork(underlyingNetwork);
8699 if (underlying == null) continue;
8700
8701 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8702 hadUnderlyingNetworks = true;
8703 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008704 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008705 }
8706
8707 // Merge capabilities of this underlying network. For bandwidth, assume the
8708 // worst case.
8709 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8710 underlyingCaps.getLinkDownstreamBandwidthKbps());
8711 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8712 underlyingCaps.getLinkUpstreamBandwidthKbps());
8713 // If this underlying network is metered, the VPN is metered (it may cost money
8714 // to send packets on this network).
8715 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8716 // If this underlying network is roaming, the VPN is roaming (the billing structure
8717 // is different than the usual, local one).
8718 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8719 // If this underlying network is congested, the VPN is congested (the current
8720 // condition of the network affects the performance of this network).
8721 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8722 // If this network is not suspended, the VPN is not suspended (the VPN
8723 // is able to transfer some data).
8724 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008725 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008726 }
8727 }
8728 if (!hadUnderlyingNetworks) {
8729 // No idea what the underlying networks are; assume reasonable defaults
8730 metered = true;
8731 roaming = false;
8732 congested = false;
8733 suspended = false;
8734 }
8735
Chalard Jean1d420b32022-10-12 16:39:37 +09008736 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008737 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8738 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8739 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8740 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8741 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8742 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008743 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008744 }
8745
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008746 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008747 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8748 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8749 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008750 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008751 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008752 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008753 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008754 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8755 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008756 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008757 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008758 if (nai.everConnected()
8759 && !nai.isVPN()
8760 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008761 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008762 // does not cause any request (that is not a listen) currently matching that agent to
8763 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008764 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008765 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008766 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008767 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008768 }
8769
Paul Jensen53f08952015-06-16 14:27:36 -04008770 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008771 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008772 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008773 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008774 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008775 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008776 }
Chalard Jean254bd162022-08-25 13:04:51 +09008777 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008778 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008779 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008780 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008781 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008782 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008783 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008784 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008785 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008786 }
Chalard Jean254bd162022-08-25 13:04:51 +09008787 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008788 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8789 } else {
8790 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8791 }
lucasline117e2e2019-10-22 18:27:33 +08008792 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008793
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008794 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008795 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8796 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008797 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008798 }
8799
Lorenzo Colittibd079452021-07-02 11:47:57 +09008800 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008801 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008802 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008803 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008804 }
8805
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008806 return newNc;
8807 }
8808
Lorenzo Colitti44840702021-01-11 22:27:57 +09008809 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8810 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8811 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8812 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8813 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8814 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8815 if (prevSuspended != suspended) {
8816 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8817 // onResumed have been removed.
8818 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8819 : ConnectivityManager.CALLBACK_RESUMED);
8820 }
8821 if (prevSuspended != suspended || prevRoaming != roaming) {
8822 // updateNetworkInfo will mix in the suspended info from the capabilities and
8823 // take appropriate action for the network having possibly changed state.
8824 updateNetworkInfo(nai, nai.networkInfo);
8825 }
8826 }
8827
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008828 /**
8829 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8830 *
8831 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8832 * capabilities we manage and store in {@code nai}, such as validated status and captive
8833 * portal status)
8834 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8835 * potentially triggers rematches.
8836 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8837 * change.)
8838 *
8839 * @param oldScore score of the network before any of the changes that prompted us
8840 * to call this function.
8841 * @param nai the network having its capabilities updated.
8842 * @param nc the new network capabilities.
8843 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008844 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008845 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008846 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008847 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008848 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8849 if (null != differences) {
8850 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8851 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008852 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008853 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008854
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008855 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008856 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008857 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008858
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008859 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008860 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8861 // the change we're processing can't affect any requests, it can only affect the listens
8862 // on this network. We might have been called by rematchNetworkAndRequests when a
8863 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008864 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008865 } else {
8866 // If the requestable capabilities have changed or the score changed, we can't have been
8867 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008868 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008869 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008870 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008871 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008872
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008873 final boolean oldMetered = prevNc.isMetered();
8874 final boolean newMetered = newNc.isMetered();
8875 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008876
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008877 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008878 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8879 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008880 }
junyulaif2c67e42018-08-07 19:50:45 +08008881
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008882 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8883 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008884
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008885 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008886 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008887 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008888 }
8889
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008890 // This network might have been underlying another network. Propagate its capabilities.
8891 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008892
8893 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008894 mDnsManager.updateTransportsForNetwork(
8895 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008896 }
lucaslin53e8a262021-06-08 01:43:59 +08008897
8898 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008899 }
8900
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008901 /** Convenience method to update the capabilities for a given network. */
8902 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008903 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008904 }
8905
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008906 private void updateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
8907 @NonNull final LocalNetworkConfig config) {
8908 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK)) {
8909 Log.wtf(TAG, "Ignoring update of a local network info on non-local network " + nai);
8910 return;
8911 }
8912 // TODO : actually apply the diff.
8913 nai.localNetworkConfig = config;
8914 }
8915
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008916 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008917 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008918 *
8919 * Ingress interface filtering enforces that all apps under the given network can only receive
8920 * packets from the network's interface (and loopback). This is important for VPNs because
8921 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8922 * non-VPN interfaces.
8923 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008924 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008925 * 1. the network is an app VPN (not legacy VPN)
8926 * 2. the VPN does not allow bypass
8927 * 3. the VPN is fully-routed
8928 * 4. the VPN interface is non-null
8929 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008930 * @see INetd#firewallAddUidInterfaceRules
8931 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008932 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008933 @Nullable
8934 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008935 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008936 if (nc == null || lp == null) return null;
8937 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008938 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008939 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008940 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008941 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008942 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008943 && !lp.hasExcludeRoute()) {
8944 return lp.getInterfaceName();
8945 }
8946 return null;
8947 }
8948
8949 /**
8950 * Returns whether we need to set interface filtering rule or not
8951 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008952 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008953 String isolationIface) {
8954 // Allow rules are always needed if VPN isolation is enabled.
8955 if (isolationIface != null) return true;
8956
8957 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8958 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8959 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09008960 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008961 }
8962
Chiachang Wang28afaff2020-12-10 22:24:47 +08008963 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8964 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8965 int index = 0;
8966 for (UidRange range : ranges) {
8967 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8968 index++;
8969 }
8970 return stableRanges;
8971 }
8972
Chalard Jeane6c95272022-01-25 21:04:21 +09008973 private static UidRangeParcel[] intsToUidRangeStableParcels(
8974 final @NonNull ArraySet<Integer> uids) {
8975 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8976 int index = 0;
8977 for (int uid : uids) {
8978 stableRanges[index] = new UidRangeParcel(uid, uid);
8979 index++;
8980 }
8981 return stableRanges;
8982 }
8983
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008984 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8985 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8986 for (int i = 0; i < ranges.length; i++) {
8987 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8988 }
8989 return stableRanges;
8990 }
8991
Motomu Utsumi93a22182023-03-16 17:04:21 +09008992 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09008993 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08008994 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8995 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09008996 if (mDeps.isAtLeastU()) {
8997 final Set<Integer> exemptUidSet = new ArraySet<>();
8998 for (final int uid: exemptUids) {
8999 exemptUidSet.add(uid);
9000 }
9001 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
9002 } else {
9003 mNetd.socketDestroy(uidRangeParcels, exemptUids);
9004 }
Ken Chen5e65a852020-12-24 12:59:10 +08009005 } catch (Exception e) {
9006 loge("Exception in socket destroy: ", e);
9007 }
9008 }
9009 }
9010
paulhuaa0743d2021-05-26 21:56:03 +08009011 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009012 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08009013 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
9014 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
9015 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09009016 exemptUids[0] = VPN_UID;
9017 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08009018 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
9019
Motomu Utsumi6345e462023-03-13 13:24:50 +09009020 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009021 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009022 try {
9023 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08009024 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009025 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009026 } else {
paulhu0e79d952021-06-09 16:11:35 +08009027 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009028 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009029 }
9030 } catch (Exception e) {
9031 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
9032 " on netId " + nai.network.netId + ". " + e);
9033 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09009034 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009035 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009036 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009037
lucaslin53e8a262021-06-08 01:43:59 +08009038 private boolean isProxySetOnAnyDefaultNetwork() {
9039 ensureRunningOnConnectivityServiceThread();
9040 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9041 final NetworkAgentInfo nai = nri.getSatisfier();
9042 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9043 return true;
9044 }
9045 }
9046 return false;
9047 }
9048
9049 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9050 NetworkCapabilities newNc) {
9051 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9052 // the proxy might be changed since the default network satisfied by the apps might also
9053 // changed.
9054 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9055 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009056 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9057 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009058 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009059 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9060 mProxyTracker.sendProxyBroadcast();
9061 }
9062 }
9063
Chalard Jeane6c95272022-01-25 21:04:21 +09009064 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9065 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009066 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9067 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009068 if (null == prevRanges) prevRanges = new ArraySet<>();
9069 if (null == newRanges) newRanges = new ArraySet<>();
9070 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9071
9072 prevRanges.removeAll(newRanges);
9073 newRanges.removeAll(prevRangesCopy);
9074
9075 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009076 // When updating the VPN uid routing rules, add the new range first then remove the old
9077 // range. If old range were removed first, there would be a window between the old
9078 // range being removed and the new range being added, during which UIDs contained
9079 // in both ranges are not subject to any VPN routing rules. Adding new range before
9080 // removing old range works because, unlike the filtering rules below, it's possible to
9081 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009082 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9083 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9084 // [1-5] & [1-2],[4-5] == [3]
9085 // Then we can do:
9086 // maybeCloseSockets([3])
9087 // mNetd.networkAddUidRanges([1-2],[4-5])
9088 // mNetd.networkRemoveUidRanges([1-5])
9089 // maybeCloseSockets([3])
9090 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9091 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009092 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009093 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009094 }
9095 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009096 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009097 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009098 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9099 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009100 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9101 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009102 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009103 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009104 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9105 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9106 // were added first and then newRanges got removed later, there would be only one uid
9107 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9108 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9109 // Note that this is in contrast with the (more robust) update of VPN routing rules
9110 // above, where the addition of new ranges happens before the removal of old ranges.
9111 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9112 // to be removed will never overlap with the new range to be added.
9113 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009114 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9115 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009116 }
9117 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009118 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009119 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009120 } catch (Exception e) {
9121 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009122 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009123 }
9124 }
9125
Chalard Jeande665262022-02-25 16:12:12 +09009126 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009127 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9128 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009129 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9130 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009131 if (prevEmpty && newEmpty) return;
9132
9133 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009134 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009135 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009136 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009137
9138 if (prevUids.equals(newUids)) return;
9139
9140 // This implementation is very simple and vastly faster for sets of Integers than
9141 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9142 // a key computed from the value and has storage for that.
9143 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9144 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9145 toRemove.removeAll(newUids);
9146 toAdd.removeAll(prevUids);
9147
9148 try {
9149 if (!toAdd.isEmpty()) {
9150 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9151 nai.network.netId,
9152 intsToUidRangeStableParcels(toAdd),
9153 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9154 }
9155 if (!toRemove.isEmpty()) {
9156 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9157 nai.network.netId,
9158 intsToUidRangeStableParcels(toRemove),
9159 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9160 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009161 } catch (ServiceSpecificException e) {
9162 // Has the interface disappeared since the network was built ?
9163 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009164 } catch (RemoteException e) {
9165 // Netd died. This usually causes a runtime restart anyway.
9166 }
9167 }
9168
Junyu Lai2ed7d412022-10-07 16:52:21 +08009169 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9170 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009171 ensureRunningOnConnectivityServiceThread();
9172
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009173 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009174 // Ignore updates for disconnected networks
9175 return;
9176 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009177 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009178 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009179 + "; created=" + nai.getCreatedTime()
9180 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009181 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009182 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9183 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009184 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009185 }
9186
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009187 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9188 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009189 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009190 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009191 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009192 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9193 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9194 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009195 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9196 // need to be sent as a separate extra.
9197 final NetworkRequest req = nri.isMultilayerRequest()
9198 ? nri.getActiveRequest()
9199 // Non-multilayer listen requests do not have an active request
9200 : nri.mRequests.get(0);
9201 if (req == null) {
9202 Log.wtf(TAG, "No request in NRI " + nri);
9203 }
9204 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009205 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009206 sendIntent(nri.mPendingIntent, intent);
9207 }
9208 // else not handled
9209 }
9210
Michael Groover73f69482023-01-27 11:01:25 -06009211 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9212 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009213 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9214 mPendingIntentWakeLock.acquire();
9215 try {
9216 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009217 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009218 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009219 // Explicitly disallow the receiver from starting activities, to prevent apps from
9220 // utilizing the PendingIntent as a backdoor to do this.
9221 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9222 }
9223 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9224 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009225 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009226 } catch (PendingIntent.CanceledException e) {
9227 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9228 mPendingIntentWakeLock.release();
9229 releasePendingNetworkRequest(pendingIntent);
9230 }
9231 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9232 }
9233
9234 @Override
9235 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9236 String resultData, Bundle resultExtras) {
9237 if (DBG) log("Finished sending " + pendingIntent);
9238 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009239 // Release with a delay so the receiving client has an opportunity to put in its
9240 // own request.
9241 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009242 }
9243
Chalard Jean46bfbf02022-02-02 00:56:25 +09009244 // networkAgent is only allowed to be null if notificationType is
9245 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9246 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009247 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009248 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009249 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009250 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009251 // Default request has no msgr. Also prevents callbacks from being invoked for
9252 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9253 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9254 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009255 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09009256 final Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009257 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009258 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009259 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009260 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009261 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009262 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9263 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009264 }
Roshan Pius951c0032020-12-22 15:10:42 -08009265 final boolean includeLocationSensitiveInfo =
9266 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009267 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009268 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009269 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009270 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009271 networkCapabilitiesRestrictedForCallerPermissions(
9272 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9273 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009274 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009275 nri.mCallingAttributionTag);
9276 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009277 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9278 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08009279 // For this notification, arg1 contains the blocked status.
9280 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009281 break;
9282 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009283 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009284 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009285 break;
9286 }
9287 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009288 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009289 final NetworkCapabilities netCap =
9290 networkCapabilitiesRestrictedForCallerPermissions(
9291 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9292 putParcelable(
9293 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009294 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009295 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009296 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009297 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009298 break;
9299 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009300 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009301 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9302 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009303 break;
9304 }
junyulaif2c67e42018-08-07 19:50:45 +08009305 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009306 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009307 msg.arg1 = arg1;
9308 break;
9309 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009310 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009311 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009312 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009313 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009314 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009315 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009316 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009317 }
James Mattis45d81842021-01-10 14:24:24 -08009318 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009319 } catch (RemoteException e) {
9320 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009321 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009322 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009323 }
9324
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009325 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9326 bundle.putParcelable(t.getClass().getSimpleName(), t);
9327 }
9328
Chalard Jean0702f982021-09-16 21:50:07 +09009329 /**
9330 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9331 *
9332 * When a request should be assigned to a new network, it is normally lingered to give
9333 * time for apps to gracefully migrate their connections. When both networks are on the same
9334 * radio, but that radio can't do time-sharing efficiently, this may end up being
9335 * counter-productive because any traffic on the old network may drastically reduce the
9336 * performance of the new network.
9337 * The stack supports a configuration to let modem vendors state that their radio can't
9338 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9339 * from one cell network to another can't be done gracefully.
9340 *
9341 * @param oldNai the old network serving the request
9342 * @param newNai the new network serving the request
9343 * @return whether the switch can be graceful
9344 */
9345 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9346 @NonNull final NetworkAgentInfo newSatisfier) {
9347 if (mCellularRadioTimesharingCapable) return true;
9348 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9349 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9350 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9351 }
9352
Paul Jensenaf94b982014-09-30 15:37:41 -04009353 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009354 if (nai.numRequestNetworkRequests() != 0) {
9355 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9356 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009357 // Ignore listening and track default requests.
9358 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009359 loge("Dead network still had at least " + nr);
9360 break;
9361 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009362 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009363 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009364 }
9365
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009366 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9367 if (oldNetwork == null) {
9368 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9369 return;
9370 }
Chalard Jean49707572019-12-10 21:07:02 +09009371 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009372
9373 // If we get here it means that the last linger timeout for this network expired. So there
9374 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009375 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009376
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009377 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009378 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009379 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009380 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009381 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009382 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009383 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009384 }
9385
James Mattise3ef1912020-12-20 11:09:58 -08009386 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9387 boolean isDefaultChanged = false;
9388 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9389 final NetworkReassignment.RequestReassignment reassignment =
9390 changes.getReassignment(defaultRequestInfo);
9391 if (null == reassignment) {
9392 continue;
9393 }
9394 // reassignment only contains those instances where the satisfying network changed.
9395 isDefaultChanged = true;
9396 // Notify system services of the new default.
9397 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9398 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009399
James Mattise3ef1912020-12-20 11:09:58 -08009400 if (isDefaultChanged) {
9401 // Hold a wakelock for a short time to help apps in migrating to a new default.
9402 scheduleReleaseNetworkTransitionWakelock();
9403 }
9404 }
9405
Aaron Huang9fe47be2021-06-08 13:11:45 +08009406 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9407 if (null == oldDefaultNetwork) return;
9408 // The network stopped being the default. If it was using a PAC proxy, then the
9409 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9410 // to the local proxy server, which would forward them over the newly default network.
9411 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9412 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9413 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9414 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9415 }
9416
James Mattise3ef1912020-12-20 11:09:58 -08009417 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9418 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9419 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9420 if (DBG) {
9421 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9422 }
Chalard Jean8e382112019-12-03 20:45:30 +09009423
James Mattisd31bdfa2020-12-23 16:37:26 -08009424 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9425 if (newDefaultNetwork != null) {
9426 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009427 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009428
James Mattisd31bdfa2020-12-23 16:37:26 -08009429 // Set an app level managed default and return since further processing only applies to the
9430 // default network.
9431 if (mDefaultRequest != nri) {
9432 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9433 return;
9434 }
9435
9436 makeDefaultNetwork(newDefaultNetwork);
9437
James Mattise3ef1912020-12-20 11:09:58 -08009438 if (oldDefaultNetwork != null) {
9439 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9440 }
9441 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009442 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009443 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009444 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009445 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009446 updateTcpBufferSizes(null != newDefaultNetwork
9447 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009448 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009449 }
9450
James Mattisd31bdfa2020-12-23 16:37:26 -08009451 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9452 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9453 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9454 try {
9455 if (VDBG) {
9456 log("Setting default network for " + nri
9457 + " using UIDs " + nri.getUids()
9458 + " with old network " + (oldDefaultNetwork != null
9459 ? oldDefaultNetwork.network().getNetId() : "null")
9460 + " and new network " + (newDefaultNetwork != null
9461 ? newDefaultNetwork.network().getNetId() : "null"));
9462 }
9463 if (nri.getUids().isEmpty()) {
9464 throw new IllegalStateException("makeDefaultForApps called without specifying"
9465 + " any applications to set as the default." + nri);
9466 }
9467 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009468 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009469 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009470 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009471 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009472 }
9473 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009474 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009475 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009476 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009477 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009478 }
9479 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009480 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009481 }
9482 }
9483
Junyu Lai35665cc2022-12-19 17:37:48 +08009484 /**
9485 * Collect restricted uid ranges for the given network and UserHandle, these uids
9486 * are not restricted for matched enterprise networks but being restricted for non-matched
9487 * enterprise networks and non-enterprise networks.
9488 */
9489 @NonNull
9490 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9491 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9492 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9493 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9494 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9495
9496 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9497 // The NC is built from a `ProfileNetworkPreference` which has only one
9498 // enterprise ID, so it's guaranteed to have exactly one.
9499 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9500 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9501 continue;
9502 }
9503 }
9504
9505 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9506 pref.capabilities.getUidRanges())) {
9507 throw new IllegalArgumentException(
9508 "Overlapping uid range in preference: " + pref);
9509 }
9510 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9511 }
9512 return restrictedUidRanges;
9513 }
9514
9515 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009516 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +09009517 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009518
Junyu Lai35665cc2022-12-19 17:37:48 +08009519 ensureRunningOnConnectivityServiceThread();
9520 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9521 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9522 .getUserHandles(true /* excludeDying */);
9523 if (users.isEmpty()) {
9524 throw new IllegalStateException("No user is available");
9525 }
9526
9527 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9528 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9529 for (final UserHandle user : users) {
9530 final ArraySet<UidRange> restrictedUidRanges =
9531 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9532 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9533 UidRange.createForUser(user), restrictedUidRanges));
9534 }
9535
9536 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9537 configs.add(new NativeUidRangeConfig(
9538 nai.network.netId, rangesParcel, 0 /* subPriority */));
9539 }
9540
9541 // The netd API replaces the previous configs with the current configs.
9542 // Thus, for network disconnection or preference removal, no need to
9543 // unset previous config. Instead, collecting all currently needed
9544 // configs and issue to netd.
9545 try {
9546 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9547 } catch (ServiceSpecificException e) {
9548 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009549 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009550 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009551 // Netd died. This will cause a runtime restart anyway.
9552 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009553 }
9554 }
9555
James Mattisd31bdfa2020-12-23 16:37:26 -08009556 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9557 try {
9558 if (null != newDefaultNetwork) {
9559 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9560 } else {
9561 mNetd.networkClearDefault();
9562 }
9563 } catch (RemoteException | ServiceSpecificException e) {
9564 loge("Exception setting default network :" + e);
9565 }
9566 }
9567
Chalard Jean05cbe972019-12-09 11:50:38 +09009568 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009569 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009570 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009571 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009572 processNewlySatisfiedListenRequests(nai);
9573 }
9574
9575 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009576 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9577 if (nri.isMultilayerRequest()) {
9578 continue;
9579 }
9580 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009581 if (!nr.isListen()) continue;
9582 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009583 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009584 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9585 }
9586 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009587 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009588
Chalard Jeancd397a22019-11-22 22:33:33 +09009589 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009590 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9591 if (nri.isMultilayerRequest()) {
9592 continue;
9593 }
9594 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009595 if (!nr.isListen()) continue;
9596 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9597 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009598 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009599 }
9600 }
9601 }
9602
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009603 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009604 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009605 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009606 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009607 @Nullable public final NetworkRequest mOldNetworkRequest;
9608 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009609 @Nullable public final NetworkAgentInfo mOldNetwork;
9610 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009611 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009612 @Nullable final NetworkRequest oldNetworkRequest,
9613 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009614 @Nullable final NetworkAgentInfo oldNetwork,
9615 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009616 mNetworkRequestInfo = networkRequestInfo;
9617 mOldNetworkRequest = oldNetworkRequest;
9618 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009619 mOldNetwork = oldNetwork;
9620 mNewNetwork = newNetwork;
9621 }
Chalard Jean49707572019-12-10 21:07:02 +09009622
9623 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009624 final NetworkRequest requestToShow = null != mNewNetworkRequest
9625 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9626 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009627 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9628 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009629 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009630 }
9631
Chalard Jean46a62372019-12-10 21:25:24 +09009632 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009633
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009634 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009635 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009636 }
9637
9638 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009639 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009640 // The code is never supposed to add two reassignments of the same request. Make
9641 // sure this stays true, but without imposing this expensive check on all
9642 // reassignments on all user devices.
9643 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009644 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009645 throw new IllegalStateException("Trying to reassign ["
9646 + reassignment + "] but already have ["
9647 + existing + "]");
9648 }
9649 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009650 }
Chalard Jean46a62372019-12-10 21:25:24 +09009651 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009652 }
9653
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009654 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009655 // the passed request.
9656 @Nullable
9657 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009658 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009659 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009660 }
9661 return null;
9662 }
Chalard Jean49707572019-12-10 21:07:02 +09009663
9664 public String toString() {
9665 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9666 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009667 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009668 for (final RequestReassignment rr : getRequestReassignments()) {
9669 sj.add(rr.toString());
9670 }
9671 return sj.toString();
9672 }
9673
9674 public String debugString() {
9675 final StringBuilder sb = new StringBuilder();
9676 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009677 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009678 for (final RequestReassignment rr : getRequestReassignments()) {
9679 sb.append("\n ").append(rr);
9680 }
9681 return sb.append("\n").toString();
9682 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009683 }
9684
Chalard Jean24344d72019-12-04 13:32:31 +09009685 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009686 @Nullable final NetworkRequest previousRequest,
9687 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009688 @Nullable final NetworkAgentInfo previousSatisfier,
9689 @Nullable final NetworkAgentInfo newSatisfier,
9690 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009691 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009692 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009693 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009694 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009695 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09009696 }
James Mattisa076c532020-12-02 14:12:41 -08009697 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009698 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009699 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009700 // If this network switch can't be supported gracefully, the request is not
9701 // lingered. This allows letting go of the network sooner to reclaim some
9702 // performance on the new network, since the radio can't do both at the same
9703 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009704 //
9705 // Also don't linger the request if the old network has been destroyed.
9706 // A destroyed network does not provide actual network connectivity, so
9707 // lingering it is not useful. In particular this ensures that a destroyed
9708 // network is outscored by its replacement,
9709 // then it is torn down immediately instead of being lingered, and any apps that
9710 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009711 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9712 }
Chalard Jean24344d72019-12-04 13:32:31 +09009713 } else {
9714 if (VDBG || DDBG) log(" accepting network in place of null");
9715 }
junyulai0ac374f2020-12-14 18:41:52 +08009716
9717 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9718 // and immediately satisfies a request then remove the timer. This will happen for
9719 // all networks except in the case of an underlying network for a VCN.
9720 if (newSatisfier.isNascent()) {
9721 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009722 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009723 }
9724
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009725 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009726 newSatisfier.unlingerRequest(newRequest.requestId);
9727 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009728 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009729 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009730 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009731 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009732 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009733 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009734 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009735 }
James Mattisa076c532020-12-02 14:12:41 -08009736 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009737 }
James Mattisa076c532020-12-02 14:12:41 -08009738 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009739 }
9740
James Mattisa076c532020-12-02 14:12:41 -08009741 /**
9742 * This function is triggered when something can affect what network should satisfy what
9743 * request, and it computes the network reassignment from the passed collection of requests to
9744 * network match to the one that the system should now have. That data is encoded in an
9745 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9746 * satisfier.
9747 *
9748 * After the reassignment is computed, it is applied to the state objects.
9749 *
9750 * @param networkRequests the nri objects to evaluate for possible network reassignment
9751 * @return NetworkReassignment listing of proposed network assignment changes
9752 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009753 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009754 private NetworkReassignment computeNetworkReassignment(
9755 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009756 final NetworkReassignment changes = new NetworkReassignment();
9757
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009758 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009759 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009760 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009761 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009762 }
Chalard Jean857a1712019-12-10 21:08:07 +09009763
James Mattisa076c532020-12-02 14:12:41 -08009764 for (final NetworkRequestInfo nri : networkRequests) {
9765 // Non-multilayer listen requests can be ignored.
9766 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9767 continue;
9768 }
9769 NetworkAgentInfo bestNetwork = null;
9770 NetworkRequest bestRequest = null;
9771 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009772 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009773 // Stop evaluating as the highest possible priority request is satisfied.
9774 if (null != bestNetwork) {
9775 bestRequest = req;
9776 break;
9777 }
9778 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009779 if (null == bestNetwork && isDefaultBlocked(nri)) {
9780 // Remove default networking if disallowed for managed default requests.
9781 bestNetwork = mNoServiceNetwork;
9782 }
9783 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009784 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009785 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009786 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009787 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009788 }
9789 return changes;
9790 }
9791
James Mattisa076c532020-12-02 14:12:41 -08009792 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9793 return new HashSet<>(mNetworkRequests.values());
9794 }
9795
Paul Jensenc88b39b2015-06-16 14:27:36 -04009796 /**
James Mattisa076c532020-12-02 14:12:41 -08009797 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009798 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009799 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009800 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009801 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9802 }
9803
9804 /**
9805 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9806 * being disconnected.
9807 */
9808 private void rematchNetworksAndRequests(
9809 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9810 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009811 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009812 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009813 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009814 final long computed = SystemClock.elapsedRealtime();
9815 applyNetworkReassignment(changes, start);
9816 final long applied = SystemClock.elapsedRealtime();
9817 issueNetworkNeeds();
9818 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009819 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009820 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9821 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009822 log(changes.debugString());
9823 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009824 // Shorter form, only one line of log
9825 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9826 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009827 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009828 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009829
Chalard Jeand7f762d2019-12-10 19:01:29 +09009830 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009831 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009832 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009833
9834 // Since most of the time there are only 0 or 1 background networks, it would probably
9835 // be more efficient to just use an ArrayList here. TODO : measure performance
9836 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9837 for (final NetworkAgentInfo nai : nais) {
9838 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9839 }
9840
Chalard Jeand7f762d2019-12-10 19:01:29 +09009841 // First, update the lists of satisfied requests in the network agents. This is necessary
9842 // because some code later depends on this state to be correct, most prominently computing
9843 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009844 for (final NetworkReassignment.RequestReassignment event :
9845 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009846 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9847 event.mOldNetworkRequest, event.mNewNetworkRequest,
9848 event.mOldNetwork, event.mNewNetwork,
9849 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009850 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009851
James Mattise3ef1912020-12-20 11:09:58 -08009852 // Process default network changes if applicable.
9853 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009854
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009855 // Notify requested networks are available after the default net is switched, but
9856 // before LegacyTypeTracker sends legacy broadcasts
9857 for (final NetworkReassignment.RequestReassignment event :
9858 changes.getRequestReassignments()) {
9859 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009860 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009861 } else {
James Mattisa076c532020-12-02 14:12:41 -08009862 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009863 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009864 }
9865 }
9866
junyulai0ac374f2020-12-14 18:41:52 +08009867 // Update the inactivity state before processing listen callbacks, because the background
9868 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009869 // just yet though, because they have to be sent after the listens are processed to keep
9870 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009871 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009872 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009873 // Rematching may have altered the inactivity state of some networks, so update all
9874 // inactivity timers. updateInactivityState reads the state from the network agent
9875 // and does nothing if the state has not changed : the source of truth is controlled
9876 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9877 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009878 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009879 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009880 }
9881 }
9882
Chalard Jeanb10ab412019-12-11 14:12:30 +09009883 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009884 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009885 // Process listen requests and update capabilities if the background state has
9886 // changed for this network. For consistency with previous behavior, send onLost
9887 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009888 processNewlyLostListenRequests(nai);
9889 if (oldBackground != nai.isBackgroundNetwork()) {
9890 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009891 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009892 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009893 }
9894
junyulai0ac374f2020-12-14 18:41:52 +08009895 for (final NetworkAgentInfo nai : inactiveNetworks) {
9896 // For nascent networks, if connecting with no foreground request, skip broadcasting
9897 // LOSING for backward compatibility. This is typical when mobile data connected while
9898 // wifi connected with mobile data always-on enabled.
9899 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009900 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009901 }
9902
James Mattise3ef1912020-12-20 11:09:58 -08009903 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009904
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009905 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +00009906 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009907 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009908 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009909 // This network has active linger timers and no requests, but is not
9910 // lingering. Linger it.
9911 //
9912 // One way (the only way?) this can happen if this network is unvalidated
9913 // and became unneeded due to another network improving its score to the
9914 // point where this network will no longer be able to satisfy any requests
9915 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009916 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009917 notifyNetworkLosing(nai, now);
9918 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009919 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009920 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009921 teardownUnneededNetwork(nai);
9922 }
9923 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009924 }
9925 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009926
Chalard Jean62edfd82019-12-02 18:39:29 +09009927 /**
9928 * Apply a change in background state resulting from rematching networks with requests.
9929 *
9930 * During rematch, a network may change background states by starting to satisfy or stopping
9931 * to satisfy a foreground request. Listens don't count for this. When a network changes
9932 * background states, its capabilities need to be updated and callbacks fired for the
9933 * capability change.
9934 *
9935 * @param nai The network that changed background states
9936 */
9937 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
9938 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
9939 if (Objects.equals(nai.networkCapabilities, newNc)) return;
9940 updateNetworkPermissions(nai, newNc);
9941 nai.getAndSetNetworkCapabilities(newNc);
9942 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
9943 }
9944
Chalard Jeanf0344532019-11-19 19:23:38 +09009945 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08009946 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009947 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09009948 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
9949 changes.getReassignment(mDefaultRequest);
9950 final NetworkAgentInfo oldDefaultNetwork =
9951 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
9952 final NetworkAgentInfo newDefaultNetwork =
9953 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08009954
Chalard Jean5b409c72021-02-04 13:12:59 +09009955 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009956 // Maintain the illusion : since the legacy API only understands one network at a time,
9957 // if the default network changed, apps should see a disconnected broadcast for the
9958 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009959 if (oldDefaultNetwork != null) {
9960 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9961 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009962 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009963 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009964 // The new default network can be newly null if and only if the old default
9965 // network doesn't satisfy the default request any more because it lost a
9966 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009967 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009968 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009969 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009970 }
9971 }
9972
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009973 // Now that all the callbacks have been sent, send the legacy network broadcasts
9974 // as needed. This is necessary so that legacy requests correctly bind dns
9975 // requests to this network. The legacy users are listening for this broadcast
9976 // and will generally do a dns request so they can ensureRouteToHost and if
9977 // they do that before the callbacks happen they'll use the default network.
9978 //
9979 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
9980 // callbacks, but if apps can receive the broadcast before the callback, they still might
9981 // have an inconsistent view of networking.
9982 //
9983 // This *does* introduce a race where if the user uses the new api
9984 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
9985 // they may get old info. Reverse this after the old startUsing api is removed.
9986 // This is on top of the multiple intent sequencing referenced in the todo above.
9987 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09009988 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009989 addNetworkToLegacyTypeTracker(nai);
9990 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08009991 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009992 }
9993
Chalard Jean0354d8c2021-01-12 10:58:56 +09009994 private void issueNetworkNeeds() {
9995 ensureRunningOnConnectivityServiceThread();
9996 for (final NetworkOfferInfo noi : mNetworkOffers) {
9997 issueNetworkNeeds(noi);
9998 }
9999 }
10000
10001 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
10002 ensureRunningOnConnectivityServiceThread();
10003 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10004 informOffer(nri, noi.offer, mNetworkRanker);
10005 }
10006 }
10007
10008 /**
10009 * Inform a NetworkOffer about any new situation of a request.
10010 *
10011 * This function handles updates to offers. A number of events may happen that require
10012 * updating the registrant for this offer about the situation :
10013 * • The offer itself was updated. This may lead the offer to no longer being able
10014 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
10015 * or conversely being strengthened enough to beat the satisfier (and therefore
10016 * start being needed)
10017 * • The network satisfying a request changed (including cases where the request
10018 * starts or stops being satisfied). The new network may be a stronger or weaker
10019 * match than the old one, possibly affecting whether the offer is needed.
10020 * • The network satisfying a request updated their score. This may lead the offer
10021 * to no longer be able to beat it if the current satisfier got better, or
10022 * conversely start being a good choice if the current satisfier got weaker.
10023 *
10024 * @param nri The request
10025 * @param offer The offer. This may be an updated offer.
10026 */
10027 private static void informOffer(@NonNull NetworkRequestInfo nri,
10028 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
10029 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
10030 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090010031
10032 // Multi-layer requests have a currently active request, the one being satisfied.
10033 // Since the system will try to bring up a better network than is currently satisfying
10034 // the request, NetworkProviders need to be told the offers matching the requests *above*
10035 // the currently satisfied one are needed, that the ones *below* the satisfied one are
10036 // not needed, and the offer is needed for the active request iff the offer can beat
10037 // the satisfier.
10038 // For non-multilayer requests, the logic above gracefully degenerates to only the
10039 // last case.
10040 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10041 // providers that the offer is needed for this request, until the active request is found.
10042 // In a second phase, deal with the currently active request. In a third phase, inform
10043 // the providers that offer is unneeded for the remaining requests.
10044
10045 // First phase : inform providers of all requests above the active request.
10046 int i;
10047 for (i = 0; nri.mRequests.size() > i; ++i) {
10048 final NetworkRequest request = nri.mRequests.get(i);
10049 if (activeRequest == request) break; // Found the active request : go to phase 2
10050 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10051 // Since this request is higher-priority than the one currently satisfied, if the
10052 // offer can satisfy it, the provider should try and bring up the network for sure ;
10053 // no need to even ask the ranker – an offer that can satisfy is always better than
10054 // no network. Hence tell the provider so unless it already knew.
10055 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10056 offer.onNetworkNeeded(request);
10057 }
10058 }
10059
10060 // Second phase : deal with the active request (if any)
10061 if (null != activeRequest && activeRequest.isRequest()) {
10062 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010063 // If an offer can satisfy the request, it is considered needed if it is currently
10064 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010065 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010066 && satisfier.factorySerialNumber == offer.providerId
10067 && activeRequest.canBeSatisfiedBy(offer.caps);
10068 final boolean newNeeded = currentlyServing
10069 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010070 if (newNeeded != oldNeeded) {
10071 if (newNeeded) {
10072 offer.onNetworkNeeded(activeRequest);
10073 } else {
10074 // The offer used to be able to beat the satisfier. Now it can't.
10075 offer.onNetworkUnneeded(activeRequest);
10076 }
10077 }
10078 }
10079
10080 // Third phase : inform the providers that the offer isn't needed for any request
10081 // below the active one.
10082 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10083 final NetworkRequest request = nri.mRequests.get(i);
10084 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10085 // Since this request is lower-priority than the one currently satisfied, if the
10086 // offer can satisfy it, the provider should not try and bring up the network.
10087 // Hence tell the provider so unless it already knew.
10088 if (offer.neededFor(request)) {
10089 offer.onNetworkUnneeded(request);
10090 }
10091 }
10092 }
10093
Chalard Jean61c79252019-11-07 23:07:32 +090010094 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10095 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10096 NetworkRequest nr = nai.requestAt(i);
10097 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10098 // legacy type tracker filters out repeat adds
10099 mLegacyTypeTracker.add(nr.legacyType, nai);
10100 }
10101 }
10102
10103 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010104 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010105 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10106 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10107 if (nai.isVPN()) {
10108 mLegacyTypeTracker.add(TYPE_VPN, nai);
10109 }
10110 }
10111
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010112 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010113 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010114 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010115 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010116 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010117 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010118
Chalard Jean254bd162022-08-25 13:04:51 +090010119 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010120 // Don't repeat publish.
10121 if (newInetCondition == mDefaultInetConditionPublished) return;
10122
10123 mDefaultInetConditionPublished = newInetCondition;
10124 sendInetConditionBroadcast(nai.networkInfo);
10125 }
10126
Chalard Jeand61375d2020-01-14 22:46:36 +090010127 @NonNull
10128 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10129 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010130 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010131 final boolean suspended =
10132 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10133 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10134 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10135 // state. This is because the network could have been suspended before connecting,
10136 // or it could be disconnecting while being suspended, and in both these cases
10137 // the state should not be overridden. Note that the only detailed state that
10138 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10139 // worry about multiple different substates of CONNECTED.
10140 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10141 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010142 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10143 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10144 // network agent is created, then goes to suspended, then goes out of suspended without
10145 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010146 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010147 ? NetworkInfo.DetailedState.CONNECTED
10148 : NetworkInfo.DetailedState.CONNECTING,
10149 info.getReason(),
10150 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010151 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010152 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010153 return newInfo;
10154 }
10155
10156 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10157 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10158
Erik Kline99f301b2017-02-15 19:59:17 +090010159 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010160 NetworkInfo oldInfo = null;
10161 synchronized (networkAgent) {
10162 oldInfo = networkAgent.networkInfo;
10163 networkAgent.networkInfo = newInfo;
10164 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010165
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010166 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010167 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10168 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010169 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010170
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010171 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010172 // A network that has just connected has zero requests and is thus a foreground network.
10173 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10174
Luke Huangfdd11f82019-04-09 18:41:49 +080010175 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010176
10177 networkAgent.setCreated();
10178
10179 // If the network is created immediately on register, then apply the LinkProperties now.
10180 // Otherwise, this is done further down when the network goes into connected state.
10181 // Applying the LinkProperties means that the network is ready to carry traffic -
10182 // interfaces and routing rules have been added, DNS servers programmed, etc.
10183 // For VPNs, this must be done before the capabilities are updated, because as soon as
10184 // that happens, UIDs are routed to the network.
10185 if (shouldCreateNetworksImmediately()) {
10186 applyInitialLinkProperties(networkAgent);
10187 }
10188
10189 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10190 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010191 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010192 // Initialize the network's capabilities to their starting values according to the
10193 // underlying networks. This ensures that the capabilities are correct before
10194 // anything happens to the network.
10195 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010196 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010197 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010198 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010199 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010200 }
10201
Chalard Jean254bd162022-08-25 13:04:51 +090010202 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10203 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010204
lucaslin45e639b2019-04-03 17:09:28 +080010205 // NetworkCapabilities need to be set before sending the private DNS config to
10206 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010207 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10208
Erik Kline9a62f012018-03-21 07:18:33 -070010209 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010210 if (!shouldCreateNetworksImmediately()) {
10211 applyInitialLinkProperties(networkAgent);
10212 } else {
10213 // The network was created when the agent registered, and the LinkProperties are
10214 // already up-to-date. However, updateLinkProperties also makes some changes only
10215 // when the network connects. Apply those changes here. On T and below these are
10216 // handled by the applyInitialLinkProperties call just above.
10217 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10218 // If something depends on both LinkProperties and connected state, it should be in
10219 // this method as well.
10220 networkAgent.clatd.update();
10221 updateProxy(networkAgent.linkProperties, null);
10222 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010223
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010224 // If a rate limit has been configured and is applicable to this network (network
10225 // provides internet connectivity), apply it. The tc police filter cannot be attached
10226 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
10227 // updateInterfaces -> INetd#networkAddInterface.
10228 // Note: in case of a system server crash, the NetworkController constructor in netd
10229 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10230 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10231 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10232 mIngressRateLimit);
10233 }
10234
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010235 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10236 // command must be sent after updating LinkProperties to maximize chances of
10237 // NetworkMonitor seeing the correct LinkProperties when starting.
10238 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010239 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010240 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010241 }
Chalard Jeand4900722022-02-06 12:25:38 +090010242 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10243 params.networkAgentConfig = networkAgent.networkAgentConfig;
10244 params.networkCapabilities = networkAgent.networkCapabilities;
10245 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10246 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010247 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10248 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10249 // call that would cause a Log.wtf to be emitted from the system_server process, and
10250 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10251 // process to check the interface version, just use an SDK check. NetworkStack will
10252 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010253 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010254 networkAgent.networkMonitor().notifyNetworkConnected(params);
10255 } else {
10256 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10257 params.networkCapabilities);
10258 }
Chalard Jean0f141332023-06-05 19:26:17 +090010259 final long evaluationDelay;
10260 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10261 // If the network is anything other than pure wifi, use the default timeout.
10262 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10263 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10264 // If the network is explicitly selected, use the default timeout because it's
10265 // shorter and the user is likely staring at the screen expecting it to validate
10266 // right away.
10267 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10268 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10269 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10270 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10271 } else {
10272 // It's wifi, automatically connected, and bad wifi is preferred : use the
10273 // longer timeout to avoid the device switching to captive portals with bad
10274 // signal or very slow response.
10275 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10276 }
10277 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010278
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010279 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10280 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10281 // capabilities, so it only needs to be done once on initial connect, not every time the
10282 // network's capabilities change. Note that we do this before rematching the network,
10283 // so we could decide to tear it down immediately afterwards. That's fine though - on
10284 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10285 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010286 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010287
junyulai0ac374f2020-12-14 18:41:52 +080010288 // Before first rematching networks, put an inactivity timer without any request, this
10289 // allows {@code updateInactivityState} to update the state accordingly and prevent
10290 // tearing down for any {@code unneeded} evaluation in this period.
10291 // Note that the timer will not be rescheduled since the expiry time is
10292 // fixed after connection regardless of the network satisfying other requests or not.
10293 // But it will be removed as soon as the network satisfies a request for the first time.
10294 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10295 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010296 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010297
Paul Jensen05e85ee2014-09-11 11:00:39 -040010298 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010299 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010300
10301 // This has to happen after matching the requests, because callbacks are just requests.
10302 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010303 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010304 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010305 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010306 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010307 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010308 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010309 if (networkAgent.isVPN()) {
10310 // As the active or bound network changes for apps, broadcast the default proxy, as
10311 // apps may need to update their proxy data. This is called after disconnecting from
10312 // VPN to make sure we do not broadcast the old proxy data.
10313 // TODO(b/122649188): send the broadcast only to VPN users.
10314 mProxyTracker.sendProxyBroadcast();
10315 }
Chalard Jean254bd162022-08-25 13:04:51 +090010316 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10317 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010318 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010319 }
10320 }
10321
Chalard Jean28018572020-12-21 18:36:52 +090010322 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010323 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10324 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010325 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010326 }
10327
Erik Kline99f301b2017-02-15 19:59:17 +090010328 // Notify only this one new request of the current state. Transfer all the
10329 // current state by calling NetworkCapabilities and LinkProperties callbacks
10330 // so that callers can be guaranteed to have as close to atomicity in state
10331 // transfer as can be supported by this current API.
10332 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010333 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010334 if (nri.mPendingIntent != null) {
10335 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10336 // Attempt no subsequent state pushes where intents are involved.
10337 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010338 }
Erik Kline99f301b2017-02-15 19:59:17 +090010339
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010340 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010341 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010342 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10343 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10344 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010345 }
10346
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010347 // Notify the requests on this NAI that the network is now lingered.
10348 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010349 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010350 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10351 }
10352
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010353 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10354 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10355 return vpnBlocked
10356 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10357 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10358 }
10359
10360 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10361 if (blockedReasons == BLOCKED_REASON_NONE) {
10362 mUidBlockedReasons.delete(uid);
10363 } else {
10364 mUidBlockedReasons.put(uid, blockedReasons);
10365 }
10366 }
10367
junyulaif2c67e42018-08-07 19:50:45 +080010368 /**
10369 * Notify of the blocked state apps with a registered callback matching a given NAI.
10370 *
10371 * Unlike other callbacks, blocked status is different between each individual uid. So for
10372 * any given nai, all requests need to be considered according to the uid who filed it.
10373 *
10374 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010375 * @param oldMetered True if the previous network capabilities were metered.
10376 * @param newMetered True if the current network capabilities are metered.
10377 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10378 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010379 */
10380 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010381 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10382 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010383
10384 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10385 NetworkRequest nr = nai.requestAt(i);
10386 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010387
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010388 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10389 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10390 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010391 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010392 : oldVpnBlocked;
10393
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010394 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10395 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10396 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010397 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010398 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010399 }
10400 }
10401 }
10402
10403 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010404 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010405 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010406 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010407 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010408 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010409 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010410 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010411 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010412
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010413 final int oldBlockedState = getBlockedState(
10414 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10415 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10416 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010417 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010418 }
junyulaif2c67e42018-08-07 19:50:45 +080010419 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10420 NetworkRequest nr = nai.requestAt(i);
10421 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010422 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010423 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10424 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010425 }
10426 }
10427 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010428 }
10429
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010430 @VisibleForTesting
10431 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010432 // The NetworkInfo we actually send out has no bearing on the real
10433 // state of affairs. For example, if the default connection is mobile,
10434 // and a request for HIPRI has just gone away, we need to pretend that
10435 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10436 // the state to DISCONNECTED, even though the network is of type MOBILE
10437 // and is still connected.
10438 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10439 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010440 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010441 if (state != DetailedState.DISCONNECTED) {
10442 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010443 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010444 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010445 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010446 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10447 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10448 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10449 if (info.isFailover()) {
10450 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10451 nai.networkInfo.setFailover(false);
10452 }
10453 if (info.getReason() != null) {
10454 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10455 }
10456 if (info.getExtraInfo() != null) {
10457 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10458 }
10459 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010460 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010461 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010462 if (newDefaultAgent != null) {
10463 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10464 newDefaultAgent.networkInfo);
10465 } else {
10466 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10467 }
10468 }
10469 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10470 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010471 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010472 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010473 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010474 }
10475 }
10476 }
10477
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010478 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010479 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010480 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010481 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010482 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010483 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10484 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010485 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10486 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010487 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010488 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010489 } else {
10490 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10491 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010492 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010493 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010494
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010495 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10496 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10497 }
10498
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010499 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010500 * Returns the list of all interfaces that could be used by network traffic that does not
10501 * explicitly specify a network. This includes the default network, but also all VPNs that are
10502 * currently connected.
10503 *
10504 * Must be called on the handler thread.
10505 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010506 @NonNull
10507 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010508 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010509 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010510 final Set<Integer> activeNetIds = new ArraySet<>();
10511 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10512 if (nri.isBeingSatisfied()) {
10513 activeNetIds.add(nri.getSatisfier().network().netId);
10514 }
10515 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010516 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010517 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010518 defaultNetworks.add(nai.network);
10519 }
10520 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010521 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010522 }
10523
10524 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010525 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10526 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010527 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010528 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010529 ensureRunningOnConnectivityServiceThread();
10530 String activeIface = null;
10531 LinkProperties activeLinkProperties = getActiveLinkProperties();
10532 if (activeLinkProperties != null) {
10533 activeIface = activeLinkProperties.getInterfaceName();
10534 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010535
junyulai2050bed2021-01-23 09:46:34 +080010536 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010537 try {
junyulaide41fc22021-01-22 22:46:01 +080010538 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010539 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010540 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10541 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010542 } catch (Exception ignored) {
10543 }
10544 }
10545
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010546 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010547 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010548 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010549 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010550 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010551
10552 if (!TextUtils.isEmpty(settingUrl)) {
10553 return settingUrl;
10554 }
10555
10556 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010557 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010558 if (!TextUtils.isEmpty(settingUrl)) {
10559 return settingUrl;
10560 }
10561
10562 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010563 }
10564
10565 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010566 public void startNattKeepalive(Network network, int intervalSeconds,
10567 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010568 enforceKeepalivePermission();
10569 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010570 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010571 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10572 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010573 // false and set the underpinned network to null because there is no way and no
10574 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10575 // deprecated method.
10576 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010577 }
10578
10579 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010580 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010581 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010582 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010583 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010584 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010585 mKeepaliveTracker.startNattKeepalive(
10586 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010587 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10588 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010589 } finally {
10590 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10591 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010592 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10593 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010594 }
10595 }
junyulaid05a1922019-01-15 11:32:44 +080010596 }
10597
10598 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010599 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010600 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010601 try {
10602 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010603 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010604 mKeepaliveTracker.startTcpKeepalive(
10605 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10606 } finally {
10607 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10608 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010609 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10610 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010611 }
10612 }
junyulai0835a1e2019-01-08 20:04:33 +080010613 }
10614
10615 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010616 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010617 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010618 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10619 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010620 }
10621
10622 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090010623 public int[] getSupportedKeepalives() {
10624 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10625 // Backwards compatibility with CTS 13
10626 android.Manifest.permission.QUERY_ALL_PACKAGES);
10627
10628 return BinderUtils.withCleanCallingIdentity(() ->
10629 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10630 }
10631
10632 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010633 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010634 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010635
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010636 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010637 final long token = Binder.clearCallingIdentity();
10638 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010639 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10640 UserHandle.getUserHandleForUid(uid))) {
10641 return;
10642 }
10643
Heemin Seogdb8489d2019-06-12 09:21:44 -070010644 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10645 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010646
10647 // Turn airplane mode off
10648 setAirplaneMode(false);
10649
10650 // restore private DNS settings to default mode (opportunistic)
10651 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10652 UserHandle.getUserHandleForUid(uid))) {
10653 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10654 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10655 }
10656
10657 Settings.Global.putString(mContext.getContentResolver(),
10658 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010659 } finally {
10660 Binder.restoreCallingIdentity(token);
10661 }
Stuart Scottd5463642015-04-02 18:00:02 -070010662 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010663
Ricky Wai7097cc92018-01-23 04:09:45 +000010664 @Override
10665 public byte[] getNetworkWatchlistConfigHash() {
10666 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10667 if (nwm == null) {
10668 loge("Unable to get NetworkWatchlistManager");
10669 return null;
10670 }
10671 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10672 return nwm.getWatchlistConfigHash();
10673 }
10674
Hugo Benichibe0c7652016-05-31 16:28:06 +090010675 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010676 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010677 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010678 }
Hugo Benichif4210292017-04-21 15:07:12 +090010679
10680 private static boolean toBool(int encodedBoolean) {
10681 return encodedBoolean != 0; // Only 0 means false.
10682 }
10683
10684 private static int encodeBool(boolean b) {
10685 return b ? 1 : 0;
10686 }
mswest4632928412018-03-12 10:34:34 -070010687
10688 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010689 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10690 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10691 @NonNull String[] args) {
10692 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10693 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010694 }
10695
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010696 private Boolean parseBooleanArgument(final String arg) {
10697 if ("true".equals(arg)) {
10698 return true;
10699 } else if ("false".equals(arg)) {
10700 return false;
10701 } else {
10702 return null;
10703 }
10704 }
10705
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010706 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010707 @Override
10708 public int onCommand(String cmd) {
10709 if (cmd == null) {
10710 return handleDefaultCommands(cmd);
10711 }
10712 final PrintWriter pw = getOutPrintWriter();
10713 try {
10714 switch (cmd) {
10715 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010716 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
10717 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070010718 final String action = getNextArg();
10719 if ("enable".equals(action)) {
10720 setAirplaneMode(true);
10721 return 0;
10722 } else if ("disable".equals(action)) {
10723 setAirplaneMode(false);
10724 return 0;
10725 } else if (action == null) {
10726 final ContentResolver cr = mContext.getContentResolver();
10727 final int enabled = Settings.Global.getInt(cr,
10728 Settings.Global.AIRPLANE_MODE_ON);
10729 pw.println(enabled == 0 ? "disabled" : "enabled");
10730 return 0;
10731 } else {
10732 onHelp();
10733 return -1;
10734 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010735 case "set-chain3-enabled": {
10736 final Boolean enabled = parseBooleanArgument(getNextArg());
10737 if (null == enabled) {
10738 onHelp();
10739 return -1;
10740 }
10741 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
10742 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
10743 enabled);
10744 return 0;
10745 }
10746 case "get-chain3-enabled": {
10747 final boolean chainEnabled = getFirewallChainEnabled(
10748 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
10749 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
10750 return 0;
10751 }
10752 case "set-package-networking-enabled": {
10753 final Boolean enabled = parseBooleanArgument(getNextArg());
10754 final String packageName = getNextArg();
10755 if (null == enabled || null == packageName) {
10756 onHelp();
10757 return -1;
10758 }
10759 // Throws NameNotFound if the package doesn't exist.
10760 final int appId = setPackageFirewallRule(
10761 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
10762 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
10763 final String msg = (enabled ? "Enabled" : "Disabled")
10764 + " networking for " + packageName + ", appId " + appId;
10765 Log.i(TAG, msg);
10766 pw.println(msg);
10767 return 0;
10768 }
10769 case "get-package-networking-enabled": {
10770 final String packageName = getNextArg();
10771 final int rule = getPackageFirewallRule(
10772 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
10773 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
10774 pw.println(packageName + ":" + "allow");
10775 } else if (FIREWALL_RULE_DENY == rule) {
10776 pw.println(packageName + ":" + "deny");
10777 } else {
10778 throw new IllegalStateException("Unknown rule " + rule + " for package "
10779 + packageName);
10780 }
10781 return 0;
10782 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010783 case "reevaluate":
10784 // Usage : adb shell cmd connectivity reevaluate <netId>
10785 // If netId is omitted, then reevaluate the default network
10786 final String netId = getNextArg();
10787 final NetworkAgentInfo nai;
10788 if (null == netId) {
10789 // Note that the command is running on the wrong thread to call this,
10790 // so this could in principle return stale data. But it can't crash.
10791 nai = getDefaultNetwork();
10792 } else {
10793 // If netId can't be parsed, this throws NumberFormatException, which
10794 // is passed back to adb who prints it.
10795 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10796 }
10797 if (null == nai) {
10798 pw.println("Unknown network (net ID not found or no default network)");
10799 return 0;
10800 }
10801 Log.d(TAG, "Reevaluating network " + nai.network);
10802 reportNetworkConnectivity(nai.network, !nai.isValidated());
10803 return 0;
mswest4632928412018-03-12 10:34:34 -070010804 default:
10805 return handleDefaultCommands(cmd);
10806 }
10807 } catch (Exception e) {
10808 pw.println(e);
10809 }
10810 return -1;
10811 }
10812
10813 @Override
10814 public void onHelp() {
10815 PrintWriter pw = getOutPrintWriter();
10816 pw.println("Connectivity service commands:");
10817 pw.println(" help");
10818 pw.println(" Print this help text.");
10819 pw.println(" airplane-mode [enable|disable]");
10820 pw.println(" Turn airplane mode on or off.");
10821 pw.println(" airplane-mode");
10822 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010823 pw.println(" set-chain3-enabled [true|false]");
10824 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
10825 pw.println(" get-chain3-enabled");
10826 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
10827 pw.println(" set-package-networking-enabled [true|false] [package name]");
10828 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
10829 + " no effect if the chain is disabled.");
10830 pw.println(" get-package-networking-enabled [package name]");
10831 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
mswest4632928412018-03-12 10:34:34 -070010832 }
10833 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010834
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010835 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010836 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10837 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10838 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010839 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010840 }
10841
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010842 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10843 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010844 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10845 final TransportInfo newInfo = nc.getTransportInfo();
10846 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10847 return;
10848 }
10849 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010850 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010851 }
10852 }
10853
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010854 /**
10855 * @param connectionInfo the connection to resolve.
10856 * @return {@code uid} if the connection is found and the app has permission to observe it
10857 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10858 * connection is not found.
10859 */
10860 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010861 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10862 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10863 }
10864
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010865 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010866 connectionInfo.local, connectionInfo.remote);
10867
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010868 if (uid == INVALID_UID) return uid; // Not found.
10869
10870 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10871 // VPN, if any, that applies to the UID that owns the connection.
10872 if (checkNetworkStackPermission()) return uid;
10873
10874 final NetworkAgentInfo vpn = getVpnForUid(uid);
10875 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010876 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010877 return INVALID_UID;
10878 }
10879
10880 return uid;
10881 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010882
Benedict Wong493e04b2018-11-09 14:45:34 -080010883 /**
10884 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10885 *
10886 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10887 */
10888 @Override
10889 public IBinder startOrGetTestNetworkService() {
10890 synchronized (mTNSLock) {
10891 TestNetworkService.enforceTestNetworkPermissions(mContext);
10892
10893 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010894 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010895 }
10896
10897 return mTNS;
10898 }
10899 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010900
Cody Kesting73708bf2019-12-18 10:57:50 -080010901 /**
10902 * Handler used for managing all Connectivity Diagnostics related functions.
10903 *
10904 * @see android.net.ConnectivityDiagnosticsManager
10905 *
10906 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10907 */
10908 @VisibleForTesting
10909 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010910 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10911
Cody Kesting73708bf2019-12-18 10:57:50 -080010912 /**
10913 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10914 * android.net.ConnectivityDiagnosticsManager}.
10915 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10916 * NetworkRequestInfo to be registered
10917 */
10918 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10919
10920 /**
10921 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10922 * android.net.ConnectivityDiagnosticsManager}.
10923 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10924 * arg1 = the uid of the caller
10925 */
10926 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10927
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010928 /**
10929 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010930 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010931 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10932 * NetworkMonitor.
10933 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010934 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010935 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010936
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010937 /**
10938 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10939 * been detected on the network.
10940 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10941 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10942 * arg2 = NetID.
10943 * data = PersistableBundle of extras passed from NetworkMonitor.
10944 */
10945 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10946
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010947 /**
10948 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10949 * the platform. This event will invoke {@link
10950 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10951 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070010952 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010953 */
10954 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
10955
Cody Kesting73708bf2019-12-18 10:57:50 -080010956 private ConnectivityDiagnosticsHandler(Looper looper) {
10957 super(looper);
10958 }
10959
10960 @Override
10961 public void handleMessage(Message msg) {
10962 switch (msg.what) {
10963 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10964 handleRegisterConnectivityDiagnosticsCallback(
10965 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
10966 break;
10967 }
10968 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10969 handleUnregisterConnectivityDiagnosticsCallback(
10970 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
10971 break;
10972 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010973 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010974 final ConnectivityReportEvent reportEvent =
10975 (ConnectivityReportEvent) msg.obj;
10976
Aaron Huang959d3642021-01-21 15:47:41 +080010977 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010978 break;
10979 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010980 case EVENT_DATA_STALL_SUSPECTED: {
10981 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080010982 final Pair<Long, PersistableBundle> arg =
10983 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010984 if (nai == null) break;
10985
Aaron Huang959d3642021-01-21 15:47:41 +080010986 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010987 break;
10988 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010989 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070010990 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010991 break;
10992 }
10993 default: {
10994 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
10995 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010996 }
10997 }
10998 }
10999
11000 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
11001 @VisibleForTesting
11002 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
11003 @NonNull private final IConnectivityDiagnosticsCallback mCb;
11004 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011005 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011006
11007 @VisibleForTesting
11008 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011009 @NonNull IConnectivityDiagnosticsCallback cb,
11010 @NonNull NetworkRequestInfo nri,
11011 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011012 mCb = cb;
11013 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011014 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011015 }
11016
11017 @Override
11018 public void binderDied() {
11019 log("ConnectivityDiagnosticsCallback IBinder died.");
11020 unregisterConnectivityDiagnosticsCallback(mCb);
11021 }
11022 }
11023
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011024 /**
11025 * Class used for sending information from {@link
11026 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
11027 */
11028 private static class NetworkTestedResults {
11029 private final int mNetId;
11030 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011031 @Nullable private final String mRedirectUrl;
11032
11033 private NetworkTestedResults(
11034 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
11035 mNetId = netId;
11036 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011037 mRedirectUrl = redirectUrl;
11038 }
11039 }
11040
11041 /**
11042 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11043 * ConnectivityDiagnosticsHandler}.
11044 */
11045 private static class ConnectivityReportEvent {
11046 private final long mTimestampMillis;
11047 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011048 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011049
Aaron Huang959d3642021-01-21 15:47:41 +080011050 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11051 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011052 mTimestampMillis = timestampMillis;
11053 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011054 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011055 }
11056 }
11057
Cody Kestingf1120be2020-08-03 18:01:40 -070011058 /**
11059 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11060 * ConnectivityDiagnosticsHandler}.
11061 */
11062 private static class ReportedNetworkConnectivityInfo {
11063 public final boolean hasConnectivity;
11064 public final boolean isNetworkRevalidating;
11065 public final int reporterUid;
11066 @NonNull public final NetworkAgentInfo nai;
11067
11068 private ReportedNetworkConnectivityInfo(
11069 boolean hasConnectivity,
11070 boolean isNetworkRevalidating,
11071 int reporterUid,
11072 @NonNull NetworkAgentInfo nai) {
11073 this.hasConnectivity = hasConnectivity;
11074 this.isNetworkRevalidating = isNetworkRevalidating;
11075 this.reporterUid = reporterUid;
11076 this.nai = nai;
11077 }
11078 }
11079
Cody Kesting73708bf2019-12-18 10:57:50 -080011080 private void handleRegisterConnectivityDiagnosticsCallback(
11081 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11082 ensureRunningOnConnectivityServiceThread();
11083
11084 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011085 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011086 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11087
James Mattis64b8b0f2020-11-24 17:40:49 -080011088 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11089 // confusing for these networks to change when an NRI is satisfied in another layer.
11090 if (nri.isMultilayerRequest()) {
11091 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11092 + "network requests.");
11093 }
11094
Cody Kesting73708bf2019-12-18 10:57:50 -080011095 // This means that the client registered the same callback multiple times. Do
11096 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011097 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011098 if (VDBG) log("Diagnostics callback is already registered");
11099
11100 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11101 // incremented when the NetworkRequestInfo is created as part of
11102 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011103 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011104 return;
11105 }
11106
Cody Kesting31f1ff62020-03-05 10:46:02 -080011107 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011108
11109 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011110 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011111 } catch (RemoteException e) {
11112 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011113 return;
11114 }
11115
11116 // Once registered, provide ConnectivityReports for matching Networks
11117 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11118 synchronized (mNetworkForNetId) {
11119 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11120 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011121 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11122 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011123 matchingNetworks.add(nai);
11124 }
11125 }
11126 }
11127 for (final NetworkAgentInfo nai : matchingNetworks) {
11128 final ConnectivityReport report = nai.getConnectivityReport();
11129 if (report == null) {
11130 continue;
11131 }
11132 if (!checkConnectivityDiagnosticsPermissions(
11133 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11134 continue;
11135 }
11136
11137 try {
11138 cb.onConnectivityReportAvailable(report);
11139 } catch (RemoteException e) {
11140 // Exception while sending the ConnectivityReport. Move on to the next network.
11141 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011142 }
11143 }
11144
11145 private void handleUnregisterConnectivityDiagnosticsCallback(
11146 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11147 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011148 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011149
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011150 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11151 mConnectivityDiagnosticsCallbacks.remove(iCb);
11152 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011153 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11154 return;
11155 }
11156
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011157 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011158
Cody Kesting70fa2b22020-12-02 12:16:56 -080011159 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11160 // (if the Binder died)
11161 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11162 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011163 return;
11164 }
11165
Cody Kesting46cb1672020-03-04 13:35:20 -080011166 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11167 // incremented when the NetworkRequestInfo is created as part of
11168 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011169 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011170
Cody Kesting31f1ff62020-03-05 10:46:02 -080011171 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011172 }
11173
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011174 private void handleNetworkTestedWithExtras(
11175 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11176 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011177 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011178 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011179 final ConnectivityReport report =
11180 new ConnectivityReport(
11181 reportEvent.mNai.network,
11182 reportEvent.mTimestampMillis,
11183 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011184 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011185 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011186 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011187
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011188 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011189 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011190 for (final IConnectivityDiagnosticsCallback cb : results) {
11191 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011192 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011193 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011194 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011195 }
11196 }
11197 }
11198
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011199 private void handleDataStallSuspected(
11200 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11201 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011202 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011203 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011204 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011205 new DataStallReport(
11206 nai.network,
11207 timestampMillis,
11208 detectionMethod,
11209 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011210 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011211 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011212 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011213 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011214 for (final IConnectivityDiagnosticsCallback cb : results) {
11215 try {
11216 cb.onDataStallSuspected(report);
11217 } catch (RemoteException ex) {
11218 loge("Error invoking onDataStallSuspected", ex);
11219 }
11220 }
11221 }
11222
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011223 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011224 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11225 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11226 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11227
11228 // If the Network is being re-validated as a result of this call to
11229 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11230 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011231 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011232 getMatchingPermissionedCallbacks(
11233 nai,
11234 reportedNetworkConnectivityInfo.isNetworkRevalidating
11235 ? Process.INVALID_UID
11236 : reportedNetworkConnectivityInfo.reporterUid);
11237
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011238 for (final IConnectivityDiagnosticsCallback cb : results) {
11239 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011240 cb.onNetworkConnectivityReported(
11241 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011242 } catch (RemoteException ex) {
11243 loge("Error invoking onNetworkConnectivityReported", ex);
11244 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011245
11246 // If the Network isn't re-validating, also provide the cached report. If there is no
11247 // cached report, the Network is still being validated and a report will be sent once
11248 // validation is complete. Note that networks which never undergo validation will still
11249 // have a cached ConnectivityReport with RESULT_SKIPPED.
11250 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11251 try {
11252 cb.onConnectivityReportAvailable(cachedReport);
11253 } catch (RemoteException ex) {
11254 loge("Error invoking onConnectivityReportAvailable", ex);
11255 }
11256 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011257 }
11258 }
11259
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011260 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011261 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11262 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011263 sanitized.setUids(null);
11264 sanitized.setAdministratorUids(new int[0]);
11265 sanitized.setOwnerUid(Process.INVALID_UID);
11266 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011267 }
11268
Cody Kestingf1120be2020-08-03 18:01:40 -070011269 /**
11270 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11271 *
11272 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11273 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011274 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011275 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011276 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011277 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011278 mConnectivityDiagnosticsCallbacks.entrySet()) {
11279 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11280 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011281
James Mattis64b8b0f2020-11-24 17:40:49 -080011282 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011283 if (!nai.satisfies(nri.mRequests.get(0))) {
11284 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011285 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011286
11287 // UID for this callback must either be:
11288 // - INVALID_UID (which sends callbacks to all UIDs), or
11289 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11290 // notified as a result)
11291 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11292 continue;
11293 }
11294
11295 if (!checkConnectivityDiagnosticsPermissions(
11296 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11297 continue;
11298 }
11299
11300 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011301 }
11302 return results;
11303 }
11304
Cody Kesting7474f672021-05-11 14:22:40 -070011305 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11306 @NonNull NetworkAgentInfo nai) {
11307 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11308 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11309 }
11310
Cody Kesting160ef392021-05-05 13:17:22 -070011311 private boolean hasLocationPermission(String packageName, int uid) {
11312 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11313 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11314 // call in a try-catch.
11315 try {
11316 if (!mLocationPermissionChecker.checkLocationPermission(
11317 packageName, null /* featureId */, uid, null /* message */)) {
11318 return false;
11319 }
11320 } catch (SecurityException e) {
11321 return false;
11322 }
11323
11324 return true;
11325 }
11326
11327 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11328 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011329 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011330 && virtual.networkCapabilities.getOwnerUid() == uid
11331 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11332 return true;
11333 }
11334 }
11335
11336 return false;
11337 }
11338
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011339 @VisibleForTesting
11340 boolean checkConnectivityDiagnosticsPermissions(
11341 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
11342 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
11343 return true;
11344 }
11345
Cody Kesting160ef392021-05-05 13:17:22 -070011346 // Administrator UIDs also contains the Owner UID
11347 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11348 if (!CollectionUtils.contains(administratorUids, callbackUid)
11349 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011350 return false;
11351 }
11352
Cody Kesting7474f672021-05-11 14:22:40 -070011353 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11354 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011355 }
11356
Cody Kestingd199a9d2019-12-17 12:55:28 -080011357 @Override
11358 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011359 @NonNull IConnectivityDiagnosticsCallback callback,
11360 @NonNull NetworkRequest request,
11361 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011362 Objects.requireNonNull(callback, "callback must not be null");
11363 Objects.requireNonNull(request, "request must not be null");
11364 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11365
Cody Kesting73708bf2019-12-18 10:57:50 -080011366 if (request.legacyType != TYPE_NONE) {
11367 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11368 + " Please use NetworkCapabilities instead.");
11369 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011370 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011371 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011372
11373 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11374 // and administrator uids to be safe.
11375 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011376 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011377
11378 final NetworkRequest requestWithId =
11379 new NetworkRequest(
11380 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11381
11382 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11383 //
11384 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11385 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11386 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011387 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011388 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011389 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011390
11391 mConnectivityDiagnosticsHandler.sendMessage(
11392 mConnectivityDiagnosticsHandler.obtainMessage(
11393 ConnectivityDiagnosticsHandler
11394 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11395 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011396 }
11397
11398 @Override
11399 public void unregisterConnectivityDiagnosticsCallback(
11400 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011401 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011402 mConnectivityDiagnosticsHandler.sendMessage(
11403 mConnectivityDiagnosticsHandler.obtainMessage(
11404 ConnectivityDiagnosticsHandler
11405 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011406 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011407 0,
11408 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011409 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011410
Yan Yanfe96dde2022-12-05 23:00:01 +000011411 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11412 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11413 if (underlyingNetworks == null) return false;
11414
11415 for (Network network : underlyingNetworks) {
11416 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11417 return true;
11418 }
11419 }
11420 return false;
11421 }
11422
Cody Kestingf53a0752020-04-15 12:33:28 -070011423 @Override
11424 public void simulateDataStall(int detectionMethod, long timestampMillis,
11425 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011426 Objects.requireNonNull(network, "network must not be null");
11427 Objects.requireNonNull(extras, "extras must not be null");
11428
paulhu3ffffe72021-09-16 10:15:22 +080011429 enforceAnyPermissionOf(mContext,
11430 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011431 android.Manifest.permission.NETWORK_STACK);
11432 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011433 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11434 throw new SecurityException(
11435 "Data Stall simulation is only possible for test networks or networks built on"
11436 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011437 }
11438
11439 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011440 if (nai == null
11441 || (nai.creatorUid != mDeps.getCallingUid()
11442 && nai.creatorUid != Process.SYSTEM_UID)) {
11443 throw new SecurityException(
11444 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011445 }
11446
Cody Kesting652e3ec2020-05-21 12:08:21 -070011447 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11448 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11449 // Data Stall information as a DataStallReportParcelable and passing to
11450 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11451 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011452 final DataStallReportParcelable p = new DataStallReportParcelable();
11453 p.timestampMillis = timestampMillis;
11454 p.detectionMethod = detectionMethod;
11455
11456 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11457 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11458 }
11459 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11460 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11461 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11462 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11463 }
11464
Serik Beketayevec8ad212020-12-07 22:43:07 -080011465 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011466 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011467
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011468 /**
11469 * Class to hold the information for network activity change event from idle timers
11470 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
11471 */
11472 private static final class NetworkActivityParams {
11473 public final boolean isActive;
11474 // Label used for idle timer. Transport type is used as label.
11475 // label is int since NMS was using the identifier as int, and it has not been changed
11476 public final int label;
11477 public final long timestampNs;
11478 // Uid represents the uid that was responsible for waking the radio.
11479 // -1 for no uid and uid is -1 if isActive is false.
11480 public final int uid;
11481
11482 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
11483 this.isActive = isActive;
11484 this.label = label;
11485 this.timestampNs = timestampNs;
11486 this.uid = uid;
11487 }
11488 }
11489
lucaslin66f44212021-02-23 01:12:55 +080011490 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11491 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011492 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080011493 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011494 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
11495 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080011496 }
lucaslin37a16d92021-01-21 19:48:09 +080011497
11498 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011499 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011500 mHandler.post(() -> {
11501 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011502 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011503 }
11504 });
lucaslin37a16d92021-01-21 19:48:09 +080011505 }
11506
11507 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011508 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011509 mHandler.post(() -> {
11510 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011511 nai.clatd.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011512 }
11513 });
lucaslin66f44212021-02-23 01:12:55 +080011514 }
11515 }
11516
lucaslin1a8b4c62021-01-21 02:02:55 +080011517 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11518
11519 /**
11520 * Class used for updating network activity tracking with netd and notify network activity
11521 * changes.
11522 */
11523 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011524 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011525 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011526 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011527 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080011528 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11529 new RemoteCallbackList<>();
11530 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090011531 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011532 // If there is no default network, default network is considered active to keep the existing
11533 // behavior. Initial value is used until first connect to the default network.
11534 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011535 // Key is netId. Value is configured idle timer information.
11536 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080011537
Chalard Jean46bfbf02022-02-02 00:56:25 +090011538 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011539 public final int timeout;
11540 public final int transportType;
11541
11542 IdleTimerParams(int timeout, int transport) {
11543 this.timeout = timeout;
11544 this.transportType = transport;
11545 }
11546 }
11547
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011548 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011549 @NonNull Handler handler) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011550 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011551 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011552 mHandler = handler;
11553 }
11554
11555 private void ensureRunningOnConnectivityServiceThread() {
11556 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
11557 throw new IllegalStateException("Not running on ConnectivityService thread: "
11558 + Thread.currentThread().getName());
11559 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011560 }
11561
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011562 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011563 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011564 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011565 // This activity change is not for the current default network.
11566 // This can happen if netd callback post activity change event message but
11567 // the default network is lost before processing this message.
11568 return;
11569 }
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011570 sendDataActivityBroadcast(transportTypeToLegacyType(activityParams.label),
11571 activityParams.isActive, activityParams.timestampNs);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011572 mIsDefaultNetworkActive = activityParams.isActive;
11573 if (mIsDefaultNetworkActive) {
11574 reportNetworkActive();
lucaslin66f44212021-02-23 01:12:55 +080011575 }
11576 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011577
lucaslin1193a5d2021-01-21 02:04:15 +080011578 private void reportNetworkActive() {
11579 final int length = mNetworkActivityListeners.beginBroadcast();
11580 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
11581 try {
11582 for (int i = 0; i < length; i++) {
11583 try {
11584 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
11585 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011586 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080011587 }
11588 }
11589 } finally {
11590 mNetworkActivityListeners.finishBroadcast();
11591 }
11592 }
11593
lucaslin1a8b4c62021-01-21 02:02:55 +080011594 // This is deprecated and only to support legacy use cases.
11595 private int transportTypeToLegacyType(int type) {
11596 switch (type) {
11597 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011598 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080011599 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011600 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080011601 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011602 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080011603 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011604 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080011605 default:
11606 loge("Unexpected transport in transportTypeToLegacyType: " + type);
11607 }
11608 return ConnectivityManager.TYPE_NONE;
11609 }
11610
11611 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
11612 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
11613 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
11614 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
11615 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
11616 final long ident = Binder.clearCallingIdentity();
11617 try {
11618 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
11619 RECEIVE_DATA_ACTIVITY_CHANGE,
11620 null /* resultReceiver */,
11621 null /* scheduler */,
11622 0 /* initialCode */,
11623 null /* initialData */,
11624 null /* initialExtra */);
11625 } finally {
11626 Binder.restoreCallingIdentity(ident);
11627 }
11628 }
11629
11630 /**
11631 * Setup data activity tracking for the given network.
11632 *
11633 * Every {@code setupDataActivityTracking} should be paired with a
11634 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090011635 *
11636 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080011637 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090011638 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011639 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011640 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080011641
11642 final int timeout;
11643 final int type;
11644
11645 if (networkAgent.networkCapabilities.hasTransport(
11646 NetworkCapabilities.TRANSPORT_CELLULAR)) {
11647 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011648 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080011649 10);
11650 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11651 } else if (networkAgent.networkCapabilities.hasTransport(
11652 NetworkCapabilities.TRANSPORT_WIFI)) {
11653 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011654 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080011655 15);
11656 type = NetworkCapabilities.TRANSPORT_WIFI;
11657 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011658 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080011659 }
11660
lucaslinb961efc2021-01-21 02:03:17 +080011661 updateRadioPowerState(true /* isActive */, type);
11662
lucaslin1a8b4c62021-01-21 02:02:55 +080011663 if (timeout > 0 && iface != null) {
11664 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011665 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, type));
Motomu Utsumic298cf02023-05-31 12:06:12 +090011666 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
Motomu Utsumi6225d572023-05-29 15:08:57 +090011667 return true;
lucaslin1a8b4c62021-01-21 02:02:55 +080011668 } catch (Exception e) {
11669 // You shall not crash!
11670 loge("Exception in setupDataActivityTracking " + e);
11671 }
11672 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011673 return false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011674 }
11675
11676 /**
11677 * Remove data activity tracking when network disconnects.
11678 */
11679 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
11680 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011681 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080011682 final NetworkCapabilities caps = networkAgent.networkCapabilities;
11683
lucaslinb961efc2021-01-21 02:03:17 +080011684 if (iface == null) return;
11685
11686 final int type;
11687 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
11688 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11689 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
11690 type = NetworkCapabilities.TRANSPORT_WIFI;
11691 } else {
11692 return; // do not track any other networks
11693 }
11694
11695 try {
11696 updateRadioPowerState(false /* isActive */, type);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011697 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011698 if (params == null) {
11699 // IdleTimer is not added if the configured timeout is 0 or negative value
11700 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080011701 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011702 mActiveIdleTimers.remove(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011703 // The call fails silently if no idle timer setup for this interface
11704 mNetd.idletimerRemoveInterface(iface, params.timeout,
11705 Integer.toString(params.transportType));
lucaslinb961efc2021-01-21 02:03:17 +080011706 } catch (Exception e) {
11707 // You shall not crash!
11708 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080011709 }
11710 }
11711
Motomu Utsumi6225d572023-05-29 15:08:57 +090011712 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
11713 boolean hasIdleTimer) {
11714 if (defaultNetwork != null) {
11715 mIsDefaultNetworkActive = true;
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011716 // Callbacks are called only when the network has the idle timer.
11717 if (hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011718 reportNetworkActive();
11719 }
11720 } else {
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011721 // If there is no default network, default network is considered active to keep the
11722 // existing behavior.
11723 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090011724 }
11725 }
11726
lucaslin1a8b4c62021-01-21 02:02:55 +080011727 /**
11728 * Update data activity tracking when network state is updated.
11729 */
11730 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
11731 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011732 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi6225d572023-05-29 15:08:57 +090011733 boolean hasIdleTimer = false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011734 if (newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011735 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080011736 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011737 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
lucaslin1a8b4c62021-01-21 02:02:55 +080011738 if (oldNetwork != null) {
11739 removeDataActivityTracking(oldNetwork);
11740 }
11741 }
lucaslinb961efc2021-01-21 02:03:17 +080011742
11743 private void updateRadioPowerState(boolean isActive, int transportType) {
11744 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
11745 switch (transportType) {
11746 case NetworkCapabilities.TRANSPORT_CELLULAR:
11747 bs.reportMobileRadioPowerState(isActive, NO_UID);
11748 break;
11749 case NetworkCapabilities.TRANSPORT_WIFI:
11750 bs.reportWifiRadioPowerState(isActive, NO_UID);
11751 break;
11752 default:
11753 logw("Untracked transport type:" + transportType);
11754 }
11755 }
lucaslin1193a5d2021-01-21 02:04:15 +080011756
11757 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011758 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080011759 }
11760
11761 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
11762 mNetworkActivityListeners.register(l);
11763 }
11764
11765 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
11766 mNetworkActivityListeners.unregister(l);
11767 }
lucaslin012f7a12021-01-21 02:04:35 +080011768
11769 public void dump(IndentingPrintWriter pw) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011770 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
11771 pw.println("Idle timers:");
11772 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011773 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
11774 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
11775 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080011776 pw.print(" timeout="); pw.print(params.timeout);
11777 pw.print(" type="); pw.println(params.transportType);
11778 }
Motomu Utsumic298cf02023-05-31 12:06:12 +090011779 } catch (Exception e) {
11780 // mActiveIdleTimers should only be accessed from handler thread, except dump().
11781 // As dump() is never called in normal usage, it would be needlessly expensive
11782 // to lock the collection only for its benefit.
11783 // Also, mActiveIdleTimers is not expected to be updated frequently.
11784 // So catching the exception and logging.
11785 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080011786 }
11787 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011788 }
James Mattis47db0582021-01-01 14:13:35 -080011789
Daniel Brightf9e945b2020-06-15 16:10:01 -070011790 /**
11791 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
11792 *
11793 * @param socketInfo the socket information
11794 * @param callback the callback to register
11795 */
11796 @Override
11797 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
11798 @NonNull final IQosCallback callback) {
11799 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
11800 if (nai == null || nai.networkCapabilities == null) {
11801 try {
11802 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
11803 } catch (final RemoteException ex) {
11804 loge("registerQosCallbackInternal: RemoteException", ex);
11805 }
11806 return;
11807 }
11808 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
11809 }
11810
11811 /**
11812 * Register a {@link IQosCallback} with base {@link QosFilter}.
11813 *
11814 * @param filter the filter to register
11815 * @param callback the callback to register
11816 * @param nai the agent information related to the filter's network
11817 */
11818 @VisibleForTesting
11819 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
11820 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011821 Objects.requireNonNull(filter, "filter must be non-null");
11822 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011823
11824 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080011825 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
11826 // on this network is unregistered when the app loses permission or b) no QoS
11827 // callbacks are sent for restricted networks unless the app currently has permission
11828 // to access restricted networks.
11829 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070011830 }
11831 mQosCallbackTracker.registerCallback(callback, filter, nai);
11832 }
11833
11834 /**
11835 * Unregisters the given callback.
11836 *
11837 * @param callback the callback to unregister
11838 */
11839 @Override
11840 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011841 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011842 mQosCallbackTracker.unregisterCallback(callback);
11843 }
James Mattis47db0582021-01-01 14:13:35 -080011844
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011845 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
11846 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
11847 // Enterprise device can be fully managed like device owner and such use case
11848 // also should be supported. Calling app check for work profile and fully managed device
11849 // is already done in DevicePolicyManager.
11850 // This check is an extra caution to be sure device is fully managed or not.
11851 final UserManager um = mContext.getSystemService(UserManager.class);
11852 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
11853 if (um.isManagedProfile(profile.getIdentifier())) {
11854 return true;
11855 }
Chalard Jeandf29a852023-05-29 17:02:43 +090011856 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011857 return false;
11858 }
11859
James Mattis45d81842021-01-10 14:24:24 -080011860 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011861 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011862 *
11863 * See the documentation for the individual preferences for a description of the supported
11864 * behaviors.
11865 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011866 * @param profile If the device owner is set, any profile is allowed.
11867 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011868 * @param preferences the list of profile network preferences for the
11869 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011870 * @param listener an optional listener to listen for completion of the operation.
11871 */
11872 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011873 public void setProfileNetworkPreferences(
11874 @NonNull final UserHandle profile,
11875 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090011876 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011877 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011878 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011879
11880 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011881 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11882 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11883 .build();
11884 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011885 }
11886
paulhu3ffffe72021-09-16 10:15:22 +080011887 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011888 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011889 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011890 }
11891 if (profile.getIdentifier() < 0) {
11892 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11893 + "UserHandle.CURRENT not supported)");
11894 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011895 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11896 throw new IllegalArgumentException("Profile must be a managed profile "
11897 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011898 }
paulhuaa0743d2021-05-26 21:56:03 +080011899
Chalard Jean0606fc82022-12-14 20:34:43 +090011900 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011901 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011902 for (final ProfileNetworkPreference preference : preferences) {
11903 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011904 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011905 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011906 switch (preference.getPreference()) {
11907 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11908 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011909 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011910 if (preference.getPreferenceEnterpriseId() != 0) {
11911 throw new IllegalArgumentException(
11912 "Invalid enterprise identifier in setProfileNetworkPreferences");
11913 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011914 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011915 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11916 blockingNonEnterprise = true;
11917 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011918 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11919 allowFallback = false;
11920 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011921 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011922 // This code is needed even though there is a check later on,
11923 // because isRangeAlreadyInPreferenceList assumes that every preference
11924 // has a UID list.
11925 if (hasDefaultPreference) {
11926 throw new IllegalArgumentException(
11927 "Default profile preference should not be set along with other "
11928 + "preference");
11929 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011930 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11931 throw new IllegalArgumentException(
11932 "Invalid enterprise identifier in setProfileNetworkPreferences");
11933 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011934 final Set<UidRange> uidRangeSet =
11935 getUidListToBeAppliedForNetworkPreference(profile, preference);
11936 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11937 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11938 } else {
11939 throw new IllegalArgumentException(
11940 "Overlapping uid range in setProfileNetworkPreferences");
11941 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011942 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011943 nc.addEnterpriseId(
11944 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011945 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11946 break;
11947 default:
11948 throw new IllegalArgumentException(
11949 "Invalid preference in setProfileNetworkPreferences");
11950 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011951 preferenceList.add(new ProfileNetworkPreferenceInfo(
11952 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011953 if (hasDefaultPreference && preferenceList.size() > 1) {
11954 throw new IllegalArgumentException(
11955 "Default profile preference should not be set along with other preference");
11956 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011957 }
11958 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011959 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011960 }
11961
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011962 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
11963 @NonNull final UserHandle profile,
11964 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
11965 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080011966 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
11967 profileNetworkPreference.getIncludedUids());
11968
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011969 if (uidRangeSet.size() > 0) {
11970 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
11971 throw new IllegalArgumentException(
11972 "Allow uid range is outside the uid range of profile.");
11973 }
11974 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080011975 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011976 profileNetworkPreference.getExcludedUids());
11977 if (disallowUidRangeSet.size() > 0) {
11978 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
11979 throw new IllegalArgumentException(
11980 "disallow uid range is outside the uid range of profile.");
11981 }
11982 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
11983 disallowUidRangeSet);
11984 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011985 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011986 uidRangeSet.add(profileUids);
11987 }
11988 }
11989 return uidRangeSet;
11990 }
11991
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011992 private boolean isEnterpriseIdentifierValid(
11993 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011994 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011995 return true;
11996 }
11997 return false;
11998 }
11999
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012000 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090012001 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012002 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090012003 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012004 // The NRI for a user should contain the request for capabilities.
12005 // If fallback to default network is needed then NRI should include
12006 // the request for the default network. Create an image of it to
12007 // have the correct UIDs in it (also a request can only be part of one NRI, because
12008 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012009 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
12010 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012011 if (pref.allowFallback) {
12012 nrs.add(createDefaultInternetRequestForTransport(
12013 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12014 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012015 if (VDBG) {
12016 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
12017 pref.capabilities.getUids()));
12018 }
12019
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012020 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080012021 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080012022 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012023 result.add(nri);
12024 }
12025 return result;
12026 }
12027
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012028 /**
12029 * Compare if the given UID range sets have the same UIDs.
12030 *
12031 */
12032 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090012033 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012034 @NonNull Set<UidRange> uidRangeSet) {
12035 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
12036 return false;
12037 }
Chalard Jean0606fc82022-12-14 20:34:43 +090012038 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012039 if (UidRangeUtils.doesRangeSetOverlap(
12040 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12041 return true;
12042 }
12043 }
12044 return false;
12045 }
12046
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012047 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012048 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012049 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012050 /*
12051 * handleSetProfileNetworkPreference is always called for single user.
12052 * preferenceList only contains preferences for different uids within the same user
12053 * (enforced by getUidListToBeAppliedForNetworkPreference).
12054 * Clear all the existing preferences for the user before applying new preferences.
12055 *
12056 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012057 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12058 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012059 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12060 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012061
paulhu74128522021-09-28 02:29:03 +000012062 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12063 addPerAppDefaultNetworkRequests(
12064 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012065 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012066
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012067 // Finally, rematch.
12068 rematchAllNetworksAndRequests();
12069
12070 if (null != listener) {
12071 try {
12072 listener.onComplete();
12073 } catch (RemoteException e) {
12074 loge("Listener for setProfileNetworkPreference has died");
12075 }
12076 }
12077 }
12078
paulhu51f77dc2021-06-07 02:34:20 +000012079 @VisibleForTesting
12080 @NonNull
12081 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12082 @NonNull final Set<Integer> uids) {
12083 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12084 if (uids.size() == 0) {
12085 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12086 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
12087 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
12088 return nris;
12089 }
12090
12091 final List<NetworkRequest> requests = new ArrayList<>();
12092 // The NRI should be comprised of two layers:
12093 // - The request for the mobile network preferred.
12094 // - The request for the default network, for fallback.
12095 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012096 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012097 requests.add(createDefaultInternetRequestForTransport(
12098 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12099 final Set<UidRange> ranges = new ArraySet<>();
12100 for (final int uid : uids) {
12101 ranges.add(new UidRange(uid, uid));
12102 }
12103 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080012104 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080012105 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000012106 return nris;
12107 }
12108
12109 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012110 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012111 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12112 addPerAppDefaultNetworkRequests(
12113 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012114 // Finally, rematch.
12115 rematchAllNetworksAndRequests();
12116 }
12117
Patrick Rohr2857ac42022-01-21 14:58:16 +010012118 private void handleIngressRateLimitChanged() {
12119 final long oldIngressRateLimit = mIngressRateLimit;
12120 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12121 mContext);
12122 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12123 if (canNetworkBeRateLimited(networkAgent)) {
12124 // If rate limit has previously been enabled, remove the old limit first.
12125 if (oldIngressRateLimit >= 0) {
12126 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12127 }
12128 if (mIngressRateLimit >= 0) {
12129 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12130 mIngressRateLimit);
12131 }
12132 }
12133 }
12134 }
12135
12136 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012137 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090012138 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012139
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012140 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12141 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12142 // internet connectivity can be rate limited.
12143 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12144 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012145 return false;
12146 }
12147
12148 final String iface = networkAgent.linkProperties.getInterfaceName();
12149 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012150 // This may happen in tests, but if there is no interface then there is nothing that
12151 // can be rate limited.
12152 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012153 return false;
12154 }
12155 return true;
12156 }
12157
James Mattis45d81842021-01-10 14:24:24 -080012158 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012159 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12160 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012161 }
12162
12163 /**
12164 * Used by automotive devices to set the network preferences used to direct traffic at an
12165 * application level as per the given OemNetworkPreferences. An example use-case would be an
12166 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12167 * vehicle via a particular network.
12168 *
12169 * Calling this will overwrite the existing preference.
12170 *
James Mattisda32cfe2021-01-26 16:23:52 -080012171 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012172 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012173 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012174 */
James Mattis47db0582021-01-01 14:13:35 -080012175 @Override
James Mattis45d81842021-01-10 14:24:24 -080012176 public void setOemNetworkPreference(
12177 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012178 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012179
James Mattisfa270db2021-05-31 17:11:10 -070012180 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12181 // Only bypass the permission/device checks if this is a valid test request.
12182 if (isValidTestOemNetworkPreference(preference)) {
12183 enforceManageTestNetworksPermission();
12184 } else {
12185 enforceAutomotiveDevice();
12186 enforceOemNetworkPreferencesPermission();
12187 validateOemNetworkPreferences(preference);
12188 }
James Mattis45d81842021-01-10 14:24:24 -080012189
James Mattis45d81842021-01-10 14:24:24 -080012190 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12191 new Pair<>(preference, listener)));
12192 }
12193
James Mattisfa270db2021-05-31 17:11:10 -070012194 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012195 * Sets the specified UIDs to get/receive the VPN as the only default network.
12196 *
12197 * Calling this will overwrite the existing network preference for this session, and the
12198 * specified UIDs won't get any default network when no VPN is connected.
12199 *
12200 * @param session The VPN session which manages the passed UIDs.
12201 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12202 * setting for this session if the array is empty. Null is not allowed, the
12203 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12204 * @hide
12205 */
12206 @Override
12207 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12208 Objects.requireNonNull(ranges);
12209 enforceNetworkStackOrSettingsPermission();
12210 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12211 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12212 throw new IllegalArgumentException(
12213 "setVpnNetworkPreference: Passed UID ranges overlap");
12214 }
12215
12216 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12217 new VpnNetworkPreferenceInfo(session,
12218 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12219 }
12220
12221 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12222 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12223
12224 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12225 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12226
12227 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12228 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12229 // Finally, rematch.
12230 rematchAllNetworksAndRequests();
12231 }
12232
12233 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12234 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12235 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12236 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
12237 final List<NetworkRequest> requests = new ArrayList<>();
12238 // Request VPN only, so other networks won't be the fallback options when VPN is not
12239 // connected temporarily.
12240 requests.add(createVpnRequest());
12241 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
12242 setNetworkRequestUids(requests, uidRanges);
12243 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
12244 }
12245 return nris;
12246 }
12247
12248 /**
James Mattisfa270db2021-05-31 17:11:10 -070012249 * Check the validity of an OEM network preference to be used for testing purposes.
12250 * @param preference the preference to validate
12251 * @return true if this is a valid OEM network preference test request.
12252 */
12253 private boolean isValidTestOemNetworkPreference(
12254 @NonNull final OemNetworkPreferences preference) {
12255 // Allow for clearing of an existing OemNetworkPreference used for testing.
12256 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
12257 // changes after this check is complete. This is an unlikely scenario as calling of this API
12258 // is controlled by the OEM therefore the added complexity is not worth adding given those
12259 // circumstances. That said, it is an edge case to be aware of hence this comment.
12260 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
12261 && isTestOemNetworkPreference(mOemNetworkPreferences);
12262 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
12263 }
12264
12265 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
12266 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
12267 return prefMap.size() == 1
12268 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
12269 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
12270 }
12271
James Mattis45d81842021-01-10 14:24:24 -080012272 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
12273 for (@OemNetworkPreferences.OemNetworkPreference final int pref
12274 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070012275 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
12276 throw new IllegalArgumentException(
12277 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
12278 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080012279 }
12280 }
12281 }
12282
12283 private void handleSetOemNetworkPreference(
12284 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012285 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080012286 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12287 if (DBG) {
12288 log("set OEM network preferences :" + preference.toString());
12289 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012290
James Mattiscb1e0362021-04-06 17:07:42 -070012291 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012292 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12293 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12294 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012295 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012296
12297 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012298 try {
12299 listener.onComplete();
12300 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012301 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012302 }
James Mattis45d81842021-01-10 14:24:24 -080012303 }
12304 }
12305
paulhu74128522021-09-28 02:29:03 +000012306 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012307 // Skip the requests which are set by other network preference. Because the uid range rules
12308 // should stay in netd.
12309 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012310 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012311 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012312 }
12313
James Mattis3ce3d3c2021-02-09 18:18:28 -080012314 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12315 ensureRunningOnConnectivityServiceThread();
12316 mDefaultNetworkRequests.addAll(nris);
12317 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12318 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012319 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012320 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12321 nrisToRegister.addAll(
12322 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12323 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012324 }
12325
12326 /**
12327 * All current requests that are tracking the default network need to be assessed as to whether
12328 * or not the current set of per-application default requests will be changing their default
12329 * network. If so, those requests will need to be updated so that they will send callbacks for
12330 * default network changes at the appropriate time. Additionally, those requests tracking the
12331 * default that were previously updated by this flow will need to be reassessed.
12332 * @return the nris which will need to be updated.
12333 */
12334 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12335 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12336 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12337 // same nri in the map's values for each of its NetworkRequest objects.
12338 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012339 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012340 // Include this nri if it is currently being tracked.
12341 if (isPerAppTrackedNri(nri)) {
12342 defaultCallbackRequests.add(nri);
12343 continue;
12344 }
12345 // We only track callbacks for requests tracking the default.
12346 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12347 continue;
12348 }
12349 // Include this nri if it will be tracked by the new per-app default requests.
12350 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012351 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012352 if (isNriGoingToBeTracked) {
12353 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012354 }
12355 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012356 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012357 }
12358
James Mattis3ce3d3c2021-02-09 18:18:28 -080012359 /**
12360 * Create nris for those network requests that are currently tracking the default network that
12361 * are being controlled by a per-application default.
12362 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12363 * foundation when creating the nri. Important items include the calling uid's original
12364 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12365 * requests are assumed to have already been validated as needing to be updated.
12366 * @return the Set of nris to use when registering network requests.
12367 */
12368 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12369 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12370 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12371 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12372 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012373 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012374
Chalard Jean9473c982021-07-29 20:03:04 +090012375 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012376 if (trackingNri == mDefaultRequest) {
12377 callbackRequestsToRegister.add(new NetworkRequestInfo(
12378 callbackRequest,
12379 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12380 continue;
12381 }
12382
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012383 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012384 callbackRequestsToRegister.add(new NetworkRequestInfo(
12385 callbackRequest,
12386 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012387 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012388 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012389 }
12390 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012391 }
12392
Chalard Jean17215832021-03-01 14:06:28 +090012393 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12394 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012395 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012396 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012397 }
12398 }
12399
James Mattis45d81842021-01-10 14:24:24 -080012400 /**
12401 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12402 */
12403 @VisibleForTesting
12404 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012405 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080012406 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012407 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080012408 final SparseArray<Set<Integer>> uids =
12409 createUidsFromOemNetworkPreferences(preference);
12410 for (int i = 0; i < uids.size(); i++) {
12411 final int key = uids.keyAt(i);
12412 final Set<Integer> value = uids.valueAt(i);
12413 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
12414 // No need to add an nri without any requests.
12415 if (0 == nri.mRequests.size()) {
12416 continue;
12417 }
12418 nris.add(nri);
12419 }
12420
12421 return nris;
12422 }
12423
12424 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
12425 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070012426 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080012427 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080012428 final List<UserHandle> users =
12429 mContext.getSystemService(UserManager.class).getUserHandles(true);
12430 if (null == users || users.size() == 0) {
12431 if (VDBG || DDBG) {
12432 log("No users currently available for setting the OEM network preference.");
12433 }
James Mattisb6b6a432021-06-01 22:30:36 -070012434 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080012435 }
James Mattis45d81842021-01-10 14:24:24 -080012436 for (final Map.Entry<String, Integer> entry :
12437 preference.getNetworkPreferences().entrySet()) {
12438 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070012439 // Add the rules for all users as this policy is device wide.
12440 for (final UserHandle user : users) {
12441 try {
12442 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
12443 if (!prefToUids.contains(pref)) {
12444 prefToUids.put(pref, new ArraySet<>());
12445 }
12446 prefToUids.get(pref).add(uid);
12447 } catch (PackageManager.NameNotFoundException e) {
12448 // Although this may seem like an error scenario, it is ok that uninstalled
12449 // packages are sent on a network preference as the system will watch for
12450 // package installations associated with this network preference and update
12451 // accordingly. This is done to minimize race conditions on app install.
12452 continue;
James Mattis45d81842021-01-10 14:24:24 -080012453 }
James Mattis45d81842021-01-10 14:24:24 -080012454 }
12455 }
James Mattisb6b6a432021-06-01 22:30:36 -070012456 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080012457 }
12458
12459 private NetworkRequestInfo createNriFromOemNetworkPreferences(
12460 @OemNetworkPreferences.OemNetworkPreference final int preference,
12461 @NonNull final Set<Integer> uids) {
12462 final List<NetworkRequest> requests = new ArrayList<>();
12463 // Requests will ultimately be evaluated by order of insertion therefore it matters.
12464 switch (preference) {
12465 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
12466 requests.add(createUnmeteredNetworkRequest());
12467 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070012468 requests.add(createDefaultInternetRequestForTransport(
12469 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080012470 break;
12471 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
12472 requests.add(createUnmeteredNetworkRequest());
12473 requests.add(createOemPaidNetworkRequest());
12474 break;
12475 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
12476 requests.add(createOemPaidNetworkRequest());
12477 break;
12478 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
12479 requests.add(createOemPrivateNetworkRequest());
12480 break;
James Mattisfa270db2021-05-31 17:11:10 -070012481 case OEM_NETWORK_PREFERENCE_TEST:
12482 requests.add(createUnmeteredNetworkRequest());
12483 requests.add(createTestNetworkRequest());
12484 requests.add(createDefaultRequest());
12485 break;
12486 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
12487 requests.add(createTestNetworkRequest());
12488 break;
James Mattis45d81842021-01-10 14:24:24 -080012489 default:
12490 // This should never happen.
12491 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
12492 + " called with invalid preference of " + preference);
12493 }
12494
James Mattisfa270db2021-05-31 17:11:10 -070012495 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090012496 for (final int uid : uids) {
12497 ranges.add(new UidRange(uid, uid));
12498 }
12499 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080012500 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080012501 }
12502
12503 private NetworkRequest createUnmeteredNetworkRequest() {
12504 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12505 .addCapability(NET_CAPABILITY_NOT_METERED)
12506 .addCapability(NET_CAPABILITY_VALIDATED);
12507 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
12508 }
12509
12510 private NetworkRequest createOemPaidNetworkRequest() {
12511 // NET_CAPABILITY_OEM_PAID is a restricted capability.
12512 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12513 .addCapability(NET_CAPABILITY_OEM_PAID)
12514 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12515 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12516 }
12517
12518 private NetworkRequest createOemPrivateNetworkRequest() {
12519 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
12520 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12521 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
12522 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12523 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12524 }
12525
12526 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070012527 final NetworkCapabilities netcap = new NetworkCapabilities();
12528 netcap.addCapability(NET_CAPABILITY_INTERNET);
12529 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
12530 return netcap;
12531 }
12532
12533 private NetworkRequest createTestNetworkRequest() {
12534 final NetworkCapabilities netcap = new NetworkCapabilities();
12535 netcap.clearAll();
12536 netcap.addTransportType(TRANSPORT_TEST);
12537 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080012538 }
James Mattis47db0582021-01-01 14:13:35 -080012539 }
markchien738ad912021-12-09 18:15:45 +080012540
12541 @Override
12542 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
12543 enforceNetworkStackOrSettingsPermission();
12544
12545 try {
12546 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012547 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012548 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012549 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012550 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012551 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012552 throw new IllegalStateException(e);
12553 }
12554 }
12555
12556 @Override
12557 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
12558 enforceNetworkStackOrSettingsPermission();
12559
12560 try {
12561 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012562 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012563 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012564 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012565 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012566 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012567 throw new IllegalStateException(e);
12568 }
12569 }
markchiene1561fa2021-12-09 22:00:56 +080012570
Chalard Jeanc8fefb32023-09-05 21:41:13 +090012571 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
12572 throws PackageManager.NameNotFoundException {
12573 final PackageManager pm = mContext.getPackageManager();
12574 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
12575 if (appId < Process.FIRST_APPLICATION_UID) {
12576 throw new RuntimeException("Can't set package firewall rule for system app "
12577 + packageName + " with appId " + appId);
12578 }
12579 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
12580 final int uid = uh.getUid(appId);
12581 setUidFirewallRule(chain, uid, rule);
12582 }
12583 return appId;
12584 }
12585
markchiene1561fa2021-12-09 22:00:56 +080012586 @Override
markchien3c04e662022-03-22 16:29:56 +080012587 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080012588 enforceNetworkStackOrSettingsPermission();
12589
markchien3c04e662022-03-22 16:29:56 +080012590 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
12591 int firewallRule = getFirewallRuleType(chain, rule);
12592
12593 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
12594 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
12595 }
12596
markchiene1561fa2021-12-09 22:00:56 +080012597 try {
markchien3c04e662022-03-22 16:29:56 +080012598 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012599 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080012600 throw new IllegalStateException(e);
12601 }
12602 }
markchien98a6f952022-01-13 23:43:53 +080012603
Chalard Jeanc8fefb32023-09-05 21:41:13 +090012604 private int getPackageFirewallRule(final int chain, final String packageName)
12605 throws PackageManager.NameNotFoundException {
12606 final PackageManager pm = mContext.getPackageManager();
12607 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
12608 return getUidFirewallRule(chain, appId);
12609 }
12610
Motomu Utsumi900b8062023-01-19 16:16:49 +090012611 @Override
12612 public int getUidFirewallRule(final int chain, final int uid) {
12613 enforceNetworkStackOrSettingsPermission();
12614 return mBpfNetMaps.getUidRule(chain, uid);
12615 }
12616
markchien3c04e662022-03-22 16:29:56 +080012617 private int getFirewallRuleType(int chain, int rule) {
12618 final int defaultRule;
12619 switch (chain) {
12620 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000012621 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
12622 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000012623 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080012624 defaultRule = FIREWALL_RULE_ALLOW;
12625 break;
12626 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
12627 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
12628 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
12629 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
12630 defaultRule = FIREWALL_RULE_DENY;
12631 break;
12632 default:
12633 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
12634 }
12635 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
12636
12637 return rule;
12638 }
12639
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012640 private void closeSocketsForFirewallChainLocked(final int chain)
12641 throws ErrnoException, SocketException, InterruptedIOException {
12642 if (mBpfNetMaps.isFirewallAllowList(chain)) {
12643 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
12644 // So, close all non-system socket owned by uids that are not explicitly allowed
12645 Set<Range<Integer>> ranges = new ArraySet<>();
12646 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
12647 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
12648 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
12649 } else {
12650 // Denylist means the firewall allows all by default, uids must be explicitly denied
12651 // So, close socket owned by uids that are explicitly denied
12652 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
12653 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
12654 }
12655 }
12656
markchien98a6f952022-01-13 23:43:53 +080012657 @Override
12658 public void setFirewallChainEnabled(final int chain, final boolean enable) {
12659 enforceNetworkStackOrSettingsPermission();
12660
12661 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012662 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012663 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080012664 throw new IllegalStateException(e);
12665 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012666
Chalard Jeandf29a852023-05-29 17:02:43 +090012667 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012668 try {
12669 closeSocketsForFirewallChainLocked(chain);
12670 } catch (ErrnoException | SocketException | InterruptedIOException e) {
12671 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
12672 }
12673 }
markchien98a6f952022-01-13 23:43:53 +080012674 }
12675
markchien00a0bed2022-01-13 23:46:13 +080012676 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012677 public boolean getFirewallChainEnabled(final int chain) {
12678 enforceNetworkStackOrSettingsPermission();
12679
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000012680 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012681 }
12682
12683 @Override
markchien00a0bed2022-01-13 23:46:13 +080012684 public void replaceFirewallChain(final int chain, final int[] uids) {
12685 enforceNetworkStackOrSettingsPermission();
12686
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000012687 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080012688 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080012689
12690 @Override
12691 public IBinder getCompanionDeviceManagerProxyService() {
12692 enforceNetworkStackPermission(mContext);
12693 return mCdmps;
12694 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070012695}