blob: 6024a2a45f726e8df1c622e09bb8ed9c95a5caa7 [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;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090020import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
21import static android.content.pm.PackageManager.FEATURE_WATCH;
22import static android.content.pm.PackageManager.FEATURE_WIFI;
23import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
Chalard Jean9a396cc2018-02-21 18:43:54 +090024import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090025import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
26import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
27import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
28import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
29import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090033import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
34import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000035import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Jeff Sharkey971cd162011-08-29 16:02:57 -070036import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090037import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090038import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090039import static android.net.ConnectivityManager.TYPE_MOBILE;
40import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
41import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
42import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
43import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
44import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
45import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
46import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
47import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
48import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070049import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090050import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070051import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090052import static android.net.ConnectivityManager.TYPE_WIFI;
53import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070054import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070055import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080056import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080057import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080058import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070059import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080060import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040061import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090062import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090063import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090064import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090065import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090066import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
67import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060068import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080070import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090071import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080072import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
73import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080074import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090075import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080076import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
77import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080078import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
79import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
80import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090081import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090082import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060083import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070084import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080085import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090086import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070087import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
88import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +090089import static android.net.shared.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070090import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080091import static android.os.Process.VPN_UID;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +090092import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
Patrick Rohr2857ac42022-01-21 14:58:16 +010093import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070094import static android.system.OsConstants.IPPROTO_TCP;
95import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey07e19362017-10-27 17:22:59 -060096
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +090097import static com.android.net.module.util.DeviceConfigUtils.TETHERING_MODULE_NAME;
98
Cody Kesting83bb5fa2020-01-05 14:06:39 -080099import static java.util.Map.Entry;
100
Chalard Jean5b639762020-03-09 21:25:37 +0900101import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000102import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800103import android.annotation.Nullable;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800104import android.annotation.TargetApi;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800105import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800106import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700107import android.app.PendingIntent;
junyulaie7c7d2a2021-01-26 15:29:15 +0800108import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700109import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800110import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800111import android.content.ContentResolver;
112import android.content.Context;
113import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700114import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800115import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700116import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900117import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900118import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700119import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800120import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800121import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800122import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900123import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800124import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900125import android.net.ConnectivityManager.RestrictBackgroundStatus;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900126import android.net.ConnectivityResources;
paulhu90a7a512021-03-17 17:19:09 +0800127import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900128import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800129import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700130import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900131import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800132import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800133import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800134import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800135import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800136import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900137import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900138import android.net.INetworkMonitor;
139import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900140import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900141import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700142import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800143import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900144import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900145import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900146import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800147import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100148import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800149import android.net.NativeNetworkConfig;
150import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800151import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700152import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700153import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900154import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700155import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800156import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700157import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900158import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900159import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000160import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900161import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700162import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900163import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700164import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900165import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700166import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800167import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900168import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700169import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000170import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800171import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900172import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800173import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400174import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700175import android.net.QosCallbackException;
176import android.net.QosFilter;
177import android.net.QosSocketFilter;
178import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700179import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800180import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800181import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800182import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900183import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400184import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800185import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800186import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400187import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800188import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900189import android.net.VpnTransportInfo;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900190import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900191import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800192import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900193import android.net.networkstack.ModuleNetworkStackClient;
194import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900195import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800196import android.net.resolv.aidl.DnsHealthEventParcel;
197import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
198import android.net.resolv.aidl.Nat64PrefixEventParcel;
199import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900200import android.net.shared.PrivateDnsConfig;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100201import android.net.util.InterfaceParams;
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900202import android.net.util.MultinetworkPolicyTracker;
lucaslinb961efc2021-01-21 02:03:17 +0800203import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800204import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800205import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700206import android.os.Bundle;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800207import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700208import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700209import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800210import android.os.Looper;
211import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700212import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700213import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900214import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800215import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700216import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700217import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800218import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700219import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900220import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900221import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700222import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700223import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400224import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800225import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900226import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700227import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700228import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700229import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800230import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900231import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000232import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600233import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900234import android.util.Pair;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700235import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700236import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800237
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900238import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400239import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400240import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700241import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900242import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800243import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900244import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800245import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900246import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900247import com.android.net.module.util.DeviceConfigUtils;
Chalard Jean79162542020-08-19 16:07:22 +0900248import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
249import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900250import com.android.net.module.util.LocationPermissionChecker;
lifrade6c2a2021-03-04 14:08:08 +0800251import com.android.net.module.util.NetworkCapabilitiesUtils;
paulhudf23d662021-01-25 18:53:17 +0800252import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100253import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000254import com.android.net.module.util.netlink.InetDiagMessage;
Chalard Jean7284daa2019-05-30 14:58:29 +0900255import com.android.server.connectivity.AutodestructReference;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800256import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900257import com.android.server.connectivity.ConnectivityFlags;
Erik Kline32120082017-12-13 19:40:49 +0900258import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500259import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700260import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900261import com.android.server.connectivity.FullScore;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900262import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100263import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700264import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700265import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600266import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900267import com.android.server.connectivity.NetworkNotificationManager;
268import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900269import com.android.server.connectivity.NetworkOffer;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900270import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700271import com.android.server.connectivity.PermissionMonitor;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800272import com.android.server.connectivity.ProfileNetworkPreferenceList;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900273import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700274import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800275import com.android.server.connectivity.UidRangeUtils;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600276
Josh Gao461a1222020-06-16 15:58:11 -0700277import libcore.io.IoUtils;
278
The Android Open Source Project28527d22009-03-03 19:31:44 -0800279import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100280import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800281import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900282import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700283import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700284import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900285import java.net.InetSocketAddress;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700286import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700287import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700288import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700289import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800290import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900291import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800292import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700293import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700294import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700295import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700296import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900297import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700298import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900299import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600300import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900301import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600302import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900303import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800304
305/**
306 * @hide
307 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800308public class ConnectivityService extends IConnectivityManager.Stub
309 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900310 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800311
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900312 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900313 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900314 private static final String NETWORK_ARG = "networks";
315 private static final String REQUEST_ARG = "requests";
Erik Klined364a242017-05-12 16:52:48 +0900316
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900317 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900318 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
319 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800320
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900321 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700322
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100323 /**
324 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
325 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800326 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100327 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
328 * (preferably via runtime resource overlays).
329 */
330 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
331 "http://connectivitycheck.gstatic.com/generate_204";
332
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700333 // TODO: create better separation between radio types and network types
334
Robert Greenwalt2034b912009-08-12 16:08:25 -0700335 // how long to wait before switching back to a radio's default network
336 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
337 // system property that can override the above value
338 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
339 "android.telephony.apn-restore";
340
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900341 // How long to wait before putting up a "This network doesn't have an Internet connection,
342 // connect anyway?" dialog after the user selects a network that doesn't validate.
343 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
344
junyulai0ac374f2020-12-14 18:41:52 +0800345 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900346 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
347 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800348 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700349
350 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900351 @VisibleForTesting
352 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700353
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900354 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700355 @VisibleForTesting
356 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900357
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900358 @VisibleForTesting
359 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800360 @VisibleForTesting
361 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900362 // True if the cell radio of the device is capable of time-sharing.
363 @VisibleForTesting
364 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900365
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800366 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800367 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800368 private final int mReleasePendingIntentDelayMs;
369
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900370 private MockableSystemProperties mSystemProperties;
371
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000372 @VisibleForTesting
373 protected final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700374
Chalard Jean9473c982021-07-29 20:03:04 +0900375 @VisibleForTesting
376 final PerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700377 @VisibleForTesting
378 final PerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700379
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900380 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700381
junyulaif2c67e42018-08-07 19:50:45 +0800382 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000383 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
384 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800385 */
Sudheer Shanka9967d462021-03-18 19:09:25 +0000386 private SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800387
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900388 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900389 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000390 // The Context is created for UserHandle.ALL.
391 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900392 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900393 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700394 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700395 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800396
Chenbo Feng15416292018-11-08 17:36:21 -0800397 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800398 protected IDnsResolver mDnsResolver;
399 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800400 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700401 private DscpPolicyTracker mDscpPolicyTracker = null;
junyulaie7c7d2a2021-01-26 15:29:15 +0800402 private NetworkStatsManager mStatsManager;
paulhu9a9f71b2020-12-29 18:15:13 +0800403 private NetworkPolicyManager mPolicyManager;
lucaslin66f44212021-02-23 01:12:55 +0800404 private final NetdCallback mNetdCallback;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800405 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700406
Benedict Wong493e04b2018-11-09 14:45:34 -0800407 /**
408 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
409 * instances.
410 */
411 @GuardedBy("mTNSLock")
412 private TestNetworkService mTNS;
413
414 private final Object mTNSLock = new Object();
415
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700416 private String mCurrentTcpBufferSizes;
417
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900418 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifraf3a3492021-03-10 13:58:14 +0800419 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900420
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500421 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400422 // Tear down networks that have no chance (e.g. even if validated) of becoming
423 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500424 // all networks have been rematched against all NetworkRequests.
425 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400426 // Don't reap networks. This should be passed when some networks have not yet been
427 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500428 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900429 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500430
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900431 private enum UnneededFor {
432 LINGER, // Determine whether this network is unneeded and should be lingered.
433 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
434 }
435
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700436 /**
paulhuaa0743d2021-05-26 21:56:03 +0800437 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800438 * should have priority. The order is passed to netd which will use it together
439 * with UID ranges to generate the corresponding IP rule. This serves to
440 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800441 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800442 * Order ints passed to netd must be in the 0~999 range. Larger values code for
paulhuaa0743d2021-05-26 21:56:03 +0800443 * a lower priority, {@see NativeUidRangeConfig}
paulhue9913722021-05-26 15:19:20 +0800444 *
paulhu48291862021-07-14 14:53:57 +0800445 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
446 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800447 */
paulhu48291862021-07-14 14:53:57 +0800448 // Used when sending to netd to code for "no order".
449 static final int PREFERENCE_ORDER_NONE = 0;
450 // Order for requests that don't code for a per-app preference. As it is
451 // out of the valid range, the corresponding order should be
452 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800453 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800454 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800455 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800456 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
457 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800458 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800459 static final int PREFERENCE_ORDER_OEM = 10;
460 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800461 // See {@link #setProfileNetworkPreference}.
462 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800463 static final int PREFERENCE_ORDER_PROFILE = 20;
464 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800465 // better scores are connected.
466 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800467 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800468 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900469 // Preference order that signifies the network shouldn't be set as a default network for
470 // the UIDs, only give them access to it. TODO : replace this with a boolean
471 // in NativeUidRangeConfig
472 @VisibleForTesting
473 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
474 // Bound for the lowest valid preference order.
475 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800476
477 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700478 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700479 * from one net to another. Clear happens when we get a new
480 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
481 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700482 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700483 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700484
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700485 /**
486 * used internally to reload global proxy settings
487 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700488 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700489
Robert Greenwalt34848c02011-03-25 13:09:25 -0700490 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400491 * PAC manager has received new port.
492 */
493 private static final int EVENT_PROXY_HAS_CHANGED = 16;
494
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700495 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900496 * used internally when registering NetworkProviders
497 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700498 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900499 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700500
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700501 /**
502 * used internally when registering NetworkAgents
503 * obj = Messenger
504 */
505 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
506
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700507 /**
508 * used to add a network request
509 * includes a NetworkRequestInfo
510 */
511 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
512
513 /**
514 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900515 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700516 * cancel it.
517 * includes a NetworkRequestInfo
518 */
519 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
520
521 /**
522 * used to add a network listener - no request
523 * includes a NetworkRequestInfo
524 */
525 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
526
527 /**
528 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400529 * arg1 = UID of caller
530 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700531 */
532 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
533
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700534 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900535 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700536 * obj = Messenger
537 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900538 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700539
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700540 /**
541 * used internally to expire a wakelock when transitioning
542 * from one net to another. Expire happens when we fail to find
543 * a new network (typically after 1 minute) -
544 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
545 * a replacement network.
546 */
547 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
548
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700549 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800550 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400551 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800552 */
553 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
554
555 /**
556 * used to remove a pending intent and its associated network request.
557 * arg1 = UID of caller
558 * obj = PendingIntent
559 */
560 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
561
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900562 /**
563 * used to specify whether a network should be used even if unvalidated.
564 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
565 * arg2 = whether to remember this choice in the future (1 or 0)
566 * obj = network
567 */
568 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
569
570 /**
571 * used to ask the user to confirm a connection to an unvalidated network.
572 * obj = network
573 */
574 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700575
Erik Kline05f2b402015-04-30 12:58:40 +0900576 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700577 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900578 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700579 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900580
Paul Jensenc8873fc2015-06-17 14:15:39 -0400581 /**
582 * used to add a network listener with a pending intent
583 * obj = NetworkRequestInfo
584 */
585 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
586
Hugo Benichid6b510a2017-04-06 17:22:18 +0900587 /**
588 * used to specify whether a network should not be penalized when it becomes unvalidated.
589 */
590 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
591
592 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700593 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900594 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700595 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900596
Erik Kline31b4a9e2018-01-11 21:07:29 +0900597 // Handle changes in Private DNS settings.
598 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
599
dalyk1720e542018-03-05 12:42:22 -0500600 // Handle private DNS validation status updates.
601 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
602
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800603 /**
604 * used to remove a network request, either a listener or a real request and call unavailable
605 * arg1 = UID of caller
606 * obj = NetworkRequest
607 */
608 private static final int EVENT_RELEASE_NETWORK_REQUEST_AND_CALL_UNAVAILABLE = 39;
609
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900610 /**
611 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
612 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800613 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
614 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
615 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900616 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900617 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900618
619 /**
620 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
621 * config was resolved.
622 * obj = PrivateDnsConfig
623 * arg2 = netid
624 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900625 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900626
627 /**
628 * Request ConnectivityService display provisioning notification.
629 * arg1 = Whether to make the notification visible.
630 * arg2 = NetID.
631 * obj = Intent to be launched when notification selected by user, null if !arg1.
632 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900633 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900634
635 /**
lucaslin2240ef62019-03-12 13:08:03 +0800636 * Used to specify whether a network should be used even if connectivity is partial.
637 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
638 * false)
639 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
640 * obj = network
641 */
lucaslin444d43a2020-02-20 16:56:59 +0800642 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800643
644 /**
lucasline117e2e2019-10-22 18:27:33 +0800645 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
646 * Both of the arguments are bitmasks, and the value of bits come from
647 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
648 * arg1 = A bitmask to describe which probes are completed.
649 * arg2 = A bitmask to describe which probes are successful.
650 */
lucaslin444d43a2020-02-20 16:56:59 +0800651 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800652
653 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900654 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
655 * arg1 = unused
656 * arg2 = netId
657 * obj = captive portal data
658 */
lucaslin444d43a2020-02-20 16:56:59 +0800659 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900660
661 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900662 * Used by setRequireVpnForUids.
663 * arg1 = whether the specified UID ranges are required to use a VPN.
664 * obj = Array of UidRange objects.
665 */
666 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
667
668 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900669 * Used internally when setting the default networks for OemNetworkPreferences.
670 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800671 */
672 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
673
674 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800675 * Used to indicate the system default network becomes active.
676 */
677 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
678
679 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900680 * Used internally when setting a network preference for a user profile.
681 * obj = Pair<ProfileNetworkPreference, Listener>
682 */
683 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
684
685 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000686 * Event to specify that reasons for why an uid is blocked changed.
687 * arg1 = uid
688 * arg2 = blockedReasons
689 */
690 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
691
692 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900693 * Event to register a new network offer
694 * obj = NetworkOffer
695 */
696 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
697
698 /**
699 * Event to unregister an existing network offer
700 * obj = INetworkOfferCallback
701 */
702 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
703
704 /**
paulhu51f77dc2021-06-07 02:34:20 +0000705 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
706 */
707 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
708
709 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800710 * Event to set temporary allow bad wifi within a limited time to override
711 * {@code config_networkAvoidBadWifi}.
712 */
713 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
714
715 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100716 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
717 */
718 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
719
720 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900721 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
722 * should be shown.
723 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900724 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900725
726 /**
727 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
728 * should be hidden.
729 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900730 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900731
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800732 /**
733 * The maximum alive time to allow bad wifi configuration for testing.
734 */
735 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
736
Patrick Rohr2857ac42022-01-21 14:58:16 +0100737 /**
738 * The priority of the tc police rate limiter -- smaller value is higher priority.
739 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
740 */
741 private static final short TC_PRIO_POLICE = 1;
742
743 /**
744 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
745 */
746 private static final String TC_POLICE_BPF_PROG_PATH =
747 "/sys/fs/bpf/prog_netd_schedact_ingress_account";
748
Hugo Benichi47011212017-03-30 10:46:05 +0900749 private static String eventName(int what) {
750 return sMagicDecoderRing.get(what, Integer.toString(what));
751 }
752
paulhua10d8212020-11-10 15:32:56 +0800753 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900754 final DnsResolverServiceManager dsm = context.getSystemService(
755 DnsResolverServiceManager.class);
756 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800757 }
758
Cody Kesting73708bf2019-12-18 10:57:50 -0800759 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900760 @VisibleForTesting
761 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700762 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700763 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700764 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700765 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800766 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
767 @VisibleForTesting
768 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
769
Erik Kline32120082017-12-13 19:40:49 +0900770 private final DnsManager mDnsManager;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900771 private final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700772
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400773 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800774 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400775
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700776 private PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800777 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700778
Chalard Jean5d70ba42018-06-07 16:44:04 +0900779 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
780 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000781 @VisibleForTesting
782 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400783
Erik Kline05f2b402015-04-30 12:58:40 +0900784 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700785
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400786 private UserManager mUserManager;
787
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700788 // the set of network types that can only be enabled by system/sig apps
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900789 private List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700790
Valentin Iftime9fa35092019-09-24 13:32:13 +0200791 private Set<String> mWolSupportedInterfaces;
792
Roshan Pius08c94fb2020-01-16 12:17:17 -0800793 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800794 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800795 private final AppOpsManager mAppOpsManager;
796
797 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400798
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900799 private KeepaliveTracker mKeepaliveTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700800 private QosCallbackTracker mQosCallbackTracker;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900801 private NetworkNotificationManager mNotifier;
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +0900802 private LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900803
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700804 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800805 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700806
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900807 // Sequence number for NetworkProvider IDs.
808 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
809 NetworkProvider.FIRST_PROVIDER_ID);
810
Erik Klineedf878b2015-07-09 18:24:03 +0900811 // NetworkRequest activity String log entries.
812 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
813 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
814
Hugo Benichid159fdd2016-07-11 11:05:12 +0900815 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900816 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900817 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
818
Hugo Benichi47011212017-03-30 10:46:05 +0900819 private static final int MAX_WAKELOCK_LOGS = 20;
820 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900821 private int mTotalWakelockAcquisitions = 0;
822 private int mTotalWakelockReleases = 0;
823 private long mTotalWakelockDurationMs = 0;
824 private long mMaxWakelockDurationMs = 0;
825 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900826
Hugo Benichi208c0102016-07-28 17:53:06 +0900827 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900828
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700829 @GuardedBy("mBandwidthRequests")
830 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
831
Erik Kline95ecfee2016-10-02 18:02:14 +0900832 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900833 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900834
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900835 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800836 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
837 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800838
Patrick Rohr2857ac42022-01-21 14:58:16 +0100839 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
840 // configured via {@link
841 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
842 // Only the handler thread is allowed to access this field.
843 private long mIngressRateLimit = -1;
844
Robert Greenwalt802c1102014-06-02 15:32:02 -0700845 /**
846 * Implements support for the legacy "one network per network type" model.
847 *
848 * We used to have a static array of NetworkStateTrackers, one for each
849 * network type, but that doesn't work any more now that we can have,
850 * for example, more that one wifi network. This class stores all the
851 * NetworkAgentInfo objects that support a given type, but the legacy
852 * API will only see the first one.
853 *
854 * It serves two main purposes:
855 *
856 * 1. Provide information about "the network for a given type" (since this
857 * API only supports one).
858 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
859 * the first network for a given type changes, or if the default network
860 * changes.
861 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900862 @VisibleForTesting
863 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900864
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900865 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900866 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900867
Robert Greenwalt802c1102014-06-02 15:32:02 -0700868 /**
869 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
870 * Each list holds references to all NetworkAgentInfos that are used to
871 * satisfy requests for that network type.
872 *
873 * This array is built out at startup such that an unsupported network
874 * doesn't get an ArrayList instance, making this a tristate:
875 * unsupported, supported but not active and active.
876 *
877 * The actual lists are populated when we scan the network types that
878 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900879 *
880 * Threading model:
881 * - addSupportedType() is only called in the constructor
882 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
883 * They are therefore not thread-safe with respect to each other.
884 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
885 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900886 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900887 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700888 */
Hugo Benichi389633f2016-06-21 09:48:07 +0900889 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900890 @NonNull
891 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700892
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900893 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
894 // an entry have no timer (equivalent to -1). Lazily loaded.
895 @NonNull
896 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
897
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900898 LegacyTypeTracker(@NonNull ConnectivityService service) {
899 mService = service;
900 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700901 }
902
Chiachang Wang3bc52762021-11-25 14:17:57 +0800903 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
904 // addressed.
905 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900906 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
907 final PackageManager pm = ctx.getPackageManager();
908 if (pm.hasSystemFeature(FEATURE_WIFI)) {
909 addSupportedType(TYPE_WIFI);
910 }
911 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
912 addSupportedType(TYPE_WIFI_P2P);
913 }
914 if (tm.isDataCapable()) {
915 // Telephony does not have granular support for these types: they are either all
916 // supported, or none is supported
917 addSupportedType(TYPE_MOBILE);
918 addSupportedType(TYPE_MOBILE_MMS);
919 addSupportedType(TYPE_MOBILE_SUPL);
920 addSupportedType(TYPE_MOBILE_DUN);
921 addSupportedType(TYPE_MOBILE_HIPRI);
922 addSupportedType(TYPE_MOBILE_FOTA);
923 addSupportedType(TYPE_MOBILE_IMS);
924 addSupportedType(TYPE_MOBILE_CBS);
925 addSupportedType(TYPE_MOBILE_IA);
926 addSupportedType(TYPE_MOBILE_EMERGENCY);
927 }
928 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
929 addSupportedType(TYPE_BLUETOOTH);
930 }
931 if (pm.hasSystemFeature(FEATURE_WATCH)) {
932 // TYPE_PROXY is only used on Wear
933 addSupportedType(TYPE_PROXY);
934 }
935 // Ethernet is often not specified in the configs, although many devices can use it via
936 // USB host adapters. Add it as long as the ethernet service is here.
937 if (ctx.getSystemService(Context.ETHERNET_SERVICE) != null) {
938 addSupportedType(TYPE_ETHERNET);
939 }
940
941 // Always add TYPE_VPN as a supported type
942 addSupportedType(TYPE_VPN);
943 }
944
945 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700946 if (mTypeLists[type] != null) {
947 throw new IllegalStateException(
948 "legacy list for type " + type + "already initialized");
949 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900950 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -0700951 }
952
Robert Greenwalt802c1102014-06-02 15:32:02 -0700953 public boolean isTypeSupported(int type) {
954 return isNetworkTypeValid(type) && mTypeLists[type] != null;
955 }
956
957 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +0900958 synchronized (mTypeLists) {
959 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
960 return mTypeLists[type].get(0);
961 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700962 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900963 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700964 }
965
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900966 public int getRestoreTimerForType(int type) {
967 synchronized (mTypeLists) {
968 if (mRestoreTimers == null) {
969 mRestoreTimers = loadRestoreTimers();
970 }
971 return mRestoreTimers.getOrDefault(type, -1);
972 }
973 }
974
975 private ArrayMap<Integer, Integer> loadRestoreTimers() {
976 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900977 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900978 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
979 for (final String config : configs) {
980 final String[] splits = TextUtils.split(config, ",");
981 if (splits.length != 2) {
982 logwtf("Invalid restore timer token count: " + config);
983 continue;
984 }
985 try {
986 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
987 } catch (NumberFormatException e) {
988 logwtf("Invalid restore timer number format: " + config, e);
989 }
990 }
991 return ret;
992 }
993
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -0700994 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +0900995 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900996 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +0900997 log("Sending " + state
998 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +0900999 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001000 }
1001 }
1002
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001003 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1004 // network type, to preserve previous behaviour.
1005 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1006 if (vpnNai != mService.getLegacyLockdownNai()) return;
1007
1008 if (vpnNai.declaredUnderlyingNetworks == null
1009 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1010 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1011 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1012 return;
1013 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001014 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001015 vpnNai.declaredUnderlyingNetworks[0]);
1016 if (underlyingNai == null) return;
1017
1018 final int type = underlyingNai.networkInfo.getType();
1019 final DetailedState state = DetailedState.CONNECTED;
1020 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1021 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1022 }
1023
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001024 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001025 public void add(int type, NetworkAgentInfo nai) {
1026 if (!isTypeSupported(type)) {
1027 return; // Invalid network type.
1028 }
1029 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1030
1031 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1032 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001033 return;
1034 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001035 synchronized (mTypeLists) {
1036 list.add(nai);
1037 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001038
Chalard Jean5b409c72021-02-04 13:12:59 +09001039 // Send a broadcast if this is the first network of its type or if it's the default.
1040 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001041
1042 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1043 // to preserve previous behaviour.
1044 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001045 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001046 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1047 mService.sendLegacyNetworkBroadcast(nai, state, type);
1048 }
1049
1050 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1051 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001052 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001053 }
1054
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001055 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001056 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001057 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1058 if (list == null || list.isEmpty()) {
1059 return;
1060 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001061 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001062
Hugo Benichi389633f2016-06-21 09:48:07 +09001063 synchronized (mTypeLists) {
1064 if (!list.remove(nai)) {
1065 return;
1066 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001067 }
1068
Lorenzo Colitti49767722015-05-01 00:30:10 +09001069 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001070 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1071 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001072 }
1073
1074 if (!list.isEmpty() && wasFirstNetwork) {
1075 if (DBG) log("Other network available for type " + type +
1076 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001077 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001078 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001079 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001080 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001081 }
1082 }
1083
1084 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001085 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1086 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001087 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001088 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001089 }
1090 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001091
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001092 // send out another legacy broadcast - currently only used for suspend/unsuspend
1093 // toggle
1094 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001095 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001096 final DetailedState state = nai.networkInfo.getDetailedState();
1097 for (int type = 0; type < mTypeLists.length; type++) {
1098 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001099 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001100 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001101 if (isFirst || contains && isDefault) {
1102 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001103 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001104 }
1105 }
1106 }
1107
Robert Greenwalt94e22142014-07-30 16:31:24 -07001108 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001109 pw.println("mLegacyTypeTracker:");
1110 pw.increaseIndent();
1111 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001112 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001113 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001114 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001115 pw.println();
1116 pw.println("Current state:");
1117 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001118 synchronized (mTypeLists) {
1119 for (int type = 0; type < mTypeLists.length; type++) {
1120 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1121 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001122 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001123 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001124 }
1125 }
1126 pw.decreaseIndent();
1127 pw.decreaseIndent();
1128 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001129 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001130 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001131 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001132
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001133 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001134 /**
1135 * Helper class which parses out priority arguments and dumps sections according to their
1136 * priority. If priority arguments are omitted, function calls the legacy dump command.
1137 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001138 private class LocalPriorityDump {
1139 private static final String PRIORITY_ARG = "--dump-priority";
1140 private static final String PRIORITY_ARG_HIGH = "HIGH";
1141 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1142
1143 LocalPriorityDump() {}
1144
1145 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1146 doDump(fd, pw, new String[] {DIAG_ARG});
1147 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001148 }
1149
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001150 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1151 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001152 }
1153
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001154 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1155 if (args == null) {
1156 dumpNormal(fd, pw, args);
1157 return;
1158 }
1159
1160 String priority = null;
1161 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1162 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1163 argIndex++;
1164 priority = args[argIndex];
1165 }
1166 }
1167
1168 if (PRIORITY_ARG_HIGH.equals(priority)) {
1169 dumpHigh(fd, pw);
1170 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1171 dumpNormal(fd, pw, args);
1172 } else {
1173 // ConnectivityService publishes binder service using publishBinderService() with
1174 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001175 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1176 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001177 // TODO: Integrate into signal dump.
1178 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001179 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001180 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001181 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001182
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001183 /**
Daniel Brightf9e945b2020-06-15 16:10:01 -07001184 * Keeps track of the number of requests made under different uids.
1185 */
1186 public static class PerUidCounter {
1187 private final int mMaxCountPerUid;
1188
1189 // Map from UID to number of NetworkRequests that UID has filed.
James Mattis20a4a8b2021-03-28 17:41:09 -07001190 @VisibleForTesting
Daniel Brightf9e945b2020-06-15 16:10:01 -07001191 @GuardedBy("mUidToNetworkRequestCount")
James Mattis20a4a8b2021-03-28 17:41:09 -07001192 final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
Daniel Brightf9e945b2020-06-15 16:10:01 -07001193
1194 /**
1195 * Constructor
1196 *
1197 * @param maxCountPerUid the maximum count per uid allowed
1198 */
1199 public PerUidCounter(final int maxCountPerUid) {
1200 mMaxCountPerUid = maxCountPerUid;
1201 }
1202
1203 /**
1204 * Increments the request count of the given uid. Throws an exception if the number
1205 * of open requests for the uid exceeds the value of maxCounterPerUid which is the value
1206 * passed into the constructor. see: {@link #PerUidCounter(int)}.
1207 *
1208 * @throws ServiceSpecificException with
1209 * {@link ConnectivityManager.Errors.TOO_MANY_REQUESTS} if the number of requests for
1210 * the uid exceed the allowed number.
1211 *
1212 * @param uid the uid that the request was made under
1213 */
1214 public void incrementCountOrThrow(final int uid) {
1215 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001216 incrementCountOrThrow(uid, 1 /* numToIncrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001217 }
1218 }
1219
James Mattis20a4a8b2021-03-28 17:41:09 -07001220 private void incrementCountOrThrow(final int uid, final int numToIncrement) {
1221 final int newRequestCount =
1222 mUidToNetworkRequestCount.get(uid, 0) + numToIncrement;
Chalard Jean9473c982021-07-29 20:03:04 +09001223 if (newRequestCount >= mMaxCountPerUid
1224 // HACK : the system server is allowed to go over the request count limit
1225 // when it is creating requests on behalf of another app (but not itself,
1226 // so it can still detect its own request leaks). This only happens in the
1227 // per-app API flows in which case the old requests for that particular
1228 // UID will be removed soon.
1229 // TODO : instead of this hack, addPerAppDefaultNetworkRequests and other
1230 // users of transact() should unregister the requests to decrease the count
1231 // before they increase it again by creating a new NRI. Then remove the
1232 // transact() method.
1233 && (Process.myUid() == uid || Process.myUid() != Binder.getCallingUid())) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001234 throw new ServiceSpecificException(
Chalard Jean9473c982021-07-29 20:03:04 +09001235 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
1236 "Uid " + uid + " exceeded its allotted requests limit");
James Mattis20a4a8b2021-03-28 17:41:09 -07001237 }
1238 mUidToNetworkRequestCount.put(uid, newRequestCount);
1239 }
1240
Daniel Brightf9e945b2020-06-15 16:10:01 -07001241 /**
1242 * Decrements the request count of the given uid.
1243 *
1244 * @param uid the uid that the request was made under
1245 */
1246 public void decrementCount(final int uid) {
1247 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001248 decrementCount(uid, 1 /* numToDecrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001249 }
1250 }
James Mattis20a4a8b2021-03-28 17:41:09 -07001251
1252 private void decrementCount(final int uid, final int numToDecrement) {
1253 final int newRequestCount =
1254 mUidToNetworkRequestCount.get(uid, 0) - numToDecrement;
1255 if (newRequestCount < 0) {
1256 logwtf("BUG: too small request count " + newRequestCount + " for UID " + uid);
1257 } else if (newRequestCount == 0) {
1258 mUidToNetworkRequestCount.delete(uid);
1259 } else {
1260 mUidToNetworkRequestCount.put(uid, newRequestCount);
1261 }
1262 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07001263 }
1264
1265 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001266 * Dependencies of ConnectivityService, for injection in tests.
1267 */
1268 @VisibleForTesting
1269 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001270 public int getCallingUid() {
1271 return Binder.getCallingUid();
1272 }
1273
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001274 /**
1275 * Get system properties to use in ConnectivityService.
1276 */
1277 public MockableSystemProperties getSystemProperties() {
1278 return new MockableSystemProperties();
1279 }
1280
1281 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001282 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1283 */
1284 public ConnectivityResources getResources(@NonNull Context ctx) {
1285 return new ConnectivityResources(ctx);
1286 }
1287
1288 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001289 * Create a HandlerThread to use in ConnectivityService.
1290 */
1291 public HandlerThread makeHandlerThread() {
1292 return new HandlerThread("ConnectivityServiceThread");
1293 }
1294
1295 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001296 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001297 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001298 public NetworkStackClientBase getNetworkStack() {
1299 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001300 }
1301
1302 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001303 * @see ProxyTracker
1304 */
1305 public ProxyTracker makeProxyTracker(@NonNull Context context,
1306 @NonNull Handler connServiceHandler) {
1307 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1308 }
1309
1310 /**
1311 * @see NetIdManager
1312 */
1313 public NetIdManager makeNetIdManager() {
1314 return new NetIdManager();
1315 }
1316
1317 /**
1318 * @see NetworkUtils#queryUserAccess(int, int)
1319 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001320 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1321 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001322 }
1323
1324 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001325 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1326 * requires CAP_NET_ADMIN, which the unit tests do not have.
1327 */
1328 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1329 InetSocketAddress remote) {
1330 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1331 }
1332
1333 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001334 * @see MultinetworkPolicyTracker
1335 */
1336 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1337 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1338 return new MultinetworkPolicyTracker(c, h, r);
1339 }
1340
Aaron Huang330a4c02020-10-27 03:36:19 +08001341 /**
1342 * @see BatteryStatsManager
1343 */
1344 public void reportNetworkInterfaceForTransports(Context context, String iface,
1345 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001346 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001347 context.getSystemService(BatteryStatsManager.class);
1348 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1349 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001350
1351 public boolean getCellular464XlatEnabled() {
1352 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1353 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001354
1355 /**
1356 * @see PendingIntent#intentFilterEquals
1357 */
1358 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1359 return a.intentFilterEquals(b);
1360 }
1361
1362 /**
1363 * @see LocationPermissionChecker
1364 */
1365 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1366 return new LocationPermissionChecker(context);
1367 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001368
1369 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001370 * @see CarrierPrivilegeAuthenticator
1371 */
1372 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1373 @NonNull final Context context, @NonNull final TelephonyManager tm) {
1374 if (SdkLevel.isAtLeastT()) {
1375 return new CarrierPrivilegeAuthenticator(context, tm);
1376 } else {
1377 return null;
1378 }
1379 }
1380
1381 /**
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001382 * @see DeviceConfigUtils#isFeatureEnabled
1383 */
1384 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1385 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1386 TETHERING_MODULE_NAME, defaultEnabled);
1387 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001388
1389 /**
1390 * Get the BpfNetMaps implementation to use in ConnectivityService.
1391 * @param netd
1392 * @return BpfNetMaps implementation.
1393 */
1394 public BpfNetMaps getBpfNetMaps(INetd netd) {
1395 return new BpfNetMaps(netd);
1396 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001397
1398 /**
1399 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1400 */
1401 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1402 final InterfaceParams params = InterfaceParams.getByName(iface);
1403 if (params == null) {
1404 // the interface might have disappeared.
1405 logw("Failed to get interface params for interface " + iface);
1406 return;
1407 }
1408 try {
1409 // converting rateInBytesPerSecond from long to int is safe here because the
1410 // setting's range is limited to INT_MAX.
1411 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
1412 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1413 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1414 } catch (IOException e) {
1415 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1416 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1417 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1418 + ") failure: ", e);
1419 }
1420 }
1421
1422 /**
1423 * Wraps {@link TcUtils#tcFilterDelDev}
1424 */
1425 public void disableIngressRateLimit(String iface) {
1426 final InterfaceParams params = InterfaceParams.getByName(iface);
1427 if (params == null) {
1428 // the interface might have disappeared.
1429 logw("Failed to get interface params for interface " + iface);
1430 return;
1431 }
1432 try {
1433 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1434 } catch (IOException e) {
1435 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1436 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1437 }
1438 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001439 }
1440
junyulaie7c7d2a2021-01-26 15:29:15 +08001441 public ConnectivityService(Context context) {
1442 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001443 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1444 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001445 }
1446
1447 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001448 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1449 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001450 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001451
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001452 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001453 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001454 mSystemProperties = mDeps.getSystemProperties();
1455 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001456 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001457 mResources = deps.getResources(mContext);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001458 mNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_UID);
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09001459 mSystemNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001460
Hugo Benichi208c0102016-07-28 17:53:06 +09001461 mMetricsLog = logger;
Chalard Jean96a4f4b2019-12-10 22:16:53 +09001462 mNetworkRanker = new NetworkRanker();
James Mattis45d81842021-01-10 14:24:24 -08001463 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1464 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001465 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001466 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001467 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001468 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1469 mDefaultNetworkRequests.add(mDefaultRequest);
1470 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001471
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001472 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001473 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001474
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001475 // The default WiFi request is a background request so that apps using WiFi are
1476 // migrated to a better network (typically ethernet) when one comes up, instead
1477 // of staying on WiFi forever.
1478 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1479 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1480
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001481 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1482 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1483 NetworkRequest.Type.BACKGROUND_REQUEST);
1484
Chalard Jean0702f982021-09-16 21:50:07 +09001485 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1486 // TODO: Consider making the timer customizable.
1487 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1488 mCellularRadioTimesharingCapable =
1489 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1490
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001491 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001492 mHandlerThread.start();
1493 mHandler = new InternalHandler(mHandlerThread.getLooper());
1494 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001495 mConnectivityDiagnosticsHandler =
1496 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001497
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001498 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001499 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001500
junyulaie7c7d2a2021-01-26 15:29:15 +08001501 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001502 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001503 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001504 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001505
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001506 mNetd = netd;
Wayne Ma2fde98c2022-01-17 18:04:05 +08001507 mBpfNetMaps = mDeps.getBpfNetMaps(netd);
Wink Saville32506bc2013-06-29 21:10:57 -07001508 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001509 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001510 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001511 mCarrierPrivilegeAuthenticator =
1512 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001513
Sudheer Shanka9967d462021-03-18 19:09:25 +00001514 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001515 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1516 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001517 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001518
1519 final PowerManager powerManager = (PowerManager) context.getSystemService(
1520 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001521 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001522 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001523
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001524 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1525 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001526 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001527 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001528 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001529 mProtectedNetworks.add(p);
1530 } else {
1531 if (DBG) loge("Ignoring protectedNetwork " + p);
1532 }
1533 }
1534
soma, kawata29444ae2019-05-23 09:30:40 +09001535 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1536
Wayne Ma2fde98c2022-01-17 18:04:05 +08001537 mPermissionMonitor = new PermissionMonitor(mContext, mNetd, mBpfNetMaps);
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -07001538
James Mattis02220e22021-03-13 19:27:21 -08001539 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001540 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001541 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001542 final IntentFilter userIntentFilter = new IntentFilter();
1543 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1544 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1545 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1546 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001547
James Mattis02220e22021-03-13 19:27:21 -08001548 // Listen to package add/removes for netd
1549 final IntentFilter packageIntentFilter = new IntentFilter();
1550 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1551 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1552 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1553 packageIntentFilter.addDataScheme("package");
1554 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001555 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001556
lucaslind5c2d072021-02-20 18:59:47 +08001557 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001558
lucaslin66f44212021-02-23 01:12:55 +08001559 mNetdCallback = new NetdCallback();
1560 try {
1561 mNetd.registerUnsolicitedEventListener(mNetdCallback);
1562 } catch (RemoteException | ServiceSpecificException e) {
1563 loge("Error registering event listener :" + e);
1564 }
1565
Erik Kline05f2b402015-04-30 12:58:40 +09001566 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1567 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001568
junyulai7e06ad42019-03-04 22:45:36 +08001569 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001570 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001571 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001572
1573 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001574 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001575 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1576 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001577 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001578 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1579 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001580
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001581 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001582 mContext, mHandler, () -> updateAvoidBadWifi());
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001583 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001584
Chiachang Wangc1215d32020-10-20 15:38:58 +08001585 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001586 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001587
Chalard Jean28018572020-12-21 18:36:52 +09001588 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1589 // request that doesn't allow fallback to the default network. It should never be visible
1590 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1591 // arguments like the handler or the DnsResolver.
1592 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001593 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001594 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001595 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001596 new LinkProperties(), new NetworkCapabilities(),
1597 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001598 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1599 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001600
1601 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001602 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1603 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1604 // Even if it could, running on S would at least require mocking out the BPF map,
1605 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1606 // the bpf syscall. http://aosp/1907693
1607 if (SdkLevel.isAtLeastT()) {
1608 mDscpPolicyTracker = new DscpPolicyTracker();
1609 }
Tyler Wear72388212021-09-09 14:49:02 -07001610 } catch (ErrnoException e) {
1611 loge("Unable to create DscpPolicyTracker");
1612 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001613
1614 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1615 mContext);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001616 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001617
Chalard Jean46adcf32018-04-18 20:18:38 +09001618 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001619 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1620 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001621 }
1622
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001623 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1624 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001625 final NetworkCapabilities netCap = new NetworkCapabilities();
1626 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001627 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001628 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001629 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001630 return netCap;
1631 }
1632
James Mattis45d81842021-01-10 14:24:24 -08001633 private NetworkRequest createDefaultRequest() {
1634 return createDefaultInternetRequestForTransport(
1635 TYPE_NONE, NetworkRequest.Type.REQUEST);
1636 }
1637
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001638 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001639 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001640 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001641 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001642 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001643 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001644 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001645 netCap.addTransportType(transportType);
1646 }
James Mattis45d81842021-01-10 14:24:24 -08001647 return createNetworkRequest(type, netCap);
1648 }
1649
1650 private NetworkRequest createNetworkRequest(
1651 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001652 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001653 }
1654
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001655 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1656 NetworkRequest.Type type) {
1657 final NetworkCapabilities netCap = new NetworkCapabilities();
1658 netCap.clearAll();
1659 netCap.addCapability(capability);
1660 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1661 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1662 }
1663
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001664 // Used only for testing.
1665 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001666 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001667 // changing ContentResolver to make registerContentObserver non-final).
1668 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1669 // by subclassing SettingsObserver.
1670 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001671 void updateAlwaysOnNetworks() {
1672 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001673 }
1674
Erik Kline9a62f012018-03-21 07:18:33 -07001675 // See FakeSettingsProvider comment above.
1676 @VisibleForTesting
1677 void updatePrivateDnsSettings() {
1678 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1679 }
1680
paulhu51f77dc2021-06-07 02:34:20 +00001681 @VisibleForTesting
1682 void updateMobileDataPreferredUids() {
1683 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1684 }
1685
Patrick Rohr2857ac42022-01-21 14:58:16 +01001686 @VisibleForTesting
1687 void updateIngressRateLimit() {
1688 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1689 }
1690
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09001691 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, int id) {
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001692 final boolean enable = mContext.getResources().getBoolean(id);
1693 handleAlwaysOnNetworkRequest(networkRequest, enable);
1694 }
1695
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001696 private void handleAlwaysOnNetworkRequest(
1697 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001698 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001699 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001700 handleAlwaysOnNetworkRequest(networkRequest, enable);
1701 }
1702
1703 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001704 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001705 if (enable == isEnabled) {
1706 return; // Nothing to do.
1707 }
1708
1709 if (enable) {
1710 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001711 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001712 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001713 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001714 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001715 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1716 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001717 }
1718 }
1719
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001720 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001721 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1722 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1723 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1724 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001725 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1726 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001727 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001728 }
1729
paulhu51f77dc2021-06-07 02:34:20 +00001730 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001731 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001732 private void registerSettingsCallbacks() {
1733 // Watch for global HTTP proxy changes.
1734 mSettingsObserver.observe(
1735 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1736 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1737
1738 // Watch for whether or not to keep mobile data always on.
1739 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001740 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001741 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1742
1743 // Watch for whether or not to keep wifi always on.
1744 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001745 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001746 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001747
1748 // Watch for mobile data preferred uids changes.
1749 mSettingsObserver.observe(
1750 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1751 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001752
1753 // Watch for ingress rate limit changes.
1754 mSettingsObserver.observe(
1755 Settings.Secure.getUriFor(
1756 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1757 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001758 }
1759
Erik Kline31b4a9e2018-01-11 21:07:29 +09001760 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001761 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1762 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001763 }
1764 }
1765
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001766 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001767 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1768 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001769 return mNextNetworkRequestId++;
1770 }
1771
junyulai74f9a8b2018-06-13 15:00:37 +08001772 @VisibleForTesting
1773 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001774 if (network == null) {
1775 return null;
1776 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001777 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001778 }
1779
1780 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001781 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001782 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001783 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001784 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001785
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001786 // TODO: determine what to do when more than one VPN applies to |uid|.
1787 private NetworkAgentInfo getVpnForUid(int uid) {
1788 synchronized (mNetworkForNetId) {
1789 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1790 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1791 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1792 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001793 }
1794 }
1795 }
1796 return null;
1797 }
1798
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001799 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001800 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001801 final NetworkAgentInfo nai = getVpnForUid(uid);
1802 if (nai != null) return nai.declaredUnderlyingNetworks;
1803 return null;
1804 }
1805
Lorenzo Colittia7574052021-01-19 01:33:05 +09001806 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001807 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001808
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001809 final Network[] networks = getVpnUnderlyingNetworks(uid);
1810 if (networks != null) {
1811 // getUnderlyingNetworks() returns:
1812 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1813 // empty array => the VPN explicitly said "no default network".
1814 // non-empty array => the VPN specified one or more default networks; we use the
1815 // first one.
1816 if (networks.length > 0) {
1817 nai = getNetworkAgentInfoForNetwork(networks[0]);
1818 } else {
1819 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001820 }
1821 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001822 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001823 }
1824
1825 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001826 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001827 */
paulhu7aeba372020-12-30 00:42:19 +08001828 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1829 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001830 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001831 if (ignoreBlocked) {
1832 return false;
1833 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001834 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001835 final long ident = Binder.clearCallingIdentity();
1836 try {
1837 final boolean metered = nc == null ? true : nc.isMetered();
1838 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1839 } finally {
1840 Binder.restoreCallingIdentity(ident);
1841 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001842 }
1843
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001844 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001845 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1846 return;
1847 }
Hugo Benichi47011212017-03-30 10:46:05 +09001848 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001849 synchronized (mBlockedAppUids) {
1850 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001851 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001852 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001853 blocked = false;
1854 } else {
1855 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001856 }
1857 }
Hugo Benichi47011212017-03-30 10:46:05 +09001858 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1859 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1860 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001861 }
1862
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001863 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001864 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1865 return;
1866 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001867 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001868 final int requestId = nri.getActiveRequest() != null
1869 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001870 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001871 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001872 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001873 }
1874
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001875 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001876 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001877 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001878 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001879 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001880 @NonNull
1881 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1882 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001883 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1884 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1885 // but only exists if an app asks about them or requests them. Ensure the requesting app
1886 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001887 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001888 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1889 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1890 null /* extraInfo */);
1891 }
1892 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001893 return filtered;
1894 }
1895
1896 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1897 boolean ignoreBlocked) {
1898 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1899 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001900 }
1901
1902 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001903 * Return NetworkInfo for the active (i.e., connected) network interface.
1904 * It is assumed that at most one network is active at a time. If more
1905 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001906 * @return the info for the active network, or {@code null} if none is
1907 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001908 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001909 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001910 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001911 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001912 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001913 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1914 if (nai == null) return null;
1915 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1916 maybeLogBlockedNetworkInfo(networkInfo, uid);
1917 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001918 }
1919
Paul Jensen1f567382015-02-13 14:18:39 -05001920 @Override
1921 public Network getActiveNetwork() {
1922 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001923 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001924 }
1925
1926 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001927 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001928 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001929 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001930 }
1931
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001932 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001933 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1934 if (vpnNai != null) {
1935 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1936 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1937 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001938 }
Paul Jensen1f567382015-02-13 14:18:39 -05001939 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001940
James Mattis2516da32021-01-31 17:06:19 -08001941 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001942 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1943 ignoreBlocked)) {
1944 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001945 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001946 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001947 }
1948
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001949 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001950 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001951 PermissionUtils.enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001952 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1953 if (nai == null) return null;
1954 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001955 }
1956
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001957 /** Returns a NetworkInfo object for a network that doesn't exist. */
1958 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1959 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1960 getNetworkTypeName(networkType), "" /* subtypeName */);
1961 info.setIsAvailable(true);
1962 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1963 // background data is restricted.
1964 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1965 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1966 ? DetailedState.BLOCKED
1967 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001968 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1969 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001970 return info;
1971 }
1972
Lorenzo Colittia7574052021-01-19 01:33:05 +09001973 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001974 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1975 return null;
1976 }
1977 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001978 if (nai == null) {
1979 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001980 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001981 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1982 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001983 }
1984
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001985 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001986 public NetworkInfo getNetworkInfo(int networkType) {
1987 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001988 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001989 if (getVpnUnderlyingNetworks(uid) != null) {
1990 // A VPN is active, so we may need to return one of its underlying networks. This
1991 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09001992 // getNetworkAgentInfoForUid.
1993 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1994 if (nai == null) return null;
1995 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1996 if (networkInfo.getType() == networkType) {
1997 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001998 }
1999 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002000 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002001 }
2002
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002003 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002004 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002005 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002006 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002007 if (nai == null) return null;
2008 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002009 }
2010
2011 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002012 public NetworkInfo[] getAllNetworkInfo() {
2013 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002014 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002015 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2016 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002017 NetworkInfo info = getNetworkInfo(networkType);
2018 if (info != null) {
2019 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002020 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002021 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002022 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002023 }
2024
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002025 @Override
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002026 public Network getNetworkForType(int networkType) {
2027 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002028 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2029 return null;
2030 }
2031 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2032 if (nai == null) {
2033 return null;
2034 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002035 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002036 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2037 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002038 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002039 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002040 }
2041
2042 @Override
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002043 public Network[] getAllNetworks() {
2044 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002045 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002046 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002047 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002048 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002049 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002050 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002051 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002052 }
2053
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002054 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002055 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002056 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002057 // The basic principle is: if an app's traffic could possibly go over a
2058 // network, without the app doing anything multinetwork-specific,
2059 // (hence, by "default"), then include that network's capabilities in
2060 // the array.
2061 //
2062 // In the normal case, app traffic only goes over the system's default
2063 // network connection, so that's the only network returned.
2064 //
2065 // With a VPN in force, some app traffic may go into the VPN, and thus
2066 // over whatever underlying networks the VPN specifies, while other app
2067 // traffic may go over the system default network (e.g.: a split-tunnel
2068 // VPN, or an app disallowed by the VPN), so the set of networks
2069 // returned includes the VPN's underlying networks and the system
2070 // default.
2071 enforceAccessPermission();
2072
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002073 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002074
James Mattis2516da32021-01-31 17:06:19 -08002075 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2076 if (!nri.isBeingSatisfied()) {
2077 continue;
2078 }
2079 final NetworkAgentInfo nai = nri.getSatisfier();
2080 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2081 if (null != nc
2082 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2083 && !result.containsKey(nai.network)) {
2084 result.put(
2085 nai.network,
2086 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002087 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002088 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2089 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002090 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002091 }
2092
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002093 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002094 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002095 if (null != networks) {
2096 for (final Network network : networks) {
2097 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2098 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002099 result.put(
2100 network,
2101 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002102 nc,
2103 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002104 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002105 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002106 }
2107 }
2108 }
2109
2110 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2111 out = result.values().toArray(out);
2112 return out;
2113 }
2114
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002115 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002116 public boolean isNetworkSupported(int networkType) {
2117 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002118 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002119 }
2120
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002121 /**
2122 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002123 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002124 * @return the ip properties for the active network, or {@code null} if
2125 * none is active
2126 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002127 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002128 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002129 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002130 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002131 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2132 if (nai == null) return null;
2133 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002134 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002135 }
2136
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002137 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002138 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002139 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002140 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002141 final LinkProperties lp = getLinkProperties(nai);
2142 if (lp == null) return null;
2143 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002144 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002145 }
2146
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002147 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002148 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002149 public LinkProperties getLinkProperties(Network network) {
2150 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002151 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2152 if (lp == null) return null;
2153 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002154 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002155 }
2156
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002157 @Nullable
2158 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002159 if (nai == null) {
2160 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002161 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002162 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002163 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002164 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002165 }
2166
lucaslinc582d502022-01-27 09:07:00 +08002167 @Override
2168 @Nullable
2169 public LinkProperties redactLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
2170 @NonNull String packageName, @Nullable String callingAttributionTag) {
2171 Objects.requireNonNull(packageName);
2172 Objects.requireNonNull(lp);
2173 enforceNetworkStackOrSettingsPermission();
2174 if (!checkAccessPermission(-1 /* pid */, uid)) {
2175 return null;
2176 }
2177 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2178 }
2179
Qingxi Lib2748102020-01-08 12:51:49 -08002180 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2181 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2182 }
2183
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002184 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002185 if (nai == null) return null;
2186 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002187 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002188 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002189 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002190 }
2191
2192 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002193 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2194 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002195 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002196 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002197 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002198 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002199 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002200 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002201 }
2202
lucaslinc582d502022-01-27 09:07:00 +08002203 @Override
2204 public NetworkCapabilities redactNetworkCapabilitiesForPackage(@NonNull NetworkCapabilities nc,
2205 int uid, @NonNull String packageName, @Nullable String callingAttributionTag) {
2206 Objects.requireNonNull(nc);
2207 Objects.requireNonNull(packageName);
2208 enforceNetworkStackOrSettingsPermission();
2209 if (!checkAccessPermission(-1 /* pid */, uid)) {
2210 return null;
2211 }
2212 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2213 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2214 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2215 callingAttributionTag);
2216 }
2217
Qingxi Libb8da982020-01-17 17:54:27 -08002218 @VisibleForTesting
2219 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002220 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002221 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2222 // this would be expensive (one more permission check every time any NC callback is
2223 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2224 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2225 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002226 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002227 if (!checkSettingsPermission(callerPid, callerUid)) {
2228 newNc.setUids(null);
2229 newNc.setSSID(null);
lucaslinc582d502022-01-27 09:07:00 +08002230 // TODO: Processes holding NETWORK_FACTORY should be able to see the underlying networks
lucaslin6adf5ac2021-10-19 15:04:56 +08002231 newNc.setUnderlyingNetworks(null);
Chalard Jean46adcf32018-04-18 20:18:38 +09002232 }
Etan Cohen107ae952018-12-30 17:59:59 -08002233 if (newNc.getNetworkSpecifier() != null) {
2234 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2235 }
Cody Kesting5ab1f552020-03-16 18:15:28 -07002236 newNc.setAdministratorUids(new int[0]);
Benedict Wong53de25f2021-03-24 14:01:51 -07002237 if (!checkAnyPermissionOf(
2238 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09002239 newNc.setAccessUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002240 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002241 }
Qingxi Libb8da982020-01-17 17:54:27 -08002242
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002243 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002244 }
2245
Roshan Pius98f59ec2021-02-23 08:47:39 -08002246 /**
2247 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002248 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002249 * NetworkCapabilities.
2250 * Note: This wrapper does not support any sort of invalidation and thus must not be
2251 * persistent or long-lived. It may only be used for the time necessary to
2252 * compute the redactions required by one particular NetworkCallback or
2253 * synchronous call.
2254 */
2255 private class RedactionPermissionChecker {
2256 private final int mCallingPid;
2257 private final int mCallingUid;
2258 @NonNull private final String mCallingPackageName;
2259 @Nullable private final String mCallingAttributionTag;
2260
2261 private Boolean mHasLocationPermission = null;
2262 private Boolean mHasLocalMacAddressPermission = null;
2263 private Boolean mHasSettingsPermission = null;
2264
2265 RedactionPermissionChecker(int callingPid, int callingUid,
2266 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2267 mCallingPid = callingPid;
2268 mCallingUid = callingUid;
2269 mCallingPackageName = callingPackageName;
2270 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002271 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002272
2273 private boolean hasLocationPermissionInternal() {
2274 final long token = Binder.clearCallingIdentity();
2275 try {
2276 return mLocationPermissionChecker.checkLocationPermission(
2277 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2278 null /* message */);
2279 } finally {
2280 Binder.restoreCallingIdentity(token);
2281 }
2282 }
2283
2284 /**
2285 * Returns whether the app holds location permission or not (might return cached result
2286 * if the permission was already checked before).
2287 */
2288 public boolean hasLocationPermission() {
2289 if (mHasLocationPermission == null) {
2290 // If there is no cached result, perform the check now.
2291 mHasLocationPermission = hasLocationPermissionInternal();
2292 }
2293 return mHasLocationPermission;
2294 }
2295
2296 /**
2297 * Returns whether the app holds local mac address permission or not (might return cached
2298 * result if the permission was already checked before).
2299 */
2300 public boolean hasLocalMacAddressPermission() {
2301 if (mHasLocalMacAddressPermission == null) {
2302 // If there is no cached result, perform the check now.
2303 mHasLocalMacAddressPermission =
2304 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2305 }
2306 return mHasLocalMacAddressPermission;
2307 }
2308
2309 /**
2310 * Returns whether the app holds settings permission or not (might return cached
2311 * result if the permission was already checked before).
2312 */
2313 public boolean hasSettingsPermission() {
2314 if (mHasSettingsPermission == null) {
2315 // If there is no cached result, perform the check now.
2316 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2317 }
2318 return mHasSettingsPermission;
2319 }
2320 }
2321
2322 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2323 @NetworkCapabilities.NetCapability long redaction) {
2324 return (redactions & redaction) != 0;
2325 }
2326
2327 /**
2328 * Use the provided |applicableRedactions| to check the receiving app's
2329 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2330 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2331 * before being sent to the corresponding app.
2332 */
2333 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2334 @NetworkCapabilities.RedactionType long applicableRedactions,
2335 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2336 boolean includeLocationSensitiveInfo) {
2337 long redactions = applicableRedactions;
2338 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2339 if (includeLocationSensitiveInfo
2340 && redactionPermissionChecker.hasLocationPermission()) {
2341 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2342 }
2343 }
2344 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2345 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2346 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2347 }
2348 }
2349 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2350 if (redactionPermissionChecker.hasSettingsPermission()) {
2351 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2352 }
2353 }
2354 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002355 }
2356
Qingxi Lib2748102020-01-08 12:51:49 -08002357 @VisibleForTesting
2358 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002359 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002360 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002361 int callingPid, int callingUid, @NonNull String callingPkgName,
2362 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002363 if (nc == null) {
2364 return null;
2365 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002366 // Avoid doing location permission check if the transport info has no location sensitive
2367 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002368 final RedactionPermissionChecker redactionPermissionChecker =
2369 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2370 callingAttributionTag);
2371 final long redactions = retrieveRequiredRedactions(
2372 nc.getApplicableRedactions(), redactionPermissionChecker,
2373 includeLocationSensitiveInfo);
2374 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002375 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002376 // TODO : calling UID is redacted because apps should generally not know what UID is
2377 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002378 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002379 newNc.setOwnerUid(INVALID_UID);
2380 return newNc;
2381 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002382 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2383 if (nc.hasTransport(TRANSPORT_VPN)) {
2384 // Owner UIDs already checked above. No need to re-check.
2385 return newNc;
2386 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002387 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2388 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002389 // compatibility for older apps.
2390 if (!includeLocationSensitiveInfo
2391 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002392 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002393 newNc.setOwnerUid(INVALID_UID);
2394 return newNc;
2395 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002396 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002397 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002398 newNc.setOwnerUid(INVALID_UID);
2399 }
Qingxi Lib2748102020-01-08 12:51:49 -08002400 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002401 }
2402
lucaslinc582d502022-01-27 09:07:00 +08002403 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002404 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2405 LinkProperties lp, int callerPid, int callerUid) {
2406 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002407 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2408 // this would be expensive (one more permission check every time any LP callback is
2409 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2410 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2411 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002412
2413 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2414 final boolean needsSanitization =
2415 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2416 if (!needsSanitization) {
2417 return new LinkProperties(lp);
2418 }
2419
2420 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002421 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002422 }
2423
2424 final LinkProperties newLp = new LinkProperties(lp);
2425 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2426 // object gets parceled.
2427 newLp.setCaptivePortalApiUrl(null);
2428 newLp.setCaptivePortalData(null);
2429 return newLp;
2430 }
2431
Roshan Pius08c94fb2020-01-16 12:17:17 -08002432 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2433 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002434 // There is no need to track the effective UID of the request here. If the caller
2435 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002436 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002437 // Unprivileged apps can only pass in null or their own UID.
2438 if (nc.getUids() == null) {
2439 // If the caller passes in null, the callback will also match networks that do not
2440 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2441 // In this case, redact everything in the request immediately. This ensures that the
2442 // app is not able to get any redacted information by filing an unredacted request
2443 // and observing whether the request matches something.
2444 if (nc.getNetworkSpecifier() != null) {
2445 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2446 }
2447 } else {
2448 nc.setSingleUid(callerUid);
2449 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002450 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002451 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002452 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002453
2454 // Clear owner UID; this can never come from an app.
2455 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002456 }
2457
Chalard Jean38354d12018-03-20 19:13:57 +09002458 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002459 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002460 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2461 }
2462 }
2463
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002464 @Override
2465 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2466 enforceAccessPermission();
2467 final int callerUid = Binder.getCallingUid();
2468 final long token = Binder.clearCallingIdentity();
2469 try {
2470 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2471 } finally {
2472 Binder.restoreCallingIdentity(token);
2473 }
2474 }
2475
junyulaiebd15162021-03-03 12:09:05 +08002476 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002477 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002478 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002479 // This contains IMSI details, so make sure the caller is privileged.
paulhudf23d662021-01-25 18:53:17 +08002480 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002481
Serik Beketayev05130302021-01-15 16:47:25 -08002482 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002483 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002484 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2485 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002486 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002487 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002488 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002489 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2490 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002491 }
2492 }
2493 return result.toArray(new NetworkState[result.size()]);
2494 }
2495
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002496 @Override
junyulaiebd15162021-03-03 12:09:05 +08002497 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002498 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002499 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002500 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002501
2502 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2503 for (Network network : getAllNetworks()) {
2504 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Junyu Laiddecb662021-08-17 08:44:36 +00002505 if (nai != null && nai.everConnected) {
junyulaiebd15162021-03-03 12:09:05 +08002506 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2507 // NetworkCapabilities, which may contain UIDs of apps to which the
2508 // network applies. Should the UIDs be cleared so as not to leak or
2509 // interfere ?
2510 result.add(nai.getNetworkStateSnapshot());
2511 }
2512 }
2513 return result;
2514 }
2515
2516 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002517 public boolean isActiveNetworkMetered() {
2518 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002519
Qingxi Lib2748102020-01-08 12:51:49 -08002520 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002521 if (caps != null) {
2522 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2523 } else {
2524 // Always return the most conservative value
2525 return true;
2526 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002527 }
2528
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002529 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002530 * Ensures that the system cannot call a particular method.
2531 */
2532 private boolean disallowedBecauseSystemCaller() {
2533 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002534 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2535 // for devices launched with Q and above. However, existing devices upgrading to Q and
2536 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002537 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002538 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002539 log("This method exists only for app backwards compatibility"
2540 + " and must not be called by system services.");
2541 return true;
2542 }
2543 return false;
2544 }
2545
paulhub2c28682021-08-18 18:35:54 +08002546 private int getAppUid(final String app, final UserHandle user) {
2547 final PackageManager pm =
2548 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2549 final long token = Binder.clearCallingIdentity();
2550 try {
2551 return pm.getPackageUid(app, 0 /* flags */);
2552 } catch (PackageManager.NameNotFoundException e) {
2553 return -1;
2554 } finally {
2555 Binder.restoreCallingIdentity(token);
2556 }
2557 }
2558
2559 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2560 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2561 if (getAppUid(packageName, user) != callingUid) {
2562 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2563 }
2564 }
2565
Lorenzo Colitti23862912018-09-28 11:31:55 +09002566 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002567 * Ensure that a network route exists to deliver traffic to the specified
2568 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002569 * @param networkType the type of the network over which traffic to the
2570 * specified host is to be routed
2571 * @param hostAddress the IP address of the host to which the route is
2572 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002573 * @return {@code true} on success, {@code false} on failure
2574 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002575 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002576 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2577 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002578 if (disallowedBecauseSystemCaller()) {
2579 return false;
2580 }
paulhub2c28682021-08-18 18:35:54 +08002581 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002582 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002583 if (mProtectedNetworks.contains(networkType)) {
paulhu8e96a752019-08-12 16:25:11 +08002584 enforceConnectivityRestrictedNetworksPermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002585 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002586
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002587 InetAddress addr;
2588 try {
2589 addr = InetAddress.getByAddress(hostAddress);
2590 } catch (UnknownHostException e) {
2591 if (DBG) log("requestRouteToHostAddress got " + e.toString());
2592 return false;
2593 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002594
The Android Open Source Project28527d22009-03-03 19:31:44 -08002595 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002596 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002597 return false;
2598 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002599
2600 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2601 if (nai == null) {
2602 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
2603 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2604 } else {
2605 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2606 }
2607 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002608 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002609
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002610 DetailedState netState;
2611 synchronized (nai) {
2612 netState = nai.networkInfo.getDetailedState();
2613 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002614
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002615 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002616 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002617 log("requestRouteToHostAddress on down network "
2618 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002619 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002620 }
2621 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002622 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002623
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002624 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002625 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002626 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002627 LinkProperties lp;
2628 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002629 synchronized (nai) {
2630 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002631 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002632 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002633 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002634 if (DBG) {
2635 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2636 }
Wink Saville32506bc2013-06-29 21:10:57 -07002637 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002638 } finally {
2639 Binder.restoreCallingIdentity(token);
2640 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002641 }
2642
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002643 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002644 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002645 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002646 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002647 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002648 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002649 if (bestRoute.getGateway().equals(addr)) {
2650 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002651 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002652 } else {
2653 // if we will connect to this through another route, add a direct route
2654 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002655 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002656 }
2657 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002658 if (DBG) log("Adding legacy route " + bestRoute +
2659 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002660
2661 final String dst = bestRoute.getDestinationLinkAddress().toString();
2662 final String nextHop = bestRoute.hasGateway()
2663 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002664 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002665 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2666 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002667 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002668 return false;
2669 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002670 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002671 }
2672
paulhu7c0a2e62021-01-08 00:51:49 +08002673 class DnsResolverUnsolicitedEventCallback extends
2674 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002675 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002676 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002677 try {
2678 mHandler.sendMessage(mHandler.obtainMessage(
2679 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002680 new PrivateDnsValidationUpdate(event.netId,
2681 InetAddresses.parseNumericAddress(event.ipAddress),
2682 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002683 } catch (IllegalArgumentException e) {
2684 loge("Error parsing ip address in validation event");
2685 }
2686 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002687
2688 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002689 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2690 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002691 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2692 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2693 // event callback for certain nai. e.g. cellular. Register here to pass to
2694 // NetworkMonitor instead.
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002695 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
2696 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2697 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002698 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002699 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002700 }
2701 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002702
2703 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002704 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2705 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2706 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002707 }
dalyk1720e542018-03-05 12:42:22 -05002708
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002709 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002710 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002711 return this.VERSION;
2712 }
2713
2714 @Override
2715 public String getInterfaceHash() {
2716 return this.HASH;
2717 }
paulhu7c0a2e62021-01-08 00:51:49 +08002718 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002719
2720 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002721 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2722 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002723
paulhu7c0a2e62021-01-08 00:51:49 +08002724 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002725 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002726 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002727 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002728 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002729 }
2730 }
2731
Sudheer Shanka9967d462021-03-18 19:09:25 +00002732 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002733 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002734 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002735 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2736 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002737 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002738 };
2739
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002740 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002741 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002742 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002743 }
2744
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002745 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002746 for (String permission : permissions) {
2747 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002748 return true;
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002749 }
2750 }
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002751 return false;
2752 }
2753
paulhu1a407652019-03-22 16:35:06 +08002754 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2755 for (String permission : permissions) {
2756 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2757 return true;
2758 }
2759 }
2760 return false;
2761 }
2762
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002763 private void enforceAnyPermissionOf(String... permissions) {
2764 if (!checkAnyPermissionOf(permissions)) {
2765 throw new SecurityException("Requires one of the following permissions: "
2766 + String.join(", ", permissions) + ".");
2767 }
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002768 }
2769
Paul Jensen83f5d572014-08-29 09:54:01 -04002770 private void enforceInternetPermission() {
2771 mContext.enforceCallingOrSelfPermission(
2772 android.Manifest.permission.INTERNET,
2773 "ConnectivityService");
2774 }
2775
The Android Open Source Project28527d22009-03-03 19:31:44 -08002776 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002777 mContext.enforceCallingOrSelfPermission(
2778 android.Manifest.permission.ACCESS_NETWORK_STATE,
2779 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002780 }
2781
lucaslinc582d502022-01-27 09:07:00 +08002782 private boolean checkAccessPermission(int pid, int uid) {
2783 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
2784 == PERMISSION_GRANTED;
2785 }
2786
paulhua6ee2122021-02-22 15:40:43 +08002787 /**
2788 * Performs a strict and comprehensive check of whether a calling package is allowed to
2789 * change the state of network, as the condition differs for pre-M, M+, and
2790 * privileged/preinstalled apps. The caller is expected to have either the
2791 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2792 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2793 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2794 * permission and cannot be revoked. See http://b/23597341
2795 *
2796 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2797 * of this app will be updated to the current time.
2798 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002799 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002800 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2801 == PackageManager.PERMISSION_GRANTED) {
2802 return;
2803 }
2804
2805 if (callingPkg == null) {
2806 throw new SecurityException("Calling package name is null.");
2807 }
2808
2809 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2810 final int uid = mDeps.getCallingUid();
2811 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2812 callingPkg, callingAttributionTag, null /* message */);
2813
2814 if (mode == AppOpsManager.MODE_ALLOWED) {
2815 return;
2816 }
2817
2818 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2819 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2820 return;
2821 }
2822
2823 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2824 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2825 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002826 }
2827
Charles He9369e612017-05-15 17:07:18 +01002828 private void enforceSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002829 enforceAnyPermissionOf(
Charles He9369e612017-05-15 17:07:18 +01002830 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002831 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002832 }
2833
paulhu8e96a752019-08-12 16:25:11 +08002834 private void enforceNetworkFactoryPermission() {
paulhub6ba8e82020-03-04 09:43:41 +08002835 enforceAnyPermissionOf(
paulhu8e96a752019-08-12 16:25:11 +08002836 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002837 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002838 }
2839
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002840 private void enforceNetworkFactoryOrSettingsPermission() {
2841 enforceAnyPermissionOf(
2842 android.Manifest.permission.NETWORK_SETTINGS,
2843 android.Manifest.permission.NETWORK_FACTORY,
2844 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2845 }
2846
2847 private void enforceNetworkFactoryOrTestNetworksPermission() {
2848 enforceAnyPermissionOf(
2849 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2850 android.Manifest.permission.NETWORK_FACTORY,
2851 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2852 }
2853
Chalard Jean9a396cc2018-02-21 18:43:54 +09002854 private boolean checkSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002855 return checkAnyPermissionOf(
2856 android.Manifest.permission.NETWORK_SETTINGS,
2857 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002858 }
2859
2860 private boolean checkSettingsPermission(int pid, int uid) {
2861 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002862 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2863 || PERMISSION_GRANTED == mContext.checkPermission(
2864 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002865 }
2866
paulhu8e96a752019-08-12 16:25:11 +08002867 private void enforceNetworkStackOrSettingsPermission() {
2868 enforceAnyPermissionOf(
2869 android.Manifest.permission.NETWORK_SETTINGS,
2870 android.Manifest.permission.NETWORK_STACK,
2871 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2872 }
2873
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002874 private void enforceNetworkStackSettingsOrSetup() {
2875 enforceAnyPermissionOf(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002876 android.Manifest.permission.NETWORK_SETTINGS,
2877 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002878 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002879 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002880 }
2881
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002882 private void enforceAirplaneModePermission() {
2883 enforceAnyPermissionOf(
2884 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2885 android.Manifest.permission.NETWORK_SETTINGS,
2886 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2887 android.Manifest.permission.NETWORK_STACK,
2888 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2889 }
2890
James Mattis8378aec2021-01-26 14:05:36 -08002891 private void enforceOemNetworkPreferencesPermission() {
2892 mContext.enforceCallingOrSelfPermission(
2893 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2894 "ConnectivityService");
2895 }
2896
James Mattisfa270db2021-05-31 17:11:10 -07002897 private void enforceManageTestNetworksPermission() {
2898 mContext.enforceCallingOrSelfPermission(
2899 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2900 "ConnectivityService");
2901 }
2902
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002903 private boolean checkNetworkStackPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002904 return checkAnyPermissionOf(
2905 android.Manifest.permission.NETWORK_STACK,
2906 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002907 }
2908
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002909 private boolean checkNetworkStackPermission(int pid, int uid) {
2910 return checkAnyPermissionOf(pid, uid,
2911 android.Manifest.permission.NETWORK_STACK,
2912 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2913 }
2914
paulhu1a407652019-03-22 16:35:06 +08002915 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2916 return checkAnyPermissionOf(pid, uid,
2917 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002918 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2919 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002920 }
2921
Hugo Benichibd0cc762016-07-19 15:59:27 +09002922 private void enforceConnectivityRestrictedNetworksPermission() {
2923 try {
2924 mContext.enforceCallingOrSelfPermission(
2925 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2926 "ConnectivityService");
2927 return;
2928 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
paulhu8e96a752019-08-12 16:25:11 +08002929 // TODO: Remove this fallback check after all apps have declared
2930 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2931 mContext.enforceCallingOrSelfPermission(
2932 android.Manifest.permission.CONNECTIVITY_INTERNAL,
2933 "ConnectivityService");
Hugo Benichibd0cc762016-07-19 15:59:27 +09002934 }
2935
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002936 private void enforceKeepalivePermission() {
Lorenzo Colittif25beee2015-09-08 13:21:48 +09002937 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002938 }
2939
Roshan Pius98f59ec2021-02-23 08:47:39 -08002940 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2941 return PERMISSION_GRANTED == mContext.checkPermission(
2942 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2943 }
2944
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002945 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002946 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002947 }
2948
2949 private void sendInetConditionBroadcast(NetworkInfo info) {
2950 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2951 }
2952
Wink Saville4f0de1e2011-08-04 15:01:58 -07002953 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002954 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002955 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002956 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002957 if (info.isFailover()) {
2958 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2959 info.setFailover(false);
2960 }
2961 if (info.getReason() != null) {
2962 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2963 }
2964 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002965 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2966 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002967 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002968 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002969 return intent;
2970 }
2971
2972 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2973 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2974 }
2975
Chiachang Wang3bc52762021-11-25 14:17:57 +08002976 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
2977 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002978 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09002979 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09002980 if (!mSystemReady
2981 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002982 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002983 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002984 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002985 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002986 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002987 }
2988
Dianne Hackborn66dd0332015-12-09 17:22:26 -08002989 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07002990 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002991 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07002992 final NetworkInfo ni = intent.getParcelableExtra(
2993 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08002994 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2995 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2996 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08002997 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002998 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07002999 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003000 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003001 } finally {
3002 Binder.restoreCallingIdentity(ident);
3003 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003004 }
3005 }
3006
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003007 /**
Aaron Huang96011892020-06-27 07:18:23 +08003008 * Called by SystemServer through ConnectivityManager when the system is ready.
3009 */
3010 @Override
3011 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003012 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003013 throw new SecurityException("Calling Uid is not system uid.");
3014 }
3015 systemReadyInternal();
3016 }
3017
3018 /**
3019 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003020 */
3021 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003022 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003023 // Load flags after PackageManager is ready to query module version
3024 mFlags.loadFlags(mDeps, mContext);
3025
Aaron Huang9a57acf2020-12-08 10:03:29 +08003026 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3027 // listening network request which is sent by MultipathPolicyTracker won't be added
3028 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3029 // be called after PermissionMonitor#startMonitoring().
3030 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3031 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3032 // to ensure the tracking will be initialized correctly.
paulhuc62d3c22019-11-19 17:55:31 +08003033 mPermissionMonitor.startMonitoring();
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003034 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003035 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003036
Hugo Benichie5220992017-04-26 14:53:28 +09003037 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003038 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003039 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003040 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003041 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003042 }
3043 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003044
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003045 // Create network requests for always-on networks.
3046 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003047
3048 // Update mobile data preference if necessary.
3049 // Note that empty uid list can be skip here only because no uid rules applied before system
3050 // ready. Normally, the empty uid list means to clear the uids rules on netd.
3051 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3052 updateMobileDataPreferredUids();
3053 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003054 }
3055
The Android Open Source Project28527d22009-03-03 19:31:44 -08003056 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003057 * Start listening for default data network activity state changes.
3058 */
3059 @Override
3060 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003061 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003062 }
3063
3064 /**
3065 * Stop listening for default data network activity state changes.
3066 */
3067 @Override
3068 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003069 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003070 }
3071
3072 /**
3073 * Check whether the default network radio is currently active.
3074 */
3075 @Override
3076 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003077 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003078 }
3079
3080 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003081 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003082 * and set it on it's iface.
3083 */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003084 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
3085 final String iface = newLp.getInterfaceName();
3086 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09003087 if (oldLp == null && mtu == 0) {
3088 // Silently ignore unset MTU value.
3089 return;
3090 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003091 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
3092 if (VDBG) log("identical MTU - not setting");
3093 return;
3094 }
paulhucbbc3db2019-03-08 16:35:20 +08003095 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003096 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003097 return;
3098 }
sy.yun4aa73922013-09-02 05:24:09 +09003099
w19976e714f1d2014-08-05 15:18:11 -07003100 // Cannot set MTU without interface name
3101 if (TextUtils.isEmpty(iface)) {
3102 loge("Setting MTU size with null iface.");
3103 return;
3104 }
3105
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003106 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003107 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003108 mNetd.interfaceSetMtu(iface, mtu);
3109 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003110 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003111 }
3112 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003113
Chenbo Feng15416292018-11-08 17:36:21 -08003114 @VisibleForTesting
3115 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003116
lucaslin821c9782018-11-28 19:27:52 +08003117 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003118 String[] values = null;
3119 if (tcpBufferSizes != null) {
3120 values = tcpBufferSizes.split(",");
3121 }
3122
3123 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003124 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003125 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3126 values = tcpBufferSizes.split(",");
3127 }
3128
3129 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3130
3131 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003132 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003133
Chenbo Feng15416292018-11-08 17:36:21 -08003134 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3135 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3136 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003137 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003138 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003139 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003140 }
3141 }
3142
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003143 @Override
3144 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003145 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003146 NETWORK_RESTORE_DELAY_PROP_NAME);
3147 if(restoreDefaultNetworkDelayStr != null &&
3148 restoreDefaultNetworkDelayStr.length() != 0) {
3149 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003150 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003151 } catch (NumberFormatException e) {
3152 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003153 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003154 // if the system property isn't set, use the value for the apn type
3155 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3156
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003157 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3158 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003159 }
3160 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003161 }
3162
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003163 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
3164 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
3165 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003166 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003167 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003168 // Start gathering diagnostic information.
3169 netDiags.add(new NetworkDiagnostics(
3170 nai.network,
3171 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003172 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003173 DIAG_TIME_MS));
3174 }
3175
3176 for (NetworkDiagnostics netDiag : netDiags) {
3177 pw.println();
3178 netDiag.waitForMeasurements();
3179 netDiag.dump(pw);
3180 }
3181 }
3182
The Android Open Source Project28527d22009-03-03 19:31:44 -08003183 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003184 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3185 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003186 if (!checkDumpPermission(mContext, TAG, writer)) return;
3187
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003188 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003189 }
3190
lucaslin99473f62020-12-10 15:10:54 +08003191 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3192 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3193 != PackageManager.PERMISSION_GRANTED) {
3194 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003195 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003196 + " due to missing android.permission.DUMP permission");
3197 return false;
3198 } else {
3199 return true;
3200 }
3201 }
3202
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003203 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003204 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003205
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003206 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003207 dumpNetworkDiagnostics(pw);
3208 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003209 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003210 dumpNetworks(pw);
3211 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003212 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003213 dumpNetworkRequests(pw);
3214 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003215 }
Erik Kline9647f382015-06-05 17:47:34 +09003216
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003217 pw.print("NetworkProviders for:");
3218 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
3219 pw.print(" " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003220 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09003221 pw.println();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003222 pw.println();
3223
Chalard Jean5b409c72021-02-04 13:12:59 +09003224 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003225 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003226 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003227 pw.println("none");
3228 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003229 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003230 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003231 pw.println();
3232
James Mattis8b298a02021-06-01 22:34:04 -07003233 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003234 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003235 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003236 pw.decreaseIndent();
3237 pw.println();
3238
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003239 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003240 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003241 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003242 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003243 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003244
junyulaif2c67e42018-08-07 19:50:45 +08003245 pw.println("Status for known UIDs:");
3246 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003247 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003248 for (int i = 0; i < size; i++) {
3249 // Don't crash if the array is modified while dumping in bugreports.
3250 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003251 final int uid = mUidBlockedReasons.keyAt(i);
3252 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3253 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003254 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003255 } catch (ArrayIndexOutOfBoundsException e) {
3256 pw.println(" ArrayIndexOutOfBoundsException");
3257 } catch (ConcurrentModificationException e) {
3258 pw.println(" ConcurrentModificationException");
3259 }
3260 }
3261 pw.println();
3262 pw.decreaseIndent();
3263
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003264 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003265 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003266 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003267 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003268 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003269
Robert Greenwalt94e22142014-07-30 16:31:24 -07003270 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003271
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003272 pw.println();
markchien5e866652019-09-30 14:40:57 +08003273 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003274
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003275 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003276 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003277
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003278 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003279
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003280 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003281 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003282 pw.println("mNetworkRequestInfoLogs (most recent first):");
3283 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003284 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003285 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003286
3287 pw.println();
3288 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3289 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003290 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003291 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003292
3293 pw.println();
3294 pw.println("NetTransition WakeLock activity (most recent first):");
3295 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003296 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3297 pw.println("total releases: " + mTotalWakelockReleases);
3298 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3299 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3300 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3301 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3302 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3303 }
James Mattiscb1e0362021-04-06 17:07:42 -07003304 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003305
3306 pw.println();
3307 pw.println("bandwidth update requests (by uid):");
3308 pw.increaseIndent();
3309 synchronized (mBandwidthRequests) {
3310 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3311 pw.println("[" + mBandwidthRequests.keyAt(i)
3312 + "]: " + mBandwidthRequests.valueAt(i));
3313 }
3314 }
3315 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003316 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003317
James Mattiscb1e0362021-04-06 17:07:42 -07003318 pw.println();
3319 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3320 pw.increaseIndent();
3321 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003322 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003323 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003324
3325 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003326
3327 pw.println();
3328 pw.println("Permission Monitor:");
3329 pw.increaseIndent();
3330 mPermissionMonitor.dump(pw);
3331 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003332
3333 pw.println();
3334 pw.println("Legacy network activity:");
3335 pw.increaseIndent();
3336 mNetworkActivityTracker.dump(pw);
3337 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003338 }
3339
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003340 private void dumpNetworks(IndentingPrintWriter pw) {
3341 for (NetworkAgentInfo nai : networksSortedById()) {
3342 pw.println(nai.toString());
3343 pw.increaseIndent();
3344 pw.println(String.format(
3345 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3346 nai.numForegroundNetworkRequests(),
3347 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3348 nai.numBackgroundNetworkRequests(),
3349 nai.numNetworkRequests()));
3350 pw.increaseIndent();
3351 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3352 pw.println(nai.requestAt(i).toString());
3353 }
3354 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003355 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003356 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003357 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003358 pw.decreaseIndent();
3359 pw.decreaseIndent();
3360 }
3361 }
3362
James Mattis8b298a02021-06-01 22:34:04 -07003363 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3364 if (!mProfileNetworkPreferences.isEmpty()) {
3365 pw.println("Profile preferences:");
3366 pw.increaseIndent();
3367 pw.println(mProfileNetworkPreferences.preferences);
3368 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003369 }
James Mattis8b298a02021-06-01 22:34:04 -07003370 if (!mOemNetworkPreferences.isEmpty()) {
3371 pw.println("OEM preferences:");
3372 pw.increaseIndent();
3373 pw.println(mOemNetworkPreferences);
3374 pw.decreaseIndent();
3375 }
3376 if (!mMobileDataPreferredUids.isEmpty()) {
3377 pw.println("Mobile data preferred UIDs:");
3378 pw.increaseIndent();
3379 pw.println(mMobileDataPreferredUids);
3380 pw.decreaseIndent();
3381 }
James Mattis45d81842021-01-10 14:24:24 -08003382
James Mattis8b298a02021-06-01 22:34:04 -07003383 pw.println("Default requests:");
3384 pw.increaseIndent();
3385 dumpPerAppDefaultRequests(pw);
3386 pw.decreaseIndent();
3387 }
3388
3389 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003390 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3391 if (mDefaultRequest == defaultRequest) {
3392 continue;
3393 }
3394
James Mattis8b298a02021-06-01 22:34:04 -07003395 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3396 final String networkOutput;
3397 if (null == satisfier) {
3398 networkOutput = "null";
3399 } else if (mNoServiceNetwork.equals(satisfier)) {
3400 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003401 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003402 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003403 }
James Mattis8b298a02021-06-01 22:34:04 -07003404 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3405 ? "" : " asUid: " + defaultRequest.mAsUid;
3406 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3407 + defaultRequest.mPid + asUidString + "]";
3408 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3409 + " Preference order: " + defaultRequest.mPreferenceOrder
3410 + " Tracked UIDs: " + defaultRequest.getUids();
3411 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003412 }
3413 }
3414
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003415 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003416 NetworkRequestInfo[] infos = null;
3417 while (infos == null) {
3418 try {
3419 infos = requestsSortedById();
3420 } catch (ConcurrentModificationException e) {
3421 // mNetworkRequests should only be accessed from handler thread, except dump().
3422 // As dump() is never called in normal usage, it would be needlessly expensive
3423 // to lock the collection only for its benefit. Instead, retry getting the
3424 // requests if ConcurrentModificationException is thrown during dump().
3425 }
3426 }
3427 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003428 pw.println(nri.toString());
3429 }
3430 }
3431
Chalard Jean524f0b12021-10-25 21:11:56 +09003432 private void dumpAllRequestInfoLogsToLogcat() {
3433 try (PrintWriter logPw = new PrintWriter(new Writer() {
3434 @Override
3435 public void write(final char[] cbuf, final int off, final int len) {
3436 // This method is called with 0-length and 1-length arrays for empty strings
3437 // or strings containing only the DEL character.
3438 if (len <= 1) return;
3439 Log.e(TAG, new String(cbuf, off, len));
3440 }
3441 @Override public void flush() {}
3442 @Override public void close() {}
3443 })) {
3444 mNetworkRequestInfoLogs.dump(logPw);
3445 }
3446 }
3447
Hugo Benichia480ba52018-09-03 08:19:02 +09003448 /**
3449 * Return an array of all current NetworkAgentInfos sorted by network id.
3450 */
3451 private NetworkAgentInfo[] networksSortedById() {
3452 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003453 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003454 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003455 return networks;
3456 }
3457
3458 /**
3459 * Return an array of all current NetworkRequest sorted by request id.
3460 */
James Mattis258ea3c2020-11-15 15:04:40 -08003461 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003462 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003463 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003464 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003465 // Sort the array based off the NRI containing the min requestId in its requests.
3466 Arrays.sort(requests,
3467 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3468 Comparator.comparingInt(req -> req.requestId)).requestId
3469 )
3470 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003471 return requests;
3472 }
3473
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003474 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003475 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003476 if (officialNai != null && officialNai.equals(nai)) return true;
3477 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003478 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003479 " - " + nai);
3480 }
3481 return false;
3482 }
3483
Robert Greenwalt2034b912009-08-12 16:08:25 -07003484 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003485 private class NetworkStateTrackerHandler extends Handler {
3486 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003487 super(looper);
3488 }
3489
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003490 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003491 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3492 final NetworkAgentInfo nai = arg.first;
3493 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003494 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003495 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003496 }
3497 return;
3498 }
3499
3500 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003501 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean15228572022-01-28 19:29:12 +09003502 final NetworkCapabilities networkCapabilities = new NetworkCapabilities(
3503 (NetworkCapabilities) arg.second);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003504 processCapabilitiesFromAgent(nai, networkCapabilities);
Hugo Benichibbc15192016-09-15 18:18:48 +09003505 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003506 break;
3507 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003508 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003509 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003510 processLinkPropertiesFromAgent(nai, newLp);
3511 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003512 break;
3513 }
3514 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003515 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003516 updateNetworkInfo(nai, info);
3517 break;
3518 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003519 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003520 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003521 break;
3522 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003523 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003524 if (nai.everConnected) {
3525 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003526 // Note that if the NAI had been connected, this would affect the
3527 // score, and therefore would require re-mixing the score and performing
3528 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003529 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003530 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3531 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003532 // Mark the network as temporarily accepting partial connectivity so that it
3533 // will be validated (and possibly become default) even if it only provides
3534 // partial internet access. Note that if user connects to partial connectivity
3535 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3536 // out of wifi coverage) and if the same wifi is available again, the device
3537 // will auto connect to this wifi even though the wifi has "no internet".
3538 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003539 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003540 break;
3541 }
junyulai011b1f12019-01-03 18:50:15 +08003542 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003543 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003544 break;
3545 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003546 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003547 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003548 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003549
3550 if (isLegacyLockdownNai(nai)
3551 && (underlying == null || underlying.size() != 1)) {
3552 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3553 + " must have exactly one underlying network: " + underlying);
3554 }
3555
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003556 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3557 nai.declaredUnderlyingNetworks = (underlying != null)
3558 ? underlying.toArray(new Network[0]) : null;
3559
3560 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3561 if (DBG) {
3562 log(nai.toShortString() + " changed underlying networks to "
3563 + Arrays.toString(nai.declaredUnderlyingNetworks));
3564 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003565 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003566 notifyIfacesChangedForNetworkStats();
3567 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003568 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003569 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003570 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3571 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3572 nai.teardownDelayMs = msg.arg1;
3573 } else {
3574 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3575 }
Chalard Jean550b5212021-03-05 23:07:53 +09003576 break;
3577 }
3578 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3579 nai.setLingerDuration((int) arg.second);
3580 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003581 }
Tyler Wear72388212021-09-09 14:49:02 -07003582 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3583 DscpPolicy policy = (DscpPolicy) arg.second;
3584 if (mDscpPolicyTracker != null) {
3585 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3586 }
3587 break;
3588 }
3589 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3590 if (mDscpPolicyTracker != null) {
3591 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3592 }
3593 break;
3594 }
3595 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3596 if (mDscpPolicyTracker != null) {
3597 mDscpPolicyTracker.removeAllDscpPolicies(nai);
3598 }
3599 break;
3600 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003601 }
3602 }
3603
3604 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3605 switch (msg.what) {
3606 default:
3607 return false;
lucasline117e2e2019-10-22 18:27:33 +08003608 case EVENT_PROBE_STATUS_CHANGED: {
3609 final Integer netId = (Integer) msg.obj;
3610 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3611 if (nai == null) {
3612 break;
3613 }
3614 final boolean probePrivateDnsCompleted =
3615 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3616 final boolean privateDnsBroken =
3617 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3618 if (probePrivateDnsCompleted) {
3619 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3620 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003621 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003622 }
3623 // Only show the notification when the private DNS is broken and the
3624 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003625 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003626 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3627 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003628 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003629 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3630 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3631 // private DNS is broken, it means this network is being reevaluated.
3632 // Either probing private DNS is not necessary any more or it hasn't been
3633 // done yet. In either case, the networkCapabilities should be updated to
3634 // reflect the new status.
3635 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003636 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003637 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003638 }
3639 break;
3640 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003641 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003642 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3643
3644 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003645 if (nai == null) break;
3646
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003647 handleNetworkTested(nai, results.mTestResult,
3648 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003649 break;
3650 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003651 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09003652 final int netId = msg.arg2;
Hugo Benichif4210292017-04-21 15:07:12 +09003653 final boolean visible = toBool(msg.arg1);
Erik Kline9a62f012018-03-21 07:18:33 -07003654 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Ondada1452016-10-11 15:10:46 -07003655 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003656 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3657 nai.lastCaptivePortalDetected = visible;
3658 nai.everCaptivePortalDetected |= visible;
Calvin Ondada1452016-10-11 15:10:46 -07003659 if (nai.lastCaptivePortalDetected &&
paulhu56e09df2021-03-17 20:30:33 +08003660 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3661 == getCaptivePortalMode()) {
Chalard Jean49707572019-12-10 21:07:02 +09003662 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003663 nai.onPreventAutomaticReconnect();
Calvin Ondada1452016-10-11 15:10:46 -07003664 teardownUnneededNetwork(nai);
3665 break;
3666 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003667 updateCapabilitiesForNetwork(nai);
Paul Jensen53f08952015-06-16 14:27:36 -04003668 }
3669 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003670 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003671 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003672 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3673 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003674 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003675 if (nai == null) {
3676 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3677 break;
3678 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003679 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003680 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003681 (PendingIntent) msg.obj,
3682 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003683 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003684 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003685 break;
3686 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003687 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline9a62f012018-03-21 07:18:33 -07003688 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003689 if (nai == null) break;
3690
Erik Kline9a62f012018-03-21 07:18:33 -07003691 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003692 break;
3693 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003694 case EVENT_CAPPORT_DATA_CHANGED: {
3695 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3696 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003697 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003698 break;
3699 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003700 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003701 return true;
3702 }
3703
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003704 private void handleNetworkTested(
3705 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3706 final boolean wasPartial = nai.partialConnectivity;
3707 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3708 final boolean partialConnectivityChanged =
3709 (wasPartial != nai.partialConnectivity);
3710
3711 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3712 final boolean wasValidated = nai.lastValidated;
Chalard Jean5b409c72021-02-04 13:12:59 +09003713 final boolean wasDefault = isDefaultNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003714
3715 if (DBG) {
3716 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3717 ? " with redirect to " + redirectUrl
3718 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003719 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003720 }
3721 if (valid != nai.lastValidated) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003722 final int oldScore = nai.getCurrentScore();
3723 nai.lastValidated = valid;
3724 nai.everValidated |= valid;
3725 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003726 if (valid) {
3727 handleFreshlyValidatedNetwork(nai);
3728 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3729 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003730 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003731 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003732 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003733 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003734 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003735 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003736 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003737 NotificationType.PRIVATE_DNS_BROKEN);
3738 // If network becomes valid, the hasShownBroken should be reset for
3739 // that network so that the notification will be fired when the private
3740 // DNS is broken again.
3741 nai.networkAgentConfig.hasShownBroken = false;
3742 }
3743 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003744 updateCapabilitiesForNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003745 }
3746 updateInetCondition(nai);
3747 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003748 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003749 nai.onValidationStatusChanged(
3750 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3751 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003752
3753 // If NetworkMonitor detects partial connectivity before
3754 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3755 // immediately. Re-notify partial connectivity silently if no internet
3756 // notification already there.
3757 if (!wasPartial && nai.partialConnectivity) {
3758 // Remove delayed message if there is a pending message.
3759 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3760 handlePromptUnvalidated(nai.network);
3761 }
3762
3763 if (wasValidated && !nai.lastValidated) {
3764 handleNetworkUnvalidated(nai);
3765 }
3766 }
3767
Calvin Ondada1452016-10-11 15:10:46 -07003768 private int getCaptivePortalMode() {
3769 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003770 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3771 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003772 }
3773
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003774 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3775 switch (msg.what) {
3776 default:
3777 return false;
3778 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3779 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3780 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3781 handleLingerComplete(nai);
3782 }
3783 break;
3784 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003785 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3786 handleNetworkAgentRegistered(msg);
3787 break;
3788 }
3789 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3790 handleNetworkAgentDisconnected(msg);
3791 break;
3792 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003793 }
3794 return true;
3795 }
3796
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003797 @Override
3798 public void handleMessage(Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003799 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003800 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003801 maybeHandleNetworkAgentMessage(msg);
3802 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003803 }
3804 }
3805
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003806 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003807 private final int mNetId;
3808 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003809
3810 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003811 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003812 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003813 }
3814
3815 @Override
3816 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3817 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003818 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003819 }
3820
3821 @Override
3822 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003823 // Legacy version of notifyNetworkTestedWithExtras.
3824 // Would only be called if the system has a NetworkStack module older than the
3825 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003826 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003827 }
3828
3829 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003830 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003831 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3832 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003833 final Message msg = mTrackerHandler.obtainMessage(
3834 EVENT_NETWORK_TESTED,
3835 new NetworkTestedResults(
3836 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003837 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003838
3839 // Invoke ConnectivityReport generation for this Network test event.
3840 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3841 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003842
Cody Kestingf1120be2020-08-03 18:01:40 -07003843 // NetworkMonitor reports the network validation result as a bitmask while
3844 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
3845 // logical value for ConnectivityDiagnostics.
3846 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
3847 p.result);
3848
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003849 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07003850 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003851 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3852 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3853
Aaron Huang959d3642021-01-21 15:47:41 +08003854 ConnectivityReportEvent reportEvent =
3855 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3856 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3857 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003858 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003859 }
3860
3861 @Override
3862 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3863 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3864 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09003865 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003866 }
3867
3868 @Override
lucasline117e2e2019-10-22 18:27:33 +08003869 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3870 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3871 EVENT_PROBE_STATUS_CHANGED,
3872 probesCompleted, probesSucceeded, new Integer(mNetId)));
3873 }
3874
3875 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003876 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3877 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3878 EVENT_CAPPORT_DATA_CHANGED,
3879 0, mNetId, data));
3880 }
3881
3882 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003883 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003884 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003885 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003886
3887 final PendingIntent pendingIntent;
3888 // Only the system server can register notifications with package "android"
3889 final long token = Binder.clearCallingIdentity();
3890 try {
paulhu7746e4e2020-06-09 19:07:03 +08003891 pendingIntent = PendingIntent.getBroadcast(
3892 mContext,
3893 0 /* requestCode */,
3894 intent,
3895 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003896 } finally {
3897 Binder.restoreCallingIdentity(token);
3898 }
3899 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3900 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09003901 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003902 }
3903
3904 @Override
3905 public void hideProvisioningNotification() {
3906 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09003907 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003908 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003909
3910 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003911 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003912 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08003913 }
3914
3915 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003916 public int getInterfaceVersion() {
3917 return this.VERSION;
3918 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09003919
3920 @Override
3921 public String getInterfaceHash() {
3922 return this.HASH;
3923 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003924 }
3925
Cody Kestingf1120be2020-08-03 18:01:40 -07003926 /**
3927 * Converts the given NetworkMonitor-specific validation result bitmask to a
3928 * ConnectivityDiagnostics-specific validation result int.
3929 */
3930 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
3931 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
3932 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
3933 }
3934 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
3935 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
3936 }
3937 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
3938 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
3939 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
3940 }
3941
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003942 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07003943 log("Data stall detected with methods: " + p.detectionMethod);
3944
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003945 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07003946 int detectionMethod = 0;
3947 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3948 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3949 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3950 }
3951 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3952 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3953 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3954 p.tcpMetricsCollectionPeriodMillis);
3955 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003956 }
3957
Cody Kestingf53a0752020-04-15 12:33:28 -07003958 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003959 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08003960 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07003961
3962 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3963 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3964 // the cost of going through two handlers.
3965 mConnectivityDiagnosticsHandler.sendMessage(msg);
3966 }
3967
Cody Kestingb37958e2020-05-15 10:36:01 -07003968 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3969 return (p.detectionMethod & detectionMethod) != 0;
3970 }
3971
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003972 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3973 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07003974 }
3975
Erik Klinea73af002018-06-26 18:53:43 +09003976 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3977 if (nai == null) return;
3978 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3979 // in order to restart a validation pass from within netd.
3980 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3981 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003982 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09003983 }
3984 }
3985
Erik Kline31b4a9e2018-01-11 21:07:29 +09003986 private void handlePrivateDnsSettingsChanged() {
3987 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3988
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003989 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07003990 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003991 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05003992 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3993 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09003994 }
3995 }
3996
Erik Kline9a62f012018-03-21 07:18:33 -07003997 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3998 // Private DNS only ever applies to networks that might provide
3999 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004000 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004001
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004002 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004003 // schedule DNS resolutions. If a DNS resolution is required the
4004 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004005 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004006
4007 // With Private DNS bypass support, we can proceed to update the
4008 // Private DNS config immediately, even if we're in strict mode
4009 // and have not yet resolved the provider name into a set of IPs.
4010 updatePrivateDns(nai, cfg);
4011 }
4012
4013 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4014 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004015 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004016 }
4017
dalyk1720e542018-03-05 12:42:22 -05004018 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4019 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4020 if (nai == null) {
4021 return;
4022 }
4023 mDnsManager.updatePrivateDnsValidation(update);
4024 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4025 }
4026
paulhu7c0a2e62021-01-08 00:51:49 +08004027 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004028 int prefixLength) {
4029 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4030 if (nai == null) return;
4031
paulhu7c0a2e62021-01-08 00:51:49 +08004032 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4033 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004034
4035 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004036 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004037 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004038 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004039 prefixLength);
4040 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004041 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004042 return;
4043 }
4044 }
4045
Lorenzo Colittid523d142020-04-01 20:16:30 +09004046 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004047 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4048 }
4049
Hai Shalome58bdc62021-01-11 18:45:34 -08004050 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004051 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004052 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004053 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4054 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4055 }
4056
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004057 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004058 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004059 * @param nai the agent info to update
4060 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004061 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004062 */
junyulai2b6f0c22021-02-03 20:15:30 +08004063 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4064 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4065 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004066 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004067 // one lingered request, set inactive.
4068 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004069 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004070 if (DBG) log("Unsetting inactive " + nai.toShortString());
4071 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004072 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004073 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004074 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004075 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4076 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004077 }
junyulai2b6f0c22021-02-03 20:15:30 +08004078 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004079 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004080 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004081 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004082 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004083 }
4084
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004085 private void handleNetworkAgentRegistered(Message msg) {
4086 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4087 if (!mNetworkAgentInfos.contains(nai)) {
4088 return;
4089 }
4090
4091 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4092 if (VDBG) log("NetworkAgent registered");
4093 } else {
4094 loge("Error connecting NetworkAgent");
4095 mNetworkAgentInfos.remove(nai);
4096 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004097 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004098 synchronized (mNetworkForNetId) {
4099 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004100 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004101 mNetIdManager.releaseNetId(nai.network.getNetId());
4102 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004103 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004104 }
4105 }
4106 }
Paul Jensend5f53392014-11-25 15:26:53 -05004107
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004108 private void handleNetworkAgentDisconnected(Message msg) {
4109 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004110 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004111 }
4112
Chalard Jeand9fffc32018-05-11 20:19:20 +09004113 // Destroys a network, remove references to it from the internal state managed by
4114 // ConnectivityService, free its interfaces and clean up.
4115 // Must be called on the Handler thread.
4116 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004117 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004118
4119 if (!mNetworkAgentInfos.contains(nai)) return;
4120
Chalard Jeand9fffc32018-05-11 20:19:20 +09004121 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004122 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004123 }
lucaslinb25c9a62019-02-12 15:30:13 +08004124 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004125 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004126 // A network agent has disconnected.
4127 // TODO - if we move the logic to the network agent (have them disconnect
4128 // because they lost all their requests or because their score isn't good)
4129 // then they would disconnect organically, report their new state and then
4130 // disconnect the channel.
4131 if (nai.networkInfo.isConnected()) {
4132 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4133 null, null);
4134 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004135 final boolean wasDefault = isDefaultNetwork(nai);
4136 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004137 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004138 }
4139 notifyIfacesChangedForNetworkStats();
4140 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4141 // by other networks that are already connected. Perhaps that can be done by
4142 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4143 // of rematchAllNetworksAndRequests
4144 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004145 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004146
4147 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004148 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4149 // Disable wakeup packet monitoring for each interface.
4150 wakeupModifyInterface(iface, nai.networkCapabilities, false);
4151 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004152 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004153 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004154 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004155 synchronized (mNetworkForNetId) {
4156 // Remove the NetworkAgent, but don't mark the netId as
4157 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004158 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004159 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004160 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004161 // Remove all previously satisfied requests.
4162 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004163 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004164 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004165 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004166 if (currentNetwork != null
4167 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004168 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004169 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4170 // rematch not to keep disconnected agents instead of setting it here ; this
4171 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004172 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004173 for (final NetworkOfferInfo noi : mNetworkOffers) {
4174 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004175 }
James Mattise3ef1912020-12-20 11:09:58 -08004176
Chalard Jean5b409c72021-02-04 13:12:59 +09004177 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004178 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004179 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004180 // network, because while incorrect this is the closest to the old (also
4181 // incorrect) behavior.
4182 mNetworkActivityTracker.updateDataActivityTracking(
4183 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004184 ensureNetworkTransitionWakelock(nai.toShortString());
4185 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004186 }
4187 }
junyulai2b6f0c22021-02-03 20:15:30 +08004188 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004189 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004190 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004191 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004192 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004193 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004194 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004195
4196 // Immediate teardown.
4197 if (nai.teardownDelayMs == 0) {
4198 destroyNetwork(nai);
4199 return;
4200 }
4201
4202 // Delayed teardown.
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304203 if (nai.created) {
4204 try {
4205 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4206 } catch (RemoteException e) {
4207 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4208 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004209 }
4210 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4211 }
4212
4213 private void destroyNetwork(NetworkAgentInfo nai) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004214 if (nai.created) {
4215 // Tell netd to clean up the configuration for this network
4216 // (routing rules, DNS, etc).
4217 // This may be slow as it requires a lot of netd shelling out to ip and
4218 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004219 // after we've rematched networks with requests (which might change the default
4220 // network or service a new request from an app), so network traffic isn't interrupted
4221 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004222 destroyNativeNetwork(nai);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004223 mDnsManager.removeNetwork(nai.network);
Patrick Rohr2857ac42022-01-21 14:58:16 +01004224
4225 // clean up tc police filters on interface.
4226 if (canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
4227 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
4228 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004229 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004230 mNetIdManager.releaseNetId(nai.network.getNetId());
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004231 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004232 }
4233
Ken Chen6df7a902021-04-09 15:08:42 +08004234 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004235 try {
4236 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004237 final NativeNetworkConfig config;
4238 if (nai.isVPN()) {
4239 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004240 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004241 return false;
4242 }
4243 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4244 INetd.PERMISSION_NONE,
4245 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
Chiachang Wang9164c102022-01-13 10:54:32 +08004246 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004247 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004248 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
4249 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
Chiachang Wangbf6b8792022-01-11 10:48:07 +08004250 VpnManager.TYPE_VPN_NONE, /*excludeLocalRoutes=*/ false);
Luke Huangfdd11f82019-04-09 18:41:49 +08004251 }
Ken Chen6df7a902021-04-09 15:08:42 +08004252 mNetd.networkCreate(config);
4253 mDnsResolver.createNetworkCache(nai.network.getNetId());
4254 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4255 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004256 return true;
4257 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004258 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004259 return false;
4260 }
4261 }
4262
Ken Chen6df7a902021-04-09 15:08:42 +08004263 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004264 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004265 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004266 } catch (RemoteException | ServiceSpecificException e) {
4267 loge("Exception destroying network(networkDestroy): " + e);
4268 }
4269 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004270 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004271 } catch (RemoteException | ServiceSpecificException e) {
4272 loge("Exception destroying network: " + e);
4273 }
4274 }
4275
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004276 // If this method proves to be too slow then we can maintain a separate
4277 // pendingIntent => NetworkRequestInfo map.
4278 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4279 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004280 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4281 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4282 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004283 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004284 return entry.getValue();
4285 }
4286 }
4287 return null;
4288 }
4289
Chalard Jean524f0b12021-10-25 21:11:56 +09004290 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4291 if (SdkLevel.isAtLeastT()) {
4292 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4293 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4294 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4295 // bug is fixed.
4296 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004297 throw new IllegalStateException("This NRI is already registered. New : " + nri
4298 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004299 }
4300 }
4301 }
4302 }
4303
Chalard Jeanac9ace02022-01-26 16:54:05 +09004304 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4305 @NonNull final NetworkCapabilities caps) {
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004306 if (SdkLevel.isAtLeastT() && mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004307 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4308 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004309 }
4310 return false;
4311 }
4312
James Mattisf7027322020-12-13 16:28:14 -08004313 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004314 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004315 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4316 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4317 final NetworkRequestInfo existingRequest =
4318 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004319 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004320 if (DBG) {
4321 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4322 + nri.mRequests.get(0) + " because their intents matched.");
4323 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004324 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004325 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004326 }
Erik Kline05f2b402015-04-30 12:58:40 +09004327 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004328 }
4329
James Mattisf7027322020-12-13 16:28:14 -08004330 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004331 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004332 }
4333
James Mattis3ce3d3c2021-02-09 18:18:28 -08004334 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004335 ensureRunningOnConnectivityServiceThread();
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004336 NetworkRequest requestToBeReleased = null;
James Mattis45d81842021-01-10 14:24:24 -08004337 for (final NetworkRequestInfo nri : nris) {
4338 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004339 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004340 for (final NetworkRequest req : nri.mRequests) {
4341 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004342 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004343 if (req.isListen()) {
4344 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4345 if (req.networkCapabilities.hasSignalStrength()
4346 && network.satisfiesImmutableCapabilitiesOf(req)) {
4347 updateSignalStrengthThresholds(network, "REGISTER", req);
4348 }
James Mattisf7027322020-12-13 16:28:14 -08004349 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004350 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004351 if (req.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004352 if (!hasCarrierPrivilegeForNetworkCaps(nri.mUid, req.networkCapabilities)
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004353 && !checkConnectivityRestrictedNetworksPermission(
4354 nri.mPid, nri.mUid)) {
4355 requestToBeReleased = req;
4356 }
4357 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004358 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004359
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004360 // If this NRI has a satisfier already, it is replacing an older request that
4361 // has been removed. Track it.
4362 final NetworkRequest activeRequest = nri.getActiveRequest();
4363 if (null != activeRequest) {
4364 // If there is an active request, then for sure there is a satisfier.
4365 nri.getSatisfier().addRequest(activeRequest);
4366 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004367 }
James Mattisf7027322020-12-13 16:28:14 -08004368
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004369 if (requestToBeReleased != null) {
4370 releaseNetworkRequestAndCallOnUnavailable(requestToBeReleased);
4371 return;
4372 }
4373
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004374 if (mFlags.noRematchAllRequestsOnRegister()) {
4375 rematchNetworksAndRequests(nris);
4376 } else {
4377 rematchAllNetworksAndRequests();
4378 }
James Mattis45d81842021-01-10 14:24:24 -08004379
Chalard Jean0354d8c2021-01-12 10:58:56 +09004380 // Requests that have not been matched to a network will not have been sent to the
4381 // providers, because the old satisfier and the new satisfier are the same (null in this
4382 // case). Send these requests to the providers.
4383 for (final NetworkRequestInfo nri : nris) {
4384 for (final NetworkOfferInfo noi : mNetworkOffers) {
4385 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004386 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004387 }
4388 }
4389
James Mattisf7027322020-12-13 16:28:14 -08004390 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4391 final int callingUid) {
4392 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004393 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004394 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4395 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4396 handleReleaseNetworkRequest(
4397 nri.mRequests.get(0),
4398 callingUid,
4399 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004400 }
4401 }
4402
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004403 // Determines whether the network is the best (or could become the best, if it validated), for
4404 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4405 // on the value of reason:
4406 //
4407 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4408 // then it should be torn down.
4409 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4410 // then it should be lingered.
4411 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004412 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004413
4414 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
4415 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4416 return false;
4417 }
4418
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004419 final int numRequests;
4420 switch (reason) {
4421 case TEARDOWN:
4422 numRequests = nai.numRequestNetworkRequests();
4423 break;
4424 case LINGER:
4425 numRequests = nai.numForegroundNetworkRequests();
4426 break;
4427 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004428 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004429 return true;
4430 }
4431
Chalard Jean947acd42021-03-08 22:29:27 +09004432 if (numRequests > 0) return false;
4433
Paul Jensende49eb12015-06-25 15:30:08 -04004434 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004435 if (reason == UnneededFor.LINGER
4436 && !nri.isMultilayerRequest()
4437 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004438 // Background requests don't affect lingering.
4439 continue;
4440 }
4441
James Mattis3d229892020-11-16 16:46:28 -08004442 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004443 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004444 }
4445 }
Paul Jensende49eb12015-06-25 15:30:08 -04004446 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004447 }
4448
James Mattis3d229892020-11-16 16:46:28 -08004449 private boolean isNetworkPotentialSatisfier(
4450 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4451 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004452 // request, return immediately. For multilayer requests, check to see if any of the
4453 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004454 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4455 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004456 return false;
4457 }
4458 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004459 // This multilayer listen request is satisfied therefore no further requests need to be
4460 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004461 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004462 return false;
4463 }
James Mattis3d229892020-11-16 16:46:28 -08004464 // As non-multilayer listen requests have already returned, the below would only happen
4465 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004466 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004467 continue;
4468 }
4469 // If this Network is already the highest scoring Network for a request, or if
4470 // there is hope for it to become one if it validated, then it is needed.
4471 if (candidate.satisfies(req)) {
4472 // As soon as a network is found that satisfies a request, return. Specifically for
4473 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4474 // is important so as to not evaluate lower priority requests further in
4475 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004476 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4477 ? nri.getSatisfier() : null;
4478 // Note that this catches two important cases:
4479 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4480 // is currently satisfying the request. This is desirable when
4481 // cellular ends up validating but WiFi does not.
4482 // 2. Unvalidated WiFi will not be reaped when validated cellular
4483 // is currently satisfying the request. This is desirable when
4484 // WiFi ends up validating and out scoring cellular.
4485 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004486 }
4487 }
4488
4489 return false;
4490 }
4491
Erik Kline0c04b742016-07-07 16:50:58 +09004492 private NetworkRequestInfo getNriForAppRequest(
4493 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004494 // Looking up the app passed param request in mRequests isn't possible since it may return
4495 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4496 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004497 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4498 // to avoid potential race conditions when validating a package->uid mapping when sending
4499 // the callback on the very low-chance that an application shuts down prior to the callback
4500 // being sent.
4501 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4502 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004503
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004504 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004505 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004506 log(String.format("UID %d attempted to %s for unowned request %s",
4507 callingUid, requestedOperation, nri));
4508 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004509 }
Erik Kline0c04b742016-07-07 16:50:58 +09004510 }
4511
4512 return nri;
4513 }
4514
James Mattisf7027322020-12-13 16:28:14 -08004515 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4516 final String callingMethod) {
4517 if (nri.isMultilayerRequest()) {
4518 throw new IllegalStateException(
4519 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004520 }
4521 }
4522
James Mattisf7027322020-12-13 16:28:14 -08004523 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004524 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004525 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4526 // single NetworkRequest and thus does not apply to multilayer requests.
4527 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4528 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004529 return;
4530 }
James Mattis2516da32021-01-31 17:06:19 -08004531 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004532 return;
4533 }
James Mattisf7027322020-12-13 16:28:14 -08004534 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4535 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004536 }
4537 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004538 callCallbackForRequest(
4539 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004540 }
4541
James Mattisf7027322020-12-13 16:28:14 -08004542 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4543 final int callingUid,
4544 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004545 final NetworkRequestInfo nri =
4546 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4547 if (nri == null) {
4548 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004549 }
James Mattisf7027322020-12-13 16:28:14 -08004550 if (VDBG || (DBG && request.isRequest())) {
4551 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004552 }
4553 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004554 if (callOnUnavailable) {
4555 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4556 }
Erik Kline155a59a2015-11-25 12:49:38 +09004557 }
Erik Kline0c04b742016-07-07 16:50:58 +09004558
James Mattisa076c532020-12-02 14:12:41 -08004559 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004560 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004561 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004562 if (null == mNetworkRequests.remove(req)) {
4563 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4564 continue;
4565 }
James Mattisa076c532020-12-02 14:12:41 -08004566 if (req.isListen()) {
4567 removeListenRequestFromNetworks(req);
4568 }
4569 }
James Mattis8f036802021-06-20 16:26:01 -07004570 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004571 if (mDefaultNetworkRequests.remove(nri)) {
4572 // If this request was one of the defaults, then the UID rules need to be updated
4573 // WARNING : if the app(s) for which this network request is the default are doing
4574 // traffic, this will kill their connected sockets, even if an equivalent request
4575 // is going to be reinstated right away ; unconnected traffic will go on the default
4576 // until the new default is set, which will happen very soon.
4577 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4578 // remove ranges for those requests that won't have a replacement
4579 final NetworkAgentInfo satisfier = nri.getSatisfier();
4580 if (null != satisfier) {
4581 try {
paulhu0e79d952021-06-09 16:11:35 +08004582 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4583 satisfier.network.getNetId(),
4584 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004585 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004586 } catch (RemoteException e) {
4587 loge("Exception setting network preference default network", e);
4588 }
4589 }
4590 }
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09004591 nri.decrementRequestCount();
Erik Kline0c04b742016-07-07 16:50:58 +09004592 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004593 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004594
4595 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004596 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004597 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004598 }
4599 }
4600
Chalard Jean0354d8c2021-01-12 10:58:56 +09004601 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4602 // needed for this offer.
4603 for (final NetworkOfferInfo noi : mNetworkOffers) {
4604 for (final NetworkRequest req : nri.mRequests) {
4605 if (req.isRequest() && noi.offer.neededFor(req)) {
4606 noi.offer.onNetworkUnneeded(req);
4607 }
4608 }
4609 }
James Mattisa076c532020-12-02 14:12:41 -08004610 }
4611
James Mattis3ce3d3c2021-02-09 18:18:28 -08004612 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4613 for (final NetworkRequestInfo nri : nris) {
4614 if (mDefaultRequest == nri) {
4615 // Make sure we never remove the default request.
4616 continue;
4617 }
4618 handleRemoveNetworkRequest(nri);
4619 }
4620 }
4621
James Mattisa076c532020-12-02 14:12:41 -08004622 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4623 // listens don't have a singular affected Network. Check all networks to see
4624 // if this listen request applies and remove it.
4625 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4626 nai.removeRequest(req.requestId);
4627 if (req.networkCapabilities.hasSignalStrength()
4628 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4629 updateSignalStrengthThresholds(nai, "RELEASE", req);
4630 }
4631 }
4632 }
4633
4634 /**
4635 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4636 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4637 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4638 */
4639 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4640 boolean wasKept = false;
4641 final NetworkAgentInfo nai = nri.getSatisfier();
4642 if (nai != null) {
4643 final int requestLegacyType = nri.getActiveRequest().legacyType;
4644 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4645 nai.removeRequest(nri.getActiveRequest().requestId);
4646 if (VDBG || DDBG) {
4647 log(" Removing from current network " + nai.toShortString()
4648 + ", leaving " + nai.numNetworkRequests() + " requests.");
4649 }
4650 // If there are still lingered requests on this network, don't tear it down,
4651 // but resume lingering instead.
4652 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004653 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004654 notifyNetworkLosing(nai, now);
4655 }
4656 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4657 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4658 teardownUnneededNetwork(nai);
4659 } else {
4660 wasKept = true;
4661 }
James Mattisa076c532020-12-02 14:12:41 -08004662 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4663 // Went from foreground to background.
4664 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004665 }
4666
Erik Kline0c04b742016-07-07 16:50:58 +09004667 // Maintain the illusion. When this request arrived, we might have pretended
4668 // that a network connected to serve it, even though the network was already
4669 // connected. Now that this request has gone away, we might have to pretend
4670 // that the network disconnected. LegacyTypeTracker will generate that
4671 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004672 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004673 boolean doRemove = true;
4674 if (wasKept) {
4675 // check if any of the remaining requests for this network are for the
4676 // same legacy type - if so, don't remove the nai
4677 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4678 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004679 if (otherRequest.legacyType == requestLegacyType
4680 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004681 if (DBG) log(" still have other legacy request - leaving");
4682 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004683 }
4684 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004685 }
4686
Erik Kline0c04b742016-07-07 16:50:58 +09004687 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004688 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004689 }
4690 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004691 }
4692 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004693
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004694 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4695 return checkAnyPermissionOf(
4696 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4697 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4698 }
4699
Lorenzo Colittid6459092016-07-04 12:55:44 +09004700 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004701 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004702 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004703 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004704 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004705 }
4706
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004707 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004708 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4709 enforceNetworkStackSettingsOrSetup();
4710 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4711 encodeBool(accept), encodeBool(always), network));
4712 }
4713
4714 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004715 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004716 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004717 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4718 }
4719
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004720 @Override
4721 public void setTestAllowBadWifiUntil(long timeMs) {
4722 enforceSettingsPermission();
4723 if (!Build.isDebuggable()) {
4724 throw new IllegalStateException("Does not support in non-debuggable build");
4725 }
4726
4727 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4728 throw new IllegalArgumentException("It should not exceed "
4729 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4730 }
4731
4732 mHandler.sendMessage(
4733 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4734 }
4735
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004736 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4737 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4738 " accept=" + accept + " always=" + always);
4739
4740 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4741 if (nai == null) {
4742 // Nothing to do.
4743 return;
4744 }
4745
4746 if (nai.everValidated) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004747 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004748 return;
4749 }
4750
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004751 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004752 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004753 }
4754
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004755 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4756 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004757 // If network becomes partial connectivity and user already accepted to use this
4758 // network, we should respect the user's option and don't need to popup the
4759 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004760 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004761 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004762 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004763 }
4764
4765 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004766 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004767 }
4768
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004769 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004770 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004771 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004772 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004773 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004774 }
4775
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004776 }
4777
lucaslin2240ef62019-03-12 13:08:03 +08004778 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4779 boolean always) {
4780 if (DBG) {
4781 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4782 + " always=" + always);
4783 }
4784
4785 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4786 if (nai == null) {
4787 // Nothing to do.
4788 return;
4789 }
4790
4791 if (nai.lastValidated) {
4792 // The network validated while the dialog box was up. Take no action.
4793 return;
4794 }
4795
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004796 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4797 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004798 }
4799
4800 // TODO: Use the current design or save the user choice into IpMemoryStore.
4801 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004802 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004803 }
4804
4805 if (!accept) {
4806 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004807 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08004808 // Tear down the network.
4809 teardownUnneededNetwork(nai);
4810 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08004811 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4812 // result in a partial connectivity result which will be processed by
4813 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08004814 //
4815 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4816 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004817 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08004818 }
4819 }
4820
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004821 private void handleSetAvoidUnvalidated(Network network) {
4822 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4823 if (nai == null || nai.lastValidated) {
4824 // Nothing to do. The network either disconnected or revalidated.
4825 return;
4826 }
4827 if (!nai.avoidUnvalidated) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004828 nai.avoidUnvalidated = true;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004829 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004830 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004831 }
4832 }
4833
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004834 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09004835 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004836 mHandler.sendMessageDelayed(
4837 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4838 PROMPT_UNVALIDATED_DELAY_MS);
4839 }
4840
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004841 @Override
4842 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004843 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004844 mHandler.post(() -> {
4845 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4846 if (nai == null) return;
4847 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004848 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004849 });
4850 }
4851
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004852 /**
4853 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4854 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004855 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004856 * @param appExtras Bundle to use as intent extras for the captive portal application.
4857 * Must be treated as opaque to avoid preventing the captive portal app to
4858 * update its arguments.
4859 */
4860 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004861 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08004862 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4863 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004864
4865 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4866 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004867 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4868 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004869 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4870
lucaslin75ff7022020-12-17 04:14:35 +08004871 final long token = Binder.clearCallingIdentity();
4872 try {
4873 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4874 } finally {
4875 Binder.restoreCallingIdentity(token);
4876 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004877 }
4878
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004879 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4880 private final Network mNetwork;
4881
4882 private CaptivePortalImpl(Network network) {
4883 mNetwork = network;
4884 }
4885
4886 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004887 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004888 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4889 enforceSettingsPermission();
4890 }
4891
Chiachang Wang938bfba2020-01-09 13:50:55 +08004892 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004893 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004894 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004895 }
4896
4897 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08004898 public void appRequest(final int request) {
4899 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4900 if (nm == null) return;
4901
4902 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08004903 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09004904 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08004905 }
4906 }
4907
4908 @Nullable
4909 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4910 // getNetworkAgentInfoForNetwork is thread-safe
4911 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4912 if (nai == null) return null;
4913
4914 // nai.networkMonitor() is thread-safe
4915 return nai.networkMonitor();
4916 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004917 }
4918
Hugo Benichic9048bc2016-09-14 23:23:08 +00004919 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004920 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09004921 }
4922
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004923 /**
4924 * Return whether the device should maintain continuous, working connectivity by switching away
4925 * from WiFi networks having no connectivity.
4926 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4927 */
4928 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004929 if (!checkNetworkStackPermission()) {
4930 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4931 }
4932 return avoidBadWifi();
4933 }
4934
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004935 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09004936 ensureRunningOnConnectivityServiceThread();
4937 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004938 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09004939 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004940 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09004941 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
4942 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
4943 for (final NetworkOfferInfo noi : offersToUpdate) {
4944 updateOfferScore(noi.offer);
4945 }
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004946 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004947 }
4948
Erik Kline95ecfee2016-10-02 18:02:14 +09004949 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004950 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004951 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004952 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004953 if (!configRestrict) {
4954 pw.println("Bad Wi-Fi avoidance: unrestricted");
4955 return;
4956 }
4957
4958 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4959 pw.increaseIndent();
4960 pw.println("Config restrict: " + configRestrict);
4961
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004962 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004963 String description;
4964 // Can't use a switch statement because strings are legal case labels, but null is not.
4965 if ("0".equals(value)) {
4966 description = "get stuck";
4967 } else if (value == null) {
4968 description = "prompt";
4969 } else if ("1".equals(value)) {
4970 description = "avoid";
4971 } else {
4972 description = value + " (?)";
4973 }
4974 pw.println("User setting: " + description);
4975 pw.println("Network overrides:");
4976 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09004977 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004978 if (nai.avoidUnvalidated) {
Chalard Jean49707572019-12-10 21:07:02 +09004979 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004980 }
4981 }
4982 pw.decreaseIndent();
4983 pw.decreaseIndent();
4984 }
4985
paulhu7746e4e2020-06-09 19:07:03 +08004986 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4987 // unify the method.
4988 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4989 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4990 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4991 return settingsComponent != null
4992 ? settingsComponent.getPackageName() : "com.android.settings";
4993 }
4994
lucaslinb1e8e382019-01-24 15:55:30 +08004995 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004996 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004997 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004998 switch (type) {
4999 case NO_INTERNET:
5000 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005001 // High priority because it is only displayed for explicitly selected networks.
5002 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005003 break;
lucasline117e2e2019-10-22 18:27:33 +08005004 case PRIVATE_DNS_BROKEN:
5005 action = Settings.ACTION_WIRELESS_SETTINGS;
5006 // High priority because we should let user know why there is no internet.
5007 highPriority = true;
5008 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005009 case LOST_INTERNET:
5010 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005011 // High priority because it could help the user avoid unexpected data usage.
5012 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005013 break;
lucaslin2240ef62019-03-12 13:08:03 +08005014 case PARTIAL_CONNECTIVITY:
5015 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005016 // Don't bother the user with a high-priority notification if the network was not
5017 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005018 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005019 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005020 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005021 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005022 return;
5023 }
5024
5025 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005026 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005027 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005028 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005029 // Some OEMs have their own Settings package. Thus, need to get the current using
5030 // Settings package name instead of just use default name "com.android.settings".
5031 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5032 intent.setClassName(settingsPkgName,
5033 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005034 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005035
paulhu2af50222020-10-11 22:52:27 +08005036 PendingIntent pendingIntent = PendingIntent.getActivity(
5037 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005038 0 /* requestCode */,
5039 intent,
paulhu2af50222020-10-11 22:52:27 +08005040 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005041
Serik Beketayevec8ad212020-12-07 22:43:07 -08005042 mNotifier.showNotification(
5043 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005044 }
5045
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005046 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5047 // Don't prompt if the network is validated, and don't prompt on captive portals
5048 // because we're already prompting the user to sign in.
5049 if (nai.everValidated || nai.everCaptivePortalDetected) {
5050 return false;
5051 }
5052
5053 // If a network has partial connectivity, always prompt unless the user has already accepted
5054 // partial connectivity and selected don't ask again. This ensures that if the device
5055 // automatically connects to a network that has partial Internet access, the user will
5056 // always be able to use it, either because they've already chosen "don't ask again" or
5057 // because we have prompt them.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005058 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005059 return true;
5060 }
5061
5062 // If a network has no Internet access, only prompt if the network was explicitly selected
5063 // and if the user has not already told us to use the network regardless of whether it
5064 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005065 if (nai.networkAgentConfig.explicitlySelected
5066 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005067 return true;
5068 }
5069
5070 return false;
5071 }
5072
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005073 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09005074 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005075 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5076
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005077 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005078 return;
5079 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005080
5081 // Stop automatically reconnecting to this network in the future. Automatically connecting
5082 // to a network that provides no or limited connectivity is not useful, because the user
5083 // cannot use that network except through the notification shown by this method, and the
5084 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005085 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005086
lucaslin2240ef62019-03-12 13:08:03 +08005087 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
5088 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
5089 // popup the notification immediately when the network is partial connectivity.
5090 if (nai.partialConnectivity) {
lucasline0118ab2019-03-21 11:59:22 +08005091 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005092 } else {
5093 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5094 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005095 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005096
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005097 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5098 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005099 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005100
lucaslin2240ef62019-03-12 13:08:03 +08005101 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5102 return;
5103 }
5104
5105 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005106 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005107 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005108 }
5109
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005110 @Override
5111 public int getMultipathPreference(Network network) {
5112 enforceAccessPermission();
5113
5114 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005115 if (nai != null && nai.networkCapabilities
5116 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005117 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5118 }
5119
Aaron Huang9a57acf2020-12-08 10:03:29 +08005120 final NetworkPolicyManager netPolicyManager =
5121 mContext.getSystemService(NetworkPolicyManager.class);
5122
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005123 final long token = Binder.clearCallingIdentity();
5124 final int networkPreference;
5125 try {
5126 networkPreference = netPolicyManager.getMultipathPreference(network);
5127 } finally {
5128 Binder.restoreCallingIdentity(token);
5129 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005130 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005131 return networkPreference;
5132 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005133 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5134 }
5135
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005136 @Override
5137 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005138 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005139 }
5140
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005141 private class InternalHandler extends Handler {
5142 public InternalHandler(Looper looper) {
5143 super(looper);
5144 }
5145
5146 @Override
5147 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005148 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005149 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005150 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005151 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005152 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005153 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005154 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005155 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005156 break;
5157 }
Jason Monka69f1b02013-10-10 14:02:51 -04005158 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005159 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5160 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005161 break;
5162 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005163 case EVENT_REGISTER_NETWORK_PROVIDER: {
5164 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005165 break;
5166 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005167 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5168 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005169 break;
5170 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005171 case EVENT_REGISTER_NETWORK_OFFER: {
5172 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5173 break;
5174 }
5175 case EVENT_UNREGISTER_NETWORK_OFFER: {
5176 final NetworkOfferInfo offer =
5177 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5178 if (null != offer) {
5179 handleUnregisterNetworkOffer(offer);
5180 }
5181 break;
5182 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005183 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005184 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5185 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5186 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005187 break;
5188 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005189 case EVENT_REGISTER_NETWORK_REQUEST:
5190 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005191 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005192 break;
5193 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005194 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5195 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005196 handleRegisterNetworkRequestWithIntent(msg);
5197 break;
5198 }
Erik Kline155a59a2015-11-25 12:49:38 +09005199 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5200 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5201 handleTimedOutNetworkRequest(nri);
5202 break;
5203 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005204 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5205 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5206 break;
5207 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005208 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005209 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5210 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005211 break;
5212 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005213 case EVENT_RELEASE_NETWORK_REQUEST_AND_CALL_UNAVAILABLE: {
5214 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5215 /* callOnUnavailable */ true);
5216 break;
5217 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005218 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005219 Network network = (Network) msg.obj;
5220 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005221 break;
5222 }
lucaslin2240ef62019-03-12 13:08:03 +08005223 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5224 Network network = (Network) msg.obj;
5225 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5226 toBool(msg.arg2));
5227 break;
5228 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005229 case EVENT_SET_AVOID_UNVALIDATED: {
5230 handleSetAvoidUnvalidated((Network) msg.obj);
5231 break;
5232 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005233 case EVENT_PROMPT_UNVALIDATED: {
5234 handlePromptUnvalidated((Network) msg.obj);
5235 break;
5236 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005237 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5238 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005239 break;
5240 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005241 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005242 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005243 mKeepaliveTracker.handleStartKeepalive(msg);
5244 break;
5245 }
5246 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005247 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005248 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5249 int slot = msg.arg1;
5250 int reason = msg.arg2;
5251 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
5252 break;
5253 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005254 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5255 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5256 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005257 break;
5258 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005259 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5260 handlePrivateDnsSettingsChanged();
5261 break;
dalyk1720e542018-03-05 12:42:22 -05005262 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5263 handlePrivateDnsValidationUpdate(
5264 (PrivateDnsValidationUpdate) msg.obj);
5265 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005266 case EVENT_UID_BLOCKED_REASON_CHANGED:
5267 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005268 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005269 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5270 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5271 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005272 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005273 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5274 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005275 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005276 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005277 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005278 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005279 final Pair<List<ProfileNetworkPreferenceList.Preference>,
5280 IOnCompleteListener> arg =
5281 (Pair<List<ProfileNetworkPreferenceList.Preference>,
5282 IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005283 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005284 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005285 }
lucaslin1193a5d2021-01-21 02:04:15 +08005286 case EVENT_REPORT_NETWORK_ACTIVITY:
5287 mNetworkActivityTracker.handleReportNetworkActivity();
5288 break;
paulhu51f77dc2021-06-07 02:34:20 +00005289 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5290 handleMobileDataPreferredUidsChanged();
5291 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005292 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5293 final long timeMs = ((Long) msg.obj).longValue();
5294 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5295 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005296 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5297 handleIngressRateLimitChanged();
5298 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005299 }
5300 }
5301 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005302
Lorenzo Colittid6459092016-07-04 12:55:44 +09005303 @Override
markchien5776f962019-12-16 20:15:20 +08005304 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005305 public int getLastTetherError(String iface) {
markchien5776f962019-12-16 20:15:20 +08005306 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5307 Context.TETHERING_SERVICE);
5308 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005309 }
5310
Lorenzo Colittid6459092016-07-04 12:55:44 +09005311 @Override
markchien5776f962019-12-16 20:15:20 +08005312 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005313 public String[] getTetherableIfaces() {
markchien5776f962019-12-16 20:15:20 +08005314 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5315 Context.TETHERING_SERVICE);
5316 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005317 }
5318
Lorenzo Colittid6459092016-07-04 12:55:44 +09005319 @Override
markchien5776f962019-12-16 20:15:20 +08005320 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005321 public String[] getTetheredIfaces() {
markchien5776f962019-12-16 20:15:20 +08005322 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5323 Context.TETHERING_SERVICE);
5324 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005325 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005326
markchien5776f962019-12-16 20:15:20 +08005327
Lorenzo Colittid6459092016-07-04 12:55:44 +09005328 @Override
markchien5776f962019-12-16 20:15:20 +08005329 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005330 public String[] getTetheringErroredIfaces() {
markchien5776f962019-12-16 20:15:20 +08005331 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5332 Context.TETHERING_SERVICE);
5333
5334 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005335 }
5336
Lorenzo Colittid6459092016-07-04 12:55:44 +09005337 @Override
markchien5776f962019-12-16 20:15:20 +08005338 @Deprecated
5339 public String[] getTetherableUsbRegexs() {
5340 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5341 Context.TETHERING_SERVICE);
5342
5343 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005344 }
5345
Udam Saini8f7d6a72017-06-07 12:06:28 -07005346 @Override
markchien5776f962019-12-16 20:15:20 +08005347 @Deprecated
5348 public String[] getTetherableWifiRegexs() {
5349 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5350 Context.TETHERING_SERVICE);
5351 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005352 }
5353
Robert Greenwalte0b00512014-07-02 09:59:16 -07005354 // Called when we lose the default network and have no replacement yet.
5355 // This will automatically be cleared after X seconds or a new default network
5356 // becomes CONNECTED, whichever happens first. The timer is started by the
5357 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005358 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005359 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005360 if (mNetTransitionWakeLock.isHeld()) {
5361 return;
5362 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005363 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005364 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5365 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005366 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005367 mWakelockLogs.log("ACQUIRE for " + forWhom);
5368 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005369 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005370 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005371 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005372 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005373
Hugo Benichi471b62a2017-03-30 23:18:10 +09005374 // Called when we gain a new default network to release the network transition wakelock in a
5375 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5376 // message is cancelled.
5377 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005378 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005379 if (!mNetTransitionWakeLock.isHeld()) {
5380 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005381 }
5382 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005383 // Cancel self timeout on wakelock hold.
5384 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5385 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5386 mHandler.sendMessageDelayed(msg, 1000);
5387 }
5388
5389 // Called when either message of ensureNetworkTransitionWakelock or
5390 // scheduleReleaseNetworkTransitionWakelock is processed.
5391 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5392 String event = eventName(eventId);
5393 synchronized (this) {
5394 if (!mNetTransitionWakeLock.isHeld()) {
5395 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005396 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005397 return;
5398 }
5399 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005400 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5401 mTotalWakelockDurationMs += lockDuration;
5402 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5403 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005404 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005405 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005406 }
5407
Robert Greenwalt986c7412010-09-08 15:24:47 -07005408 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005409 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005410 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005411 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005412 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005413 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005414 }
5415
Lorenzo Colittid6459092016-07-04 12:55:44 +09005416 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005417 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005418 enforceAccessPermission();
5419 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005420 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005421 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005422
5423 final NetworkAgentInfo nai;
5424 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005425 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005426 } else {
5427 nai = getNetworkAgentInfoForNetwork(network);
5428 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005429
5430 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005431 mHandler.obtainMessage(
5432 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005433 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005434
Hugo Benichid6b510a2017-04-06 17:22:18 +09005435 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005436 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005437 if (nai == null
5438 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005439 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005440 return;
5441 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005442 // Revalidate if the app report does not match our current validated state.
Hugo Benichie9d321b2017-04-06 16:01:44 +09005443 if (hasConnectivity == nai.lastValidated) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005444 mConnectivityDiagnosticsHandler.sendMessage(
5445 mConnectivityDiagnosticsHandler.obtainMessage(
5446 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5447 new ReportedNetworkConnectivityInfo(
5448 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005449 return;
5450 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005451 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005452 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005453 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005454 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005455 // Validating a network that has not yet connected could result in a call to
5456 // rematchNetworkAndRequests() which is not meant to work on such networks.
5457 if (!nai.everConnected) {
5458 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005459 }
paulhu7aeba372020-12-30 00:42:19 +08005460 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5461 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005462 return;
5463 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005464
5465 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5466 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5467 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5468 // completed.
5469 mConnectivityDiagnosticsHandler.sendMessage(
5470 mConnectivityDiagnosticsHandler.obtainMessage(
5471 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5472 new ReportedNetworkConnectivityInfo(
5473 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005474 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005475 }
5476
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005477 // TODO: call into netd.
5478 private boolean queryUserAccess(int uid, Network network) {
5479 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5480 if (nai == null) return false;
5481
5482 // Any UID can use its default network.
5483 if (nai == getDefaultNetworkForUid(uid)) return true;
5484
5485 // Privileged apps can use any network.
5486 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5487 return true;
5488 }
5489
5490 // An unprivileged UID can use a VPN iff the VPN applies to it.
5491 if (nai.isVPN()) {
5492 return nai.networkCapabilities.appliesToUid(uid);
5493 }
5494
5495 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5496 // sockets, i.e., if it is the owner.
5497 final NetworkAgentInfo vpn = getVpnForUid(uid);
5498 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5499 && uid != vpn.networkCapabilities.getOwnerUid()) {
5500 return false;
5501 }
5502
5503 // The UID's permission must be at least sufficient for the network. Since the restricted
5504 // permission was already checked above, that just leaves background networks.
5505 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5506 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5507 }
5508
5509 // Unrestricted network. Anyone gets to use it.
5510 return true;
5511 }
5512
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005513 /**
5514 * Returns information about the proxy a certain network is using. If given a null network, it
5515 * it will return the proxy for the bound network for the caller app or the default proxy if
5516 * none.
5517 *
5518 * @param network the network we want to get the proxy information for.
5519 * @return Proxy information if a network has a proxy configured, or otherwise null.
5520 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005521 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005522 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005523 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005524 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005525 if (network == null) {
5526 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005527 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005528 true);
5529 if (activeNetwork == null) {
5530 return null;
5531 }
5532 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005533 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005534 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5535 // caller may not have.
5536 return getLinkPropertiesProxyInfo(network);
5537 }
5538 // No proxy info available if the calling UID does not have network access.
5539 return null;
5540 }
5541
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005542
5543 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005544 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5545 if (nai == null) return null;
5546 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005547 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5548 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005549 }
5550 }
5551
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005552 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005553 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhudf23d662021-01-25 18:53:17 +08005554 PermissionUtils.enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005555 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005556 }
5557
Chalard Jean777e2e52018-06-07 18:02:37 +09005558 @Override
5559 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005560 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005561 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005562 }
5563
Jason Monk4d5e20f2014-04-25 15:00:09 -04005564 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005565 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005566 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005567 proxy = null;
5568 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005569 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005570 }
5571
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005572 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5573 // when any network changes proxy.
5574 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5575 // multi-network world where an app might be bound to a non-default network.
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005576 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensenc0618a62014-12-10 15:12:18 -05005577 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5578 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5579
Chalard Jean7d97afc2018-06-07 17:41:29 +09005580 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005581 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005582 }
5583 }
5584
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005585 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005586 final private HashMap<Uri, Integer> mUriEventMap;
5587 final private Context mContext;
5588 final private Handler mHandler;
5589
5590 SettingsObserver(Context context, Handler handler) {
5591 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005592 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005593 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005594 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005595 }
5596
Erik Kline05f2b402015-04-30 12:58:40 +09005597 void observe(Uri uri, int what) {
5598 mUriEventMap.put(uri, what);
5599 final ContentResolver resolver = mContext.getContentResolver();
5600 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005601 }
5602
5603 @Override
5604 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005605 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005606 }
5607
5608 @Override
5609 public void onChange(boolean selfChange, Uri uri) {
5610 final Integer what = mUriEventMap.get(uri);
5611 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005612 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005613 } else {
5614 loge("No matching event to send for URI=" + uri);
5615 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005616 }
5617 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005618
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005619 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005620 Log.d(TAG, s);
5621 }
5622
5623 private static void logw(String s) {
5624 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005625 }
5626
Daniel Brightf9e945b2020-06-15 16:10:01 -07005627 private static void logwtf(String s) {
5628 Log.wtf(TAG, s);
5629 }
5630
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005631 private static void logwtf(String s, Throwable t) {
5632 Log.wtf(TAG, s, t);
5633 }
5634
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005635 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005636 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005637 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005638
Hugo Benichi39621362017-02-11 17:04:43 +09005639 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005640 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005641 }
5642
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005643 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005644 * Return the information of all ongoing VPNs.
5645 *
5646 * <p>This method is used to update NetworkStatsService.
5647 *
5648 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005649 */
junyulai2050bed2021-01-23 09:46:34 +08005650 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005651 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005652 if (mLockdownEnabled) {
5653 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005654 }
junyulai2050bed2021-01-23 09:46:34 +08005655 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005656 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005657 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005658 if (info != null) {
5659 infoList.add(info);
5660 }
5661 }
junyulai2050bed2021-01-23 09:46:34 +08005662 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005663 }
5664
5665 /**
5666 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005667 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005668 */
junyulai2050bed2021-01-23 09:46:34 +08005669 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005670 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005671 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5672 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005673 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5674 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5675 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08005676 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5677 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005678 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005679 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005680 }
5681 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005682
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005683 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005684
5685 List<String> interfaces = new ArrayList<>();
5686 for (Network network : underlyingNetworks) {
5687 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5688 if (underlyingNai == null) continue;
5689 LinkProperties lp = underlyingNai.linkProperties;
5690 for (String iface : lp.getAllInterfaceNames()) {
5691 if (!TextUtils.isEmpty(iface)) {
5692 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005693 }
5694 }
Benedict Wong34857f82019-06-12 17:46:15 +00005695 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005696
5697 if (interfaces.isEmpty()) return null;
5698
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005699 // Must be non-null or NetworkStatsService will crash.
5700 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5701 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005702 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005703 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005704
junyulai2050bed2021-01-23 09:46:34 +08005705 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5706 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005707 }
5708
James Mattisd31bdfa2020-12-23 16:37:26 -08005709 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005710 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5711 Network[] underlyingNetworks) {
5712 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005713 if (underlyingNetworks == null && defaultNetwork != null) {
5714 // null underlying networks means to track the default.
5715 underlyingNetworks = new Network[] { defaultNetwork };
5716 }
5717 return underlyingNetworks;
5718 }
5719
5720 // Returns true iff |network| is an underlying network of |nai|.
5721 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5722 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5723 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005724 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005725 final Network[] underlying = underlyingNetworksOrDefault(
5726 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005727 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005728 }
5729
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005730 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005731 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005732 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005733 * When underlying networks change, such networks may have to update capabilities to reflect
5734 * things like the metered bit, their transports, and so on. The capabilities are calculated
5735 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005736 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005737 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005738 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005739 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005740 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005741 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005742 }
5743 }
5744 }
5745
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005746 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5747 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5748 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5749 // a VPN is not up.
5750 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5751 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5752 for (UidRange range : blockedUidRanges) {
5753 if (range.contains(uid)) return true;
5754 }
5755 return false;
5756 }
5757
5758 @Override
5759 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005760 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005761 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5762 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5763 }
5764
5765 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5766 if (DBG) {
5767 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5768 + Arrays.toString(ranges));
5769 }
5770 // Cannot use a Set since the list of UID ranges might contain duplicates.
5771 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5772 for (int i = 0; i < ranges.length; i++) {
5773 if (requireVpn) {
5774 newVpnBlockedUidRanges.add(ranges[i]);
5775 } else {
5776 newVpnBlockedUidRanges.remove(ranges[i]);
5777 }
5778 }
5779
5780 try {
5781 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5782 } catch (RemoteException | ServiceSpecificException e) {
5783 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5784 + Arrays.toString(ranges) + "): netd command failed: " + e);
5785 }
5786
5787 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5788 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005789 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5790 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005791 }
5792
5793 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5794 }
5795
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005796 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005797 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005798 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005799 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005800 }
5801
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005802 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5803 return mLockdownEnabled
5804 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5805 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005806 }
5807
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005808 private NetworkAgentInfo getLegacyLockdownNai() {
5809 if (!mLockdownEnabled) {
5810 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005811 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005812 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005813 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5814 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005815
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005816 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005817 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5818 // a local variable. There is no need to make a copy because its contents cannot change.
5819 final Network[] underlying = nai.declaredUnderlyingNetworks;
5820 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005821 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005822 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005823
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005824 // The legacy lockdown VPN always uses the default network.
5825 // If the VPN's underlying network is no longer the current default network, it means that
5826 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005827 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5828 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005829 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005830 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005831 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005832 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005833
5834 return nai;
5835 };
5836
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005837 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5838 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5839 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005840 private DetailedState getLegacyLockdownState(DetailedState origState) {
5841 if (origState != DetailedState.CONNECTED) {
5842 return origState;
5843 }
5844 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5845 ? DetailedState.CONNECTING
5846 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005847 }
5848
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005849 private void filterForLegacyLockdown(NetworkInfo ni) {
5850 if (!mLockdownEnabled || !ni.isConnected()) return;
5851 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5852 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5853 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5854 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5855 // network, this time with a state of CONNECTED.
5856 //
5857 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5858 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5859 // is not too far off the truth, since an always-on VPN, when not connected, is always
5860 // trying to reconnect.
5861 if (getLegacyLockdownNai() == null) {
5862 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5863 }
5864 }
5865
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005866 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005867 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04005868 String action) {
paulhu8e96a752019-08-12 16:25:11 +08005869 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09005870 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5871 return;
5872 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04005873 final long ident = Binder.clearCallingIdentity();
5874 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09005875 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09005876 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09005877 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04005878 } finally {
5879 Binder.restoreCallingIdentity(ident);
5880 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005881 }
Wink Savillecb117d32013-08-29 14:57:08 -07005882
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005883 @Override
5884 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01005885 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005886 final long ident = Binder.clearCallingIdentity();
5887 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005888 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09005889 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005890 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5891 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08005892 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005893 } finally {
5894 Binder.restoreCallingIdentity(ident);
5895 }
5896 }
5897
James Mattis02220e22021-03-13 19:27:21 -08005898 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005899 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08005900 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5901 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5902 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005903 }
5904
James Mattis02220e22021-03-13 19:27:21 -08005905 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005906 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09005907 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005908 handleSetProfileNetworkPreference(
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08005909 List.of(new ProfileNetworkPreferenceList.Preference(user, null, true)),
Chalard Jean0f57a492021-03-09 21:09:20 +09005910 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08005911 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5912 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5913 }
junyulaid91e7052020-08-28 13:44:33 +08005914 }
5915
James Mattis02220e22021-03-13 19:27:21 -08005916 private void onPackageChanged(@NonNull final String packageName) {
5917 // This is necessary in case a package is added or removed, but also when it's replaced to
5918 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5919 // as one in the preferences, then it should follow the same routing as that other package,
5920 // which means updating the rules is never to be needed in this case (whether it joins or
5921 // leaves a UID with a preference).
5922 if (isMappedInOemNetworkPreference(packageName)) {
5923 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5924 }
5925 }
5926
5927 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005928 @Override
5929 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09005930 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005931 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005932 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08005933
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005934 // User should be filled for below intents, check the existence.
5935 if (user == null) {
5936 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5937 return;
5938 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005939
Lorenzo Colitticd675292021-02-04 17:32:07 +09005940 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005941 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005942 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005943 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09005944 } else {
junyulaid91e7052020-08-28 13:44:33 +08005945 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005946 }
5947 }
5948 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07005949
James Mattis02220e22021-03-13 19:27:21 -08005950 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5951 @Override
5952 public void onReceive(Context context, Intent intent) {
5953 ensureRunningOnConnectivityServiceThread();
5954 switch (intent.getAction()) {
5955 case Intent.ACTION_PACKAGE_ADDED:
5956 case Intent.ACTION_PACKAGE_REMOVED:
5957 case Intent.ACTION_PACKAGE_REPLACED:
5958 onPackageChanged(intent.getData().getSchemeSpecificPart());
5959 break;
5960 default:
5961 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5962 }
5963 }
5964 };
5965
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005966 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005967 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005968
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005969 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005970 public final String name;
5971 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005972 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005973 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005974
lifraf3a3492021-03-10 13:58:14 +08005975 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5976 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005977 this.name = name;
5978 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005979 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005980 mDeathRecipient = deathRecipient;
5981
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005982 if (mDeathRecipient == null) {
5983 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005984 }
5985 }
5986
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005987 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005988 try {
5989 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5990 } catch (RemoteException e) {
5991 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005992 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005993 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005994 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005995
James Mattis4fce5d12020-11-12 15:53:42 -08005996 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5997 for (int i = 0; i < requests.size(); i++) {
5998 ensureNetworkRequestHasType(requests.get(i));
5999 }
6000 }
6001
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006002 private void ensureNetworkRequestHasType(NetworkRequest request) {
6003 if (request.type == NetworkRequest.Type.NONE) {
6004 throw new IllegalArgumentException(
6005 "All NetworkRequests in ConnectivityService must have a type");
6006 }
6007 }
6008
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006009 /**
6010 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006011 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006012 */
James Mattis258ea3c2020-11-15 15:04:40 -08006013 @VisibleForTesting
6014 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006015 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6016 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006017 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006018
James Mattisa076c532020-12-02 14:12:41 -08006019 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6020 void setSatisfier(
6021 @Nullable final NetworkAgentInfo satisfier,
6022 @Nullable final NetworkRequest activeRequest) {
6023 mSatisfier = satisfier;
6024 mActiveRequest = activeRequest;
6025 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006026
James Mattisd31bdfa2020-12-23 16:37:26 -08006027 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006028 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006029 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006030 private NetworkAgentInfo mSatisfier;
6031 NetworkAgentInfo getSatisfier() {
6032 return mSatisfier;
6033 }
6034
6035 // The request in mRequests assigned to a network agent. This is null if none of the
6036 // requests in mRequests can be satisfied. This member has the constraint of only being
6037 // accessible on the handler thread.
6038 @Nullable
6039 private NetworkRequest mActiveRequest;
6040 NetworkRequest getActiveRequest() {
6041 return mActiveRequest;
6042 }
6043
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006044 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006045 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006046 @Nullable
6047 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006048
6049 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006050 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006051 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006052 final int mPid;
6053 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006054 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006055 @Nullable
6056 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006057
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006058 // Counter keeping track of this NRI.
6059 final PerUidCounter mPerUidCounter;
6060
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006061 // Effective UID of this request. This is different from mUid when a privileged process
6062 // files a request on behalf of another UID. This UID is used to determine blocked status,
6063 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6064 // maximum limit of registered callbacks per UID.
6065 final int mAsUid;
6066
paulhu48291862021-07-14 14:53:57 +08006067 // Preference order of this request.
6068 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006069
James Mattis3ce3d3c2021-02-09 18:18:28 -08006070 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6071 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6072 // maintained for keying off of. This is only a concern when the original nri
6073 // mNetworkRequests changes which happens currently for apps that register callbacks to
6074 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6075 // that match the per-app default nri that currently tracks the calling app's uid so that
6076 // callbacks are fired at the appropriate time. When the callbacks fire,
6077 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6078 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6079 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6080 @NonNull
6081 private final NetworkRequest mNetworkRequestForCallback;
6082 NetworkRequest getNetworkRequestForCallback() {
6083 return mNetworkRequestForCallback;
6084 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006085
James Mattisd31bdfa2020-12-23 16:37:26 -08006086 /**
6087 * Get the list of UIDs this nri applies to.
6088 */
6089 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006090 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006091 // networkCapabilities.getUids() returns a defensive copy.
6092 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006093 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6094 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006095 }
6096
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006097 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6098 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006099 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006100 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006101 }
6102
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006103 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006104 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006105 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006106 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006107 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006108 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006109 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006110 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006111 mBinder = null;
6112 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006113 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006114 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006115 mPerUidCounter = getRequestCounter(this);
6116 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006117 /**
6118 * Location sensitive data not included in pending intent. Only included in
6119 * {@link NetworkCallback}.
6120 */
6121 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006122 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006123 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006124 }
6125
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006126 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006127 @Nullable final IBinder binder,
6128 @NetworkCallback.Flag int callbackFlags,
6129 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006130 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6131 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006132 }
6133
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006134 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006135 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006136 @Nullable final IBinder binder,
6137 @NetworkCallback.Flag int callbackFlags,
6138 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006139 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006140 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006141 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006142 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006143 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006144 mBinder = binder;
6145 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006146 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006147 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006148 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006149 mPerUidCounter = getRequestCounter(this);
6150 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006151 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006152 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006153 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006154 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006155 }
6156
James Mattis3ce3d3c2021-02-09 18:18:28 -08006157 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6158 @NonNull final List<NetworkRequest> r) {
6159 super();
6160 ensureAllNetworkRequestsHaveType(r);
6161 mRequests = initializeRequests(r);
6162 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006163 final NetworkAgentInfo satisfier = nri.getSatisfier();
6164 if (null != satisfier) {
6165 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6166 // The active request is necessary to figure out what callbacks to send, in
6167 // particular then a network updates its capabilities.
6168 // As this code creates a new NRI with a new set of requests, figure out which of
6169 // the list of requests should be the active request. It is always the first
6170 // request of the list that can be satisfied by the satisfier since the order of
6171 // requests is a priority order.
6172 // Note even in the presence of a satisfier there may not be an active request,
6173 // when the satisfier is the no-service network.
6174 NetworkRequest activeRequest = null;
6175 for (final NetworkRequest candidate : r) {
6176 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6177 activeRequest = candidate;
6178 break;
6179 }
6180 }
6181 setSatisfier(satisfier, activeRequest);
6182 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006183 mMessenger = nri.mMessenger;
6184 mBinder = nri.mBinder;
6185 mPid = nri.mPid;
6186 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006187 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006188 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006189 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006190 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006191 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006192 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006193 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006194 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006195 }
6196
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006197 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006198 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006199 }
6200
paulhue9913722021-05-26 15:19:20 +08006201 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006202 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006203 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006204 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006205 }
6206
James Mattis2516da32021-01-31 17:06:19 -08006207 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6208 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6209 // false.
6210 boolean isBeingSatisfied() {
6211 return (null != mSatisfier && null != mActiveRequest);
6212 }
6213
James Mattis3d229892020-11-16 16:46:28 -08006214 boolean isMultilayerRequest() {
6215 return mRequests.size() > 1;
6216 }
6217
James Mattis45d81842021-01-10 14:24:24 -08006218 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6219 // Creating a defensive copy to prevent the sender from modifying the list being
6220 // reflected in the return value of this method.
6221 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006222 return Collections.unmodifiableList(tempRequests);
6223 }
6224
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006225 void decrementRequestCount() {
6226 mPerUidCounter.decrementCount(mUid);
6227 }
6228
James Mattisb1392002021-03-31 13:57:52 -07006229 void linkDeathRecipient() {
6230 if (null != mBinder) {
6231 try {
6232 mBinder.linkToDeath(this, 0);
6233 } catch (RemoteException e) {
6234 binderDied();
6235 }
6236 }
6237 }
6238
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006239 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006240 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006241 try {
6242 mBinder.unlinkToDeath(this, 0);
6243 } catch (NoSuchElementException e) {
6244 // Temporary workaround for b/194394697 pending analysis of additional logs
6245 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6246 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006247 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006248 }
6249
paulhu48291862021-07-14 14:53:57 +08006250 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6251 // Compare two preference orders.
6252 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006253 }
6254
paulhu48291862021-07-14 14:53:57 +08006255 int getPreferenceOrderForNetd() {
6256 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6257 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6258 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006259 }
paulhu48291862021-07-14 14:53:57 +08006260 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006261 }
6262
James Mattis4fce5d12020-11-12 15:53:42 -08006263 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006264 public void binderDied() {
6265 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006266 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006267 // As an immutable collection, mRequests cannot change by the time the
6268 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6269 // is acceptable. Use handleReleaseNetworkRequest and not directly
6270 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6271 // the app already unregistered the request.
6272 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6273 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006274 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006275
James Mattis4fce5d12020-11-12 15:53:42 -08006276 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006277 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006278 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6279 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006280 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006281 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006282 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006283 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006284 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006285 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006286 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006287 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006288 }
6289
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006290 // This checks that the passed capabilities either do not request a
6291 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006292 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006293 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006294 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006295 throw new SecurityException("Insufficient permissions to request a specific SSID");
6296 }
paulhu1a407652019-03-22 16:35:06 +08006297
6298 if (nc.hasSignalStrength()
6299 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6300 throw new SecurityException(
6301 "Insufficient permissions to request a specific signal strength");
6302 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006303 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006304
junyulai2217bec2021-04-14 23:33:31 +08006305 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006306 enforceNetworkFactoryPermission();
6307 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006308 }
6309
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006310 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006311 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006312 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006313 // mNetworkRequests may contain the same value multiple times in case of
6314 // multilayer requests. It won't matter in this case because the thresholds
6315 // will then be the same and be deduplicated as they enter the `thresholds` set.
6316 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006317 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6318 for (final NetworkRequest req : nri.mRequests) {
6319 if (req.networkCapabilities.hasSignalStrength()
6320 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6321 thresholds.add(req.networkCapabilities.getSignalStrength());
6322 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006323 }
6324 }
6325 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006326 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006327 }
6328
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006329 private void updateSignalStrengthThresholds(
6330 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006331 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006332
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006333 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006334 String detail;
6335 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6336 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6337 } else {
6338 detail = reason;
6339 }
6340 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006341 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006342 }
6343
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006344 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006345 }
6346
Chalard Jeandd421992021-12-16 23:16:02 +09006347 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006348 if (nc == null) {
6349 return;
6350 }
6351 NetworkSpecifier ns = nc.getNetworkSpecifier();
6352 if (ns == null) {
6353 return;
6354 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006355 if (ns instanceof MatchAllNetworkSpecifier) {
6356 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6357 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006358 }
6359
Chalard Jeandd421992021-12-16 23:16:02 +09006360 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006361 ensureValidNetworkSpecifier(nc);
6362 if (nc.isPrivateDnsBroken()) {
6363 throw new IllegalArgumentException("Can't request broken private DNS");
6364 }
Chalard Jean9a30acf2021-12-13 22:53:51 +09006365 if (nc.hasAccessUids()) {
6366 throw new IllegalArgumentException("Can't request access UIDs");
6367 }
lucasline117e2e2019-10-22 18:27:33 +08006368 }
6369
Chalard Jeandd421992021-12-16 23:16:02 +09006370 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6371 ensureListenableCapabilities(nc);
6372 final String badCapability = nc.describeFirstNonRequestableCapability();
6373 if (badCapability != null) {
6374 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6375 }
6376 }
6377
Chiachang Wang3bc52762021-11-25 14:17:57 +08006378 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6379 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006380 private boolean isTargetSdkAtleast(int version, int callingUid,
6381 @NonNull String callingPackageName) {
6382 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006383 final PackageManager pm =
6384 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006385 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006386 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006387 if (callingVersion < version) return false;
6388 } catch (PackageManager.NameNotFoundException e) { }
6389 return true;
6390 }
6391
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006392 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006393 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006394 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006395 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006396 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006397 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006398 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6399 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006400 throw new SecurityException("Insufficient permissions to specify legacy type");
6401 }
markchienfac84a22020-03-18 21:16:15 +08006402 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006403 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006404 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006405 // Privileged callers can track the default network of another UID by passing in a UID.
6406 if (asUid != Process.INVALID_UID) {
6407 enforceSettingsPermission();
6408 } else {
6409 asUid = callingUid;
6410 }
junyulaiad010792021-01-11 16:53:38 +08006411 final NetworkRequest.Type reqType;
6412 try {
6413 reqType = NetworkRequest.Type.values()[reqTypeInt];
6414 } catch (ArrayIndexOutOfBoundsException e) {
6415 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6416 }
6417 switch (reqType) {
6418 case TRACK_DEFAULT:
6419 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006420 // is unused and will be replaced by ones appropriate for the UID (usually, the
6421 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006422 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006423 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006424 enforceAccessPermission();
6425 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006426 case TRACK_SYSTEM_DEFAULT:
6427 enforceSettingsPermission();
6428 networkCapabilities = new NetworkCapabilities(defaultNc);
6429 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006430 case BACKGROUND_REQUEST:
6431 enforceNetworkStackOrSettingsPermission();
6432 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006433 case REQUEST:
6434 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6435 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6436 callingAttributionTag);
6437 // TODO: this is incorrect. We mark the request as metered or not depending on
6438 // the state of the app when the request is filed, but we never change the
6439 // request if the app changes network state. http://b/29964605
6440 enforceMeteredApnPolicy(networkCapabilities);
6441 break;
junyulai1b1c8742021-03-12 20:05:08 +08006442 case LISTEN_FOR_BEST:
6443 enforceAccessPermission();
6444 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6445 break;
junyulaiad010792021-01-11 16:53:38 +08006446 default:
6447 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006448 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006449 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006450 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006451 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006452
junyulai1b1c8742021-03-12 20:05:08 +08006453 // Enforce FOREGROUND if the caller does not have permission to use background network.
6454 if (reqType == LISTEN_FOR_BEST) {
6455 restrictBackgroundRequestForCaller(networkCapabilities);
6456 }
6457
6458 // Set the UID range for this request to the single UID of the requester, unless the
6459 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006460 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6461 // are no visible methods to set the UIDs, an app could use reflection to try and get
6462 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006463 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006464 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6465 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006466
Etan Cohen85000162017-02-05 10:42:27 -08006467 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006468 throw new IllegalArgumentException("Bad timeout specified");
6469 }
Etan Cohen9786d922015-11-18 10:56:15 -08006470
James Mattis3ce3d3c2021-02-09 18:18:28 -08006471 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006472 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006473 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006474 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006475 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006476 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006477
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006478 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6479 // copied from the default request above. (This is necessary to ensure, for example, that
6480 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6481 // changes don't alter request matching.
6482 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6483 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006484 throw new IllegalStateException(
6485 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006486 + networkCapabilities + " vs. " + defaultNc);
6487 }
6488
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006489 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006490 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006491 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006492 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006493 }
6494 return networkRequest;
6495 }
6496
James Mattis3ce3d3c2021-02-09 18:18:28 -08006497 /**
6498 * Return the nri to be used when registering a network request. Specifically, this is used with
6499 * requests registered to track the default request. If there is currently a per-app default
6500 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6501 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006502 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6503 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006504 * @param nr the network request for the nri.
6505 * @param msgr the messenger for the nri.
6506 * @param binder the binder for the nri.
6507 * @param callingAttributionTag the calling attribution tag for the nri.
6508 * @return the nri to register.
6509 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006510 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006511 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006512 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006513 @Nullable String callingAttributionTag) {
6514 final List<NetworkRequest> requests;
6515 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6516 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006517 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006518 } else {
6519 requests = Collections.singletonList(nr);
6520 }
Roshan Pius951c0032020-12-22 15:10:42 -08006521 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006522 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006523 }
6524
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006525 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
6526 String callingPackageName, String callingAttributionTag) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006527 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006528 if (!networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
6529 enforceConnectivityRestrictedNetworksPermission();
6530 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006531 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006532 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006533 }
6534 }
6535
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006536 private boolean checkConnectivityRestrictedNetworksPermission(int callerPid, int callerUid) {
6537 if (checkAnyPermissionOf(callerPid, callerUid,
6538 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)
6539 || checkAnyPermissionOf(callerPid, callerUid,
6540 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
6541 return true;
6542 }
6543 return false;
6544 }
6545
fenglu3f357402015-03-20 11:29:56 -07006546 @Override
fenglub00f4882015-04-21 17:12:05 -07006547 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006548 enforceAccessPermission();
6549 NetworkAgentInfo nai = null;
6550 if (network == null) {
6551 return false;
6552 }
6553 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006554 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006555 }
6556 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006557 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006558 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006559 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006560 Integer uidReqs = mBandwidthRequests.get(uid);
6561 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006562 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006563 }
6564 mBandwidthRequests.put(uid, ++uidReqs);
6565 }
fenglu3f357402015-03-20 11:29:56 -07006566 return true;
6567 }
6568 return false;
6569 }
6570
Felipe Leme0a5ae422016-06-20 16:36:29 -07006571 private boolean isSystem(int uid) {
6572 return uid < Process.FIRST_APPLICATION_UID;
6573 }
fenglu3f357402015-03-20 11:29:56 -07006574
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006575 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006576 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006577 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006578 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006579 return;
6580 }
Hugo Benichi39621362017-02-11 17:04:43 +09006581 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6582 // Policy already enforced.
6583 return;
6584 }
paulhuaf50d7d2020-12-24 19:47:34 +08006585 final long ident = Binder.clearCallingIdentity();
6586 try {
6587 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6588 // If UID is restricted, don't allow them to bring up metered APNs.
6589 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6590 }
6591 } finally {
6592 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006593 }
6594 }
6595
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006596 @Override
6597 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006598 PendingIntent operation, @NonNull String callingPackageName,
6599 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006600 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006601 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006602 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006603 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6604 callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006605 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006606 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006607 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006608 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006609 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6610 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09006611
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006612 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006613 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006614 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6615 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006616 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006617 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6618 nri));
6619 return networkRequest;
6620 }
6621
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006622 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6623 mHandler.sendMessageDelayed(
6624 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006625 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006626 }
6627
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006628 @Override
6629 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006630 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006631 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006632 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006633 }
6634
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006635 // In order to implement the compatibility measure for pre-M apps that call
6636 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6637 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6638 // This ensures it has permission to do so.
6639 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6640 if (nc == null) {
6641 return false;
6642 }
6643 int[] transportTypes = nc.getTransportTypes();
6644 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6645 return false;
6646 }
6647 try {
6648 mContext.enforceCallingOrSelfPermission(
6649 android.Manifest.permission.ACCESS_WIFI_STATE,
6650 "ConnectivityService");
6651 } catch (SecurityException e) {
6652 return false;
6653 }
6654 return true;
6655 }
6656
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006657 @Override
6658 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006659 Messenger messenger, IBinder binder,
6660 @NetworkCallback.Flag int callbackFlags,
6661 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006662 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006663 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6664 enforceAccessPermission();
6665 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006666
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006667 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006668 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006669 Binder.getCallingPid(), callingUid, callingPackageName);
6670 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006671 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6672 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6673 // onLost and onAvailable callbacks when networks move in and out of the background.
6674 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6675 // can't request networks.
6676 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09006677 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006678
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006679 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006680 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006681 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006682 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006683 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006684 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006685
6686 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6687 return networkRequest;
6688 }
6689
6690 @Override
6691 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006692 PendingIntent operation, @NonNull String callingPackageName,
6693 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006694 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006695 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006696 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6697 enforceAccessPermission();
6698 }
Chalard Jeandd421992021-12-16 23:16:02 +09006699 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006700 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006701 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006702 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006703 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006704
6705 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006706 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006707 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6708 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006709 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006710
WeiZhang1cc3f172021-06-03 19:02:04 -05006711 mHandler.sendMessage(mHandler.obtainMessage(
6712 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006713 }
6714
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006715 /** Returns the next Network provider ID. */
6716 public final int nextNetworkProviderId() {
6717 return mNextNetworkProviderId.getAndIncrement();
6718 }
6719
Erik Kline0c04b742016-07-07 16:50:58 +09006720 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006721 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006722 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006723 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006724 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006725 }
6726
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006727 private void releaseNetworkRequestAndCallOnUnavailable(NetworkRequest networkRequest) {
6728 ensureNetworkRequestHasType(networkRequest);
6729 mHandler.sendMessage(mHandler.obtainMessage(
6730 EVENT_RELEASE_NETWORK_REQUEST_AND_CALL_UNAVAILABLE, mDeps.getCallingUid(), 0,
6731 networkRequest));
6732 }
6733
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006734 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6735 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006736 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6737 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6738 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006739 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006740 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006741 return;
6742 }
6743
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006744 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6745 mNetworkProviderInfos.put(npi.messenger, npi);
6746 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006747 }
6748
6749 @Override
6750 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006751 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006752 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006753 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006754 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006755 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6756 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006757 }
6758
6759 @Override
6760 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006761 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006762 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006763 }
6764
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006765 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09006766 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006767 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6768 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09006769 Objects.requireNonNull(score);
6770 Objects.requireNonNull(caps);
6771 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006772 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006773 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09006774 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
6775 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006776 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6777 }
6778
Chalard Jeanbb902a52021-08-18 01:35:19 +09006779 private void updateOfferScore(final NetworkOffer offer) {
6780 final boolean yieldToBadWiFi =
6781 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
6782 final NetworkOffer newOffer = new NetworkOffer(
6783 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
6784 offer.caps, offer.callback, offer.providerId);
6785 if (offer.equals(newOffer)) return;
6786 handleRegisterNetworkOffer(newOffer);
6787 }
6788
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006789 @Override
6790 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6791 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6792 }
6793
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006794 private void handleUnregisterNetworkProvider(Messenger messenger) {
6795 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6796 if (npi == null) {
6797 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006798 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006799 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006800 // Unregister all the offers from this provider
6801 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6802 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09006803 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006804 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6805 toRemove.add(noi);
6806 }
6807 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09006808 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006809 handleUnregisterNetworkOffer(noi);
6810 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006811 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006812 }
6813
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006814 @Override
James Mattisf7027322020-12-13 16:28:14 -08006815 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006816 if (request.hasTransport(TRANSPORT_TEST)) {
6817 enforceNetworkFactoryOrTestNetworksPermission();
6818 } else {
6819 enforceNetworkFactoryPermission();
6820 }
James Mattisf7027322020-12-13 16:28:14 -08006821 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6822 if (nri != null) {
6823 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6824 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6825 mHandler.post(() -> handleReleaseNetworkRequest(
6826 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6827 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006828 }
6829
Paul Jensen1f567382015-02-13 14:18:39 -05006830 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6831 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006832 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05006833 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006834 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05006835 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006836 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006837
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09006838 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05006839 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006840 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006841
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006842 // UID ranges for users that are currently blocked by VPNs.
6843 // This array is accessed and iterated on multiple threads without holding locks, so its
6844 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6845 // (on the handler thread).
6846 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6847
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006848 // Must only be accessed on the handler thread
6849 @NonNull
6850 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6851
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006852 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006853 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006854
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006855 // Current OEM network preferences. This object must only be written to on the handler thread.
6856 // Since it is immutable and always non-null, other threads may read it if they only care
6857 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08006858 @NonNull
6859 private OemNetworkPreferences mOemNetworkPreferences =
6860 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006861 // Current per-profile network preferences. This object follows the same threading rules as
6862 // the OEM network preferences above.
6863 @NonNull
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006864 private ProfileNetworkPreferenceList mProfileNetworkPreferences =
6865 new ProfileNetworkPreferenceList();
James Mattis45d81842021-01-10 14:24:24 -08006866
paulhu51f77dc2021-06-07 02:34:20 +00006867 // A set of UIDs that should use mobile data preferentially if available. This object follows
6868 // the same threading rules as the OEM network preferences above.
6869 @NonNull
6870 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
6871
James Mattiscb1e0362021-04-06 17:07:42 -07006872 // OemNetworkPreferences activity String log entries.
6873 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6874 @NonNull
6875 private final LocalLog mOemNetworkPreferencesLogs =
6876 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6877
James Mattis02220e22021-03-13 19:27:21 -08006878 /**
6879 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6880 * @param packageName the package name to check existence of a mapping for.
6881 * @return true if a mapping exists, false otherwise
6882 */
6883 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6884 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6885 }
6886
James Mattise3ef1912020-12-20 11:09:58 -08006887 // The always-on request for an Internet-capable network that apps without a specific default
6888 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08006889 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09006890 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006891 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08006892 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08006893 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08006894 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006895 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006896
James Mattisd31bdfa2020-12-23 16:37:26 -08006897 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6898 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6899 }
6900
6901 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08006902 * Return the default network request currently tracking the given uid.
6903 * @param uid the uid to check.
6904 * @return the NetworkRequestInfo tracking the given uid.
6905 */
6906 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08006907 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08006908 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006909 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006910 // Checking the first request is sufficient as only multilayer requests will have more
6911 // than one request and for multilayer, all requests will track the same uids.
6912 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08006913 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08006914 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08006915 highestPriorityNri = nri;
6916 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006917 }
6918 }
paulhuaa0743d2021-05-26 21:56:03 +08006919 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006920 }
6921
6922 /**
6923 * Get a copy of the network requests of the default request that is currently tracking the
6924 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006925 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6926 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006927 * @param requestorUid the uid to check the default for.
6928 * @param requestorPackageName the requestor's package name.
6929 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6930 */
6931 @NonNull
6932 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006933 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006934 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006935 getDefaultRequestTrackingUid(asUid).mRequests,
6936 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006937 }
6938
6939 /**
6940 * Copy the given nri's NetworkRequest collection.
6941 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006942 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6943 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006944 * @param requestorUid the uid to set on the copied collection.
6945 * @param requestorPackageName the package name to set on the copied collection.
6946 * @return the copied NetworkRequest collection.
6947 */
6948 @NonNull
6949 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006950 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6951 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006952 final List<NetworkRequest> requests = new ArrayList<>();
6953 for (final NetworkRequest nr : requestsToCopy) {
6954 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006955 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08006956 nr.legacyType, nextNetworkRequestId(), nr.type));
6957 }
6958 return requests;
6959 }
6960
6961 @NonNull
6962 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006963 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6964 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09006965 // These capabilities are for a TRACK_DEFAULT callback, so:
6966 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6967 // mDefaultRequest and a per-UID default request.
6968 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006969 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09006970 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006971 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6972 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006973 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006974 restrictRequestUidsForCallerAndSetRequestorInfo(
6975 netCap, requestorUid, requestorPackageName);
6976 return netCap;
6977 }
6978
6979 /**
6980 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6981 * @param nr the network request to check for equality against.
6982 * @return the nri if one exists, null otherwise.
6983 */
6984 @Nullable
6985 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6986 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6987 if (nri.getNetworkRequestForCallback().equals(nr)) {
6988 return nri;
6989 }
6990 }
6991 return null;
6992 }
6993
6994 /**
6995 * Check if an nri is currently being managed by per-app default networking.
6996 * @param nri the nri to check.
6997 * @return true if this nri is currently being managed by per-app default networking.
6998 */
6999 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7000 // nri.mRequests.get(0) is only different from the original request filed in
7001 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7002 // functionality therefore if these two don't match, it means this particular nri is
7003 // currently being managed by a per-app default.
7004 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7005 }
7006
7007 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007008 * Determine if an nri is a managed default request that disallows default networking.
7009 * @param nri the request to evaluate
7010 * @return true if device-default networking is disallowed
7011 */
7012 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7013 // Check if this nri is a managed default that supports the default network at its
7014 // lowest priority request.
7015 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7016 final NetworkCapabilities lowestPriorityNetCap =
7017 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7018 return isPerAppDefaultRequest(nri)
7019 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7020 lowestPriorityNetCap));
7021 }
7022
Erik Kline05f2b402015-04-30 12:58:40 +09007023 // Request used to optionally keep mobile data active even when higher
7024 // priority networks like Wi-Fi are active.
7025 private final NetworkRequest mDefaultMobileDataRequest;
7026
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007027 // Request used to optionally keep wifi data active even when higher
7028 // priority networks like ethernet are active.
7029 private final NetworkRequest mDefaultWifiRequest;
7030
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007031 // Request used to optionally keep vehicle internal network always active
7032 private final NetworkRequest mDefaultVehicleRequest;
7033
James Mattisd31bdfa2020-12-23 16:37:26 -08007034 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7035 // network with no service. This NAI should never be matched against, nor should any public API
7036 // ever return the associated network. For this reason, this NAI is not in the list of available
7037 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7038 // default requests that don't support using the device default network which will ultimately
7039 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7040 @VisibleForTesting
7041 final NetworkAgentInfo mNoServiceNetwork;
7042
Chalard Jean5b409c72021-02-04 13:12:59 +09007043 // The NetworkAgentInfo currently satisfying the default request, if any.
7044 private NetworkAgentInfo getDefaultNetwork() {
7045 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007046 }
7047
James Mattis2516da32021-01-31 17:06:19 -08007048 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007049 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007050 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7051 // Currently, all network requests will have the same uids therefore checking the first
7052 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007053 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007054 if (null == uids) {
7055 continue;
7056 }
7057 for (final UidRange range : uids) {
7058 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007059 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007060 highestPriorityNri = nri;
7061 }
James Mattis2516da32021-01-31 17:06:19 -08007062 }
7063 }
7064 }
paulhuaa0743d2021-05-26 21:56:03 +08007065 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007066 }
7067
Varun Ananddf569952019-02-06 10:13:38 -08007068 @Nullable
7069 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7070 return nai != null ? nai.network : null;
7071 }
7072
7073 private void ensureRunningOnConnectivityServiceThread() {
7074 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7075 throw new IllegalStateException(
7076 "Not running on ConnectivityService thread: "
7077 + Thread.currentThread().getName());
7078 }
7079 }
7080
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007081 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007082 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7083 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007084 }
7085
Chalard Jean29d06db2018-05-02 21:14:54 +09007086 /**
7087 * Register a new agent with ConnectivityService to handle a network.
7088 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007089 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007090 * @param networkInfo the initial info associated with this network. It can be updated later :
7091 * see {@link #updateNetworkInfo}.
7092 * @param linkProperties the initial link properties of this network. They can be updated
7093 * later : see {@link #updateLinkProperties}.
7094 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007095 * later : see {@link #updateCapabilities}.
Chalard Jean28018572020-12-21 18:36:52 +09007096 * @param initialScore the initial score of the network. See
Chalard Jean29d06db2018-05-02 21:14:54 +09007097 * {@link NetworkAgentInfo#getCurrentScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007098 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007099 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007100 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007101 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007102 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007103 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007104 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7105 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007106 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7107 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7108 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007109 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007110 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007111 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
7112 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007113 } else {
7114 enforceNetworkFactoryPermission();
7115 }
7116
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007117 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007118 final long token = Binder.clearCallingIdentity();
7119 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007120 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007121 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007122 } finally {
7123 Binder.restoreCallingIdentity(token);
7124 }
7125 }
7126
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007127 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007128 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007129 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7130 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007131
Chalard Jean366c5252022-01-25 18:27:53 +09007132 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
7133 // the capabilities' access UID comply with security limitations. They will be sanitized
7134 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7135 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007136 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jean366c5252022-01-25 18:27:53 +09007137 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo),
7138 linkProperties, networkCapabilities,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007139 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007140 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7141 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007142
Chalard Jeanf2da1772018-04-26 16:16:10 +09007143 final String extraInfo = networkInfo.getExtraInfo();
7144 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007145 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007146 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007147 mDeps.getNetworkStack().makeNetworkMonitor(
7148 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007149 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7150 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007151 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007152 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007153 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007154 }
7155
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007156 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007157 if (VDBG) log("Network Monitor created for " + nai);
7158 // nai.nc and nai.lp are the same object that was passed by the network agent if the agent
7159 // lives in the same process as this code (e.g. wifi), so make sure this code doesn't
7160 // mutate their object
7161 final NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities);
7162 final LinkProperties lp = new LinkProperties(nai.linkProperties);
7163 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
7164 processCapabilitiesFromAgent(nai, nc);
7165 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
7166 processLinkPropertiesFromAgent(nai, lp);
7167 nai.linkProperties = lp;
7168
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007169 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007170
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007171 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007172 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007173 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007174 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007175
7176 try {
7177 networkMonitor.start();
7178 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007179 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007180 }
Chalard Jean366c5252022-01-25 18:27:53 +09007181
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007182 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007183 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007184 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007185 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007186 }
7187
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007188 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7189 @NonNull public final NetworkOffer offer;
7190
7191 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7192 this.offer = offer;
7193 }
7194
7195 @Override
7196 public void binderDied() {
7197 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7198 }
7199 }
7200
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007201 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7202 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7203 if (npi.providerId == providerId) return true;
7204 }
7205 return false;
7206 }
7207
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007208 /**
7209 * Register or update a network offer.
7210 * @param newOffer The new offer. If the callback member is the same as an existing
7211 * offer, it is an update of that offer.
7212 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007213 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007214 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7215 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007216 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007217 // This may actually happen if a provider updates its score or registers and then
7218 // immediately unregisters. The offer would still be in the handler queue, but the
7219 // provider would have been removed.
7220 if (DBG) log("Received offer from an unregistered provider");
7221 return;
7222 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007223 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7224 if (null != existingOffer) {
7225 handleUnregisterNetworkOffer(existingOffer);
7226 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007227 if (DBG) {
7228 // handleUnregisterNetworkOffer has already logged the old offer
7229 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7230 }
7231 } else {
7232 if (DBG) {
7233 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7234 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007235 }
7236 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7237 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007238 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007239 } catch (RemoteException e) {
7240 noi.binderDied();
7241 return;
7242 }
7243 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007244 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007245 }
7246
7247 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7248 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007249 if (DBG) {
7250 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7251 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007252
7253 // If the provider removes the offer and dies immediately afterwards this
7254 // function may be called twice in a row, but the array will no longer contain
7255 // the offer.
7256 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007257 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007258 }
7259
7260 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7261 @NonNull final INetworkOfferCallback callback) {
7262 ensureRunningOnConnectivityServiceThread();
7263 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007264 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007265 }
7266 return null;
7267 }
7268
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007269 /**
7270 * Called when receiving LinkProperties directly from a NetworkAgent.
7271 * Stores into |nai| any data coming from the agent that might also be written to the network's
7272 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7273 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007274 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007275 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007276 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7277 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007278 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007279 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007280 }
7281
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007282 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007283 @NonNull LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007284 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007285
Lorenzo Colittid523d142020-04-01 20:16:30 +09007286 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7287 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7288 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007289 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007290
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007291 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007292
7293 // update filtering rules, need to happen after the interface update so netd knows about the
7294 // new interface (the interface name -> index map becomes initialized)
7295 updateVpnFiltering(newLp, oldLp, networkAgent);
7296
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007297 updateMtu(newLp, oldLp);
7298 // TODO - figure out what to do for clat
7299// for (LinkProperties lp : newLp.getStackedLinks()) {
7300// updateMtu(lp, null);
7301// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007302 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007303 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7304 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007305
Erik Klineb9888902016-04-05 13:30:49 +09007306 updateRoutes(newLp, oldLp, netId);
7307 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007308 // Make sure LinkProperties represents the latest private DNS status.
7309 // This does not need to be done before updateDnses because the
7310 // LinkProperties are not the source of the private DNS configuration.
7311 // updateDnses will fetch the private DNS configuration from DnsManager.
7312 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007313
Chalard Jean5b409c72021-02-04 13:12:59 +09007314 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007315 handleApplyDefaultProxy(newLp.getHttpProxy());
7316 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007317 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007318 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007319
7320 updateWakeOnLan(newLp);
7321
Hai Shalome58bdc62021-01-11 18:45:34 -08007322 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7323 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7324 // does, it needs to be merged here.
7325 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7326 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007327
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007328 // TODO - move this check to cover the whole function
7329 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007330 synchronized (networkAgent) {
7331 networkAgent.linkProperties = newLp;
7332 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007333 // Start or stop DNS64 detection and 464xlat according to network state.
7334 networkAgent.clatd.update();
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08007335 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007336 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7337 new LinkProperties(newLp, true /* parcelSensitiveFields */));
lucaslin74fa3972018-11-28 12:51:55 +08007338 if (networkAgent.everConnected) {
7339 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
7340 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007341 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007342
7343 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007344 }
7345
Hai Shalome58bdc62021-01-11 18:45:34 -08007346 /**
7347 * @param naData captive portal data from NetworkAgent
7348 * @param apiData captive portal data from capport API
7349 */
7350 @Nullable
7351 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7352 CaptivePortalData apiData) {
7353 if (naData == null || apiData == null) {
7354 return naData == null ? apiData : naData;
7355 }
7356 final CaptivePortalData.Builder captivePortalBuilder =
7357 new CaptivePortalData.Builder(naData);
7358
7359 if (apiData.isCaptive()) {
7360 captivePortalBuilder.setCaptive(true);
7361 }
7362 if (apiData.isSessionExtendable()) {
7363 captivePortalBuilder.setSessionExtendable(true);
7364 }
7365 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7366 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7367 // otherwise data would be inconsistent. Prefer the capport API info if present,
7368 // as it can generally be refreshed more often.
7369 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7370 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7371 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7372 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7373 // No source has time / bytes remaining information: surface the newest refresh time
7374 // for other fields
7375 captivePortalBuilder.setRefreshTime(
7376 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7377 }
7378
Hai Shalom7c6ab402021-02-04 19:34:06 -08007379 // Prioritize the user portal URL from the network agent if the source is authenticated.
7380 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7381 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7382 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7383 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007384 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007385 // Prioritize the venue information URL from the network agent if the source is
7386 // authenticated.
7387 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7388 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7389 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7390 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007391 }
7392 return captivePortalBuilder.build();
7393 }
7394
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007395 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007396 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007397 // marks on unsupported interfaces is harmless.
7398 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7399 return;
7400 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007401
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007402 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7403 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7404
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007405 // Mask/mark of zero will not detect anything interesting.
7406 // Don't install rules unless both values are nonzero.
7407 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007408 return;
7409 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007410
7411 final String prefix = "iface:" + iface;
7412 try {
7413 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007414 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007415 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007416 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007417 }
7418 } catch (Exception e) {
7419 loge("Exception modifying wakeup packet monitoring: " + e);
7420 }
7421
Joel Scherpelza235a812017-05-22 13:47:41 +09007422 }
7423
Chalard Jean9589e722019-11-19 19:03:53 +09007424 private void updateInterfaces(final @Nullable LinkProperties newLp,
7425 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007426 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007427 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fa7d9e2017-08-22 16:35:52 +01007428 oldLp != null ? oldLp.getAllInterfaceNames() : null,
7429 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jean9589e722019-11-19 19:03:53 +09007430 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007431 for (final String iface : interfaceDiff.added) {
7432 try {
7433 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007434 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007435 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007436 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7437 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007438 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007439 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007440 }
Paul Jensenbff73492014-04-28 10:33:11 -04007441 }
7442 }
Chalard Jean9589e722019-11-19 19:03:53 +09007443 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007444 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007445 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007446 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007447 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007448 } catch (Exception e) {
7449 loge("Exception removing interface: " + e);
7450 }
7451 }
7452 }
7453
Tyler Weare4314862019-12-05 14:55:30 -08007454 // TODO: move to frameworks/libs/net.
7455 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7456 final String nextHop;
7457
7458 switch (route.getType()) {
7459 case RouteInfo.RTN_UNICAST:
7460 if (route.hasGateway()) {
7461 nextHop = route.getGateway().getHostAddress();
7462 } else {
7463 nextHop = INetd.NEXTHOP_NONE;
7464 }
7465 break;
7466 case RouteInfo.RTN_UNREACHABLE:
7467 nextHop = INetd.NEXTHOP_UNREACHABLE;
7468 break;
7469 case RouteInfo.RTN_THROW:
7470 nextHop = INetd.NEXTHOP_THROW;
7471 break;
7472 default:
7473 nextHop = INetd.NEXTHOP_NONE;
7474 break;
7475 }
7476
7477 final RouteInfoParcel rip = new RouteInfoParcel();
7478 rip.ifName = route.getInterface();
7479 rip.destination = route.getDestination().toString();
7480 rip.nextHop = nextHop;
7481 rip.mtu = route.getMtu();
7482
7483 return rip;
7484 }
7485
Paul Jensene0fd4a82014-08-06 15:51:33 -04007486 /**
7487 * Have netd update routes from oldLp to newLp.
7488 * @return true if routes changed between oldLp and newLp
7489 */
7490 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007491 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007492 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7493 new CompareOrUpdateResult<>(
7494 oldLp != null ? oldLp.getAllRoutes() : null,
7495 newLp != null ? newLp.getAllRoutes() : null,
7496 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007497
7498 // add routes before removing old in case it helps with continuous connectivity
7499
Chalard Jean9dd11612018-06-04 16:52:49 +09007500 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007501 for (RouteInfo route : routeDiff.added) {
7502 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007503 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007504 try {
Tyler Weare4314862019-12-05 14:55:30 -08007505 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007506 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007507 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007508 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007509 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007510 }
7511 }
7512 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007513 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007514 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007515 try {
Tyler Weare4314862019-12-05 14:55:30 -08007516 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007517 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007518 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007519 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007520 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007521 }
7522 }
7523
7524 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007525 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007526 try {
Tyler Weare4314862019-12-05 14:55:30 -08007527 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007528 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007529 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007530 }
7531 }
Tyler Weare4314862019-12-05 14:55:30 -08007532
7533 for (RouteInfo route : routeDiff.updated) {
7534 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7535 try {
7536 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7537 } catch (Exception e) {
7538 loge("Exception in networkUpdateRouteParcel: " + e);
7539 }
7540 }
7541 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7542 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007543 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007544
Erik Klineb9888902016-04-05 13:30:49 +09007545 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7546 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7547 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007548 }
Erik Klineb9888902016-04-05 13:30:49 +09007549
Erik Kline31b4a9e2018-01-11 21:07:29 +09007550 if (DBG) {
7551 final Collection<InetAddress> dnses = newLp.getDnsServers();
7552 log("Setting DNS servers for network " + netId + " to " + dnses);
7553 }
Erik Klineb9888902016-04-05 13:30:49 +09007554 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007555 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007556 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007557 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007558 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007559 }
Erik Kline54e35c02017-04-07 15:29:29 +09007560 }
7561
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007562 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7563 NetworkAgentInfo nai) {
7564 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
7565 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
7566 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
7567 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
7568
7569 if (!wasFiltering && !needsFiltering) {
7570 // Nothing to do.
7571 return;
7572 }
7573
7574 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7575 // Nothing changed.
7576 return;
7577 }
7578
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007579 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Qingxi Libb8da982020-01-17 17:54:27 -08007580 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007581 // TODO: this create a window of opportunity for apps to receive traffic between the time
7582 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007583 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007584 // old rules are being removed.
7585 if (wasFiltering) {
7586 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7587 }
7588 if (needsFiltering) {
7589 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7590 }
7591 }
7592
Valentin Iftime9fa35092019-09-24 13:32:13 +02007593 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007594 if (mWolSupportedInterfaces == null) {
7595 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007596 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007597 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007598 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7599 }
7600
Luke Huangb913c812018-08-24 20:33:16 +08007601 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007602 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007603 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007604 }
7605 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007606 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007607 }
Luke Huangb913c812018-08-24 20:33:16 +08007608 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007609 }
7610
Chalard Jean62edfd82019-12-02 18:39:29 +09007611 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7612 @NonNull final NetworkCapabilities newNc) {
7613 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7614 final int newPermission = getNetworkPermission(newNc);
7615 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7616 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007617 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007618 } catch (RemoteException | ServiceSpecificException e) {
7619 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007620 }
7621 }
7622 }
7623
Paul Jensen53f08952015-06-16 14:27:36 -04007624 /**
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007625 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7626 * Stores into |nai| any data coming from the agent that might also be written to the network's
7627 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7628 * agent is not lost when updateCapabilities is called.
7629 */
7630 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
Chalard Jean15228572022-01-28 19:29:12 +09007631 if (nc.hasConnectivityManagedCapability()) {
7632 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
7633 }
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007634 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7635 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7636 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7637 // the owner UID here and behave as if the agent had never tried to change it.
Lorenzo Colitti93401342020-12-09 18:30:52 +09007638 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7639 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7640 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7641 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7642 }
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007643 nai.declaredCapabilities = new NetworkCapabilities(nc);
Chalard Jeanac9ace02022-01-26 16:54:05 +09007644 NetworkAgentInfo.restrictCapabilitiesFromNetworkAgent(nc, nai.creatorUid,
7645 mCarrierPrivilegeAuthenticator);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007646 }
7647
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007648 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007649 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007650 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007651 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007652 underlyingNetworks = underlyingNetworksOrDefault(
7653 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007654 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007655 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7656 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007657 // metered if any underlying is metered, or originally declared metered by the agent.
7658 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007659 boolean roaming = false; // roaming if any underlying is roaming
7660 boolean congested = false; // congested if any underlying is congested
7661 boolean suspended = true; // suspended if all underlying are suspended
7662
7663 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08007664 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007665 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08007666 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007667 for (Network underlyingNetwork : underlyingNetworks) {
7668 final NetworkAgentInfo underlying =
7669 getNetworkAgentInfoForNetwork(underlyingNetwork);
7670 if (underlying == null) continue;
7671
7672 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7673 hadUnderlyingNetworks = true;
7674 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007675 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007676 }
7677
7678 // Merge capabilities of this underlying network. For bandwidth, assume the
7679 // worst case.
7680 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7681 underlyingCaps.getLinkDownstreamBandwidthKbps());
7682 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7683 underlyingCaps.getLinkUpstreamBandwidthKbps());
7684 // If this underlying network is metered, the VPN is metered (it may cost money
7685 // to send packets on this network).
7686 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7687 // If this underlying network is roaming, the VPN is roaming (the billing structure
7688 // is different than the usual, local one).
7689 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7690 // If this underlying network is congested, the VPN is congested (the current
7691 // condition of the network affects the performance of this network).
7692 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7693 // If this network is not suspended, the VPN is not suspended (the VPN
7694 // is able to transfer some data).
7695 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08007696 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007697 }
7698 }
7699 if (!hadUnderlyingNetworks) {
7700 // No idea what the underlying networks are; assume reasonable defaults
7701 metered = true;
7702 roaming = false;
7703 congested = false;
7704 suspended = false;
7705 }
7706
lifrade6c2a2021-03-04 14:08:08 +08007707 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007708 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7709 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7710 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7711 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7712 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7713 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08007714 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007715 }
7716
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007717 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007718 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7719 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7720 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007721 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007722 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007723 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007724 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007725 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7726 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007727 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007728 // avoid connect/teardown loops.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007729 if (nai.everConnected &&
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007730 !nai.isVPN() &&
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007731 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7732 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007733 // does not cause any request (that is not a listen) currently matching that agent to
7734 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007735 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007736 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007737 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007738 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007739 }
7740
Paul Jensen53f08952015-06-16 14:27:36 -04007741 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007742 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensende49eb12015-06-25 15:30:08 -04007743 if (nai.lastValidated) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007744 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007745 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007746 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007747 }
Paul Jensende49eb12015-06-25 15:30:08 -04007748 if (nai.lastCaptivePortalDetected) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007749 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007750 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007751 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007752 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007753 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007754 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007755 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007756 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007757 }
lucaslin2240ef62019-03-12 13:08:03 +08007758 if (nai.partialConnectivity) {
7759 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7760 } else {
7761 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7762 }
lucasline117e2e2019-10-22 18:27:33 +08007763 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007764
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007765 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007766 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7767 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007768 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007769 }
7770
Lorenzo Colittibd079452021-07-02 11:47:57 +09007771 if (nai.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007772 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7773 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007774 }
7775
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007776 return newNc;
7777 }
7778
Lorenzo Colitti44840702021-01-11 22:27:57 +09007779 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7780 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7781 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7782 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7783 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7784 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7785 if (prevSuspended != suspended) {
7786 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7787 // onResumed have been removed.
7788 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7789 : ConnectivityManager.CALLBACK_RESUMED);
7790 }
7791 if (prevSuspended != suspended || prevRoaming != roaming) {
7792 // updateNetworkInfo will mix in the suspended info from the capabilities and
7793 // take appropriate action for the network having possibly changed state.
7794 updateNetworkInfo(nai, nai.networkInfo);
7795 }
7796 }
7797
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007798 /**
7799 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7800 *
7801 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7802 * capabilities we manage and store in {@code nai}, such as validated status and captive
7803 * portal status)
7804 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7805 * potentially triggers rematches.
7806 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7807 * change.)
7808 *
7809 * @param oldScore score of the network before any of the changes that prompted us
7810 * to call this function.
7811 * @param nai the network having its capabilities updated.
7812 * @param nc the new network capabilities.
7813 */
Chalard Jean62edfd82019-12-02 18:39:29 +09007814 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7815 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007816 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007817 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09007818 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09007819 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007820
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007821 updateVpnUids(nai, prevNc, newNc);
7822 updateAccessUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09007823 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007824
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007825 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007826 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7827 // the change we're processing can't affect any requests, it can only affect the listens
7828 // on this network. We might have been called by rematchNetworkAndRequests when a
7829 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09007830 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007831 } else {
7832 // If the requestable capabilities have changed or the score changed, we can't have been
7833 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09007834 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04007835 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07007836 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09007837 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007838
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007839 final boolean oldMetered = prevNc.isMetered();
7840 final boolean newMetered = newNc.isMetered();
7841 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08007842
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007843 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00007844 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7845 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007846 }
junyulaif2c67e42018-08-07 19:50:45 +08007847
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007848 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7849 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08007850
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007851 // Report changes that are interesting for network statistics tracking.
7852 if (meteredChanged || roamingChanged) {
7853 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06007854 }
7855
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007856 // This network might have been underlying another network. Propagate its capabilities.
7857 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08007858
7859 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007860 mDnsManager.updateTransportsForNetwork(
7861 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08007862 }
lucaslin53e8a262021-06-08 01:43:59 +08007863
7864 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007865 }
7866
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007867 /** Convenience method to update the capabilities for a given network. */
7868 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7869 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7870 }
7871
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007872 /**
7873 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7874 * network.
7875 *
7876 * Ingress interface filtering enforces that all apps under the given network can only receive
7877 * packets from the network's interface (and loopback). This is important for VPNs because
7878 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7879 * non-VPN interfaces.
7880 *
7881 * As a result, this method should return true iff
7882 * 1. the network is an app VPN (not legacy VPN)
7883 * 2. the VPN does not allow bypass
7884 * 3. the VPN is fully-routed
7885 * 4. the VPN interface is non-null
7886 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007887 * @see INetd#firewallAddUidInterfaceRules
7888 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007889 */
7890 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7891 LinkProperties lp) {
7892 if (nc == null || lp == null) return false;
7893 return nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007894 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08007895 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007896 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08007897 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7898 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007899 }
7900
Chiachang Wang28afaff2020-12-10 22:24:47 +08007901 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7902 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7903 int index = 0;
7904 for (UidRange range : ranges) {
7905 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7906 index++;
7907 }
7908 return stableRanges;
7909 }
7910
Chalard Jeane6c95272022-01-25 21:04:21 +09007911 private static UidRangeParcel[] intsToUidRangeStableParcels(
7912 final @NonNull ArraySet<Integer> uids) {
7913 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
7914 int index = 0;
7915 for (int uid : uids) {
7916 stableRanges[index] = new UidRangeParcel(uid, uid);
7917 index++;
7918 }
7919 return stableRanges;
7920 }
7921
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007922 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7923 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7924 for (int i = 0; i < ranges.length; i++) {
7925 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7926 }
7927 return stableRanges;
7928 }
7929
Ken Chen5e65a852020-12-24 12:59:10 +08007930 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7931 int[] exemptUids) {
7932 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7933 try {
7934 mNetd.socketDestroy(ranges, exemptUids);
7935 } catch (Exception e) {
7936 loge("Exception in socket destroy: ", e);
7937 }
7938 }
7939 }
7940
paulhuaa0743d2021-05-26 21:56:03 +08007941 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08007942 int[] exemptUids = new int[2];
7943 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7944 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7945 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7946 exemptUids[0] = VPN_UID;
7947 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7948 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7949
7950 maybeCloseSockets(nai, ranges, exemptUids);
7951 try {
7952 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08007953 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007954 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08007955 } else {
paulhu0e79d952021-06-09 16:11:35 +08007956 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007957 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08007958 }
7959 } catch (Exception e) {
7960 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7961 " on netId " + nai.network.netId + ". " + e);
7962 }
7963 maybeCloseSockets(nai, ranges, exemptUids);
7964 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007965
lucaslin53e8a262021-06-08 01:43:59 +08007966 private boolean isProxySetOnAnyDefaultNetwork() {
7967 ensureRunningOnConnectivityServiceThread();
7968 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7969 final NetworkAgentInfo nai = nri.getSatisfier();
7970 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
7971 return true;
7972 }
7973 }
7974 return false;
7975 }
7976
7977 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7978 NetworkCapabilities newNc) {
7979 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
7980 // the proxy might be changed since the default network satisfied by the apps might also
7981 // changed.
7982 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
7983 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09007984 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
7985 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
7986 if (nai.isVPN() && nai.everConnected && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08007987 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
7988 mProxyTracker.sendProxyBroadcast();
7989 }
7990 }
7991
Chalard Jeane6c95272022-01-25 21:04:21 +09007992 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
7993 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007994 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7995 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007996 if (null == prevRanges) prevRanges = new ArraySet<>();
7997 if (null == newRanges) newRanges = new ArraySet<>();
7998 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7999
8000 prevRanges.removeAll(newRanges);
8001 newRanges.removeAll(prevRangesCopy);
8002
8003 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008004 // When updating the VPN uid routing rules, add the new range first then remove the old
8005 // range. If old range were removed first, there would be a window between the old
8006 // range being removed and the new range being added, during which UIDs contained
8007 // in both ranges are not subject to any VPN routing rules. Adding new range before
8008 // removing old range works because, unlike the filtering rules below, it's possible to
8009 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008010 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8011 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8012 // [1-5] & [1-2],[4-5] == [3]
8013 // Then we can do:
8014 // maybeCloseSockets([3])
8015 // mNetd.networkAddUidRanges([1-2],[4-5])
8016 // mNetd.networkRemoveUidRanges([1-5])
8017 // maybeCloseSockets([3])
8018 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8019 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008020 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008021 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008022 }
8023 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008024 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008025 }
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008026 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
8027 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
8028 final String iface = nai.linkProperties.getInterfaceName();
8029 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008030 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008031 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8032 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8033 // were added first and then newRanges got removed later, there would be only one uid
8034 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8035 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8036 // Note that this is in contrast with the (more robust) update of VPN routing rules
8037 // above, where the addition of new ranges happens before the removal of old ranges.
8038 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8039 // to be removed will never overlap with the new range to be added.
8040 if (wasFiltering && !prevRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08008041 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008042 }
8043 if (shouldFilter && !newRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08008044 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008045 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008046 } catch (Exception e) {
8047 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008048 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008049 }
8050 }
8051
Chalard Jeane6c95272022-01-25 21:04:21 +09008052 private void updateAccessUids(@NonNull NetworkAgentInfo nai,
8053 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8054 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
8055 final boolean prevEmpty = null == prevNc || prevNc.getAccessUidsNoCopy().isEmpty();
8056 final boolean newEmpty = null == newNc || newNc.getAccessUidsNoCopy().isEmpty();
8057 if (prevEmpty && newEmpty) return;
8058
8059 final ArraySet<Integer> prevUids =
8060 null == prevNc ? new ArraySet<>() : prevNc.getAccessUidsNoCopy();
8061 final ArraySet<Integer> newUids =
8062 null == newNc ? new ArraySet<>() : newNc.getAccessUidsNoCopy();
8063
8064 if (prevUids.equals(newUids)) return;
8065
8066 // This implementation is very simple and vastly faster for sets of Integers than
8067 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8068 // a key computed from the value and has storage for that.
8069 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8070 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8071 toRemove.removeAll(newUids);
8072 toAdd.removeAll(prevUids);
8073
8074 try {
8075 if (!toAdd.isEmpty()) {
8076 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8077 nai.network.netId,
8078 intsToUidRangeStableParcels(toAdd),
8079 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8080 }
8081 if (!toRemove.isEmpty()) {
8082 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8083 nai.network.netId,
8084 intsToUidRangeStableParcels(toRemove),
8085 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8086 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008087 } catch (ServiceSpecificException e) {
8088 // Has the interface disappeared since the network was built ?
8089 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008090 } catch (RemoteException e) {
8091 // Netd died. This usually causes a runtime restart anyway.
8092 }
8093 }
8094
Hugo Benichi9d35b752017-09-01 01:23:32 +00008095 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008096 ensureRunningOnConnectivityServiceThread();
8097
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008098 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008099 // Ignore updates for disconnected networks
8100 return;
8101 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008102 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008103 log("Update of LinkProperties for " + nai.toShortString()
8104 + "; created=" + nai.created
8105 + "; everConnected=" + nai.everConnected);
Hugo Benichi9d35b752017-09-01 01:23:32 +00008106 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008107 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8108 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008109 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008110 }
8111
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008112 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8113 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008114 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008115 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008116 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008117 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8118 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8119 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008120 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8121 // need to be sent as a separate extra.
8122 final NetworkRequest req = nri.isMultilayerRequest()
8123 ? nri.getActiveRequest()
8124 // Non-multilayer listen requests do not have an active request
8125 : nri.mRequests.get(0);
8126 if (req == null) {
8127 Log.wtf(TAG, "No request in NRI " + nri);
8128 }
8129 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008130 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008131 sendIntent(nri.mPendingIntent, intent);
8132 }
8133 // else not handled
8134 }
8135
8136 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8137 mPendingIntentWakeLock.acquire();
8138 try {
8139 if (DBG) log("Sending " + pendingIntent);
8140 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
8141 } catch (PendingIntent.CanceledException e) {
8142 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8143 mPendingIntentWakeLock.release();
8144 releasePendingNetworkRequest(pendingIntent);
8145 }
8146 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8147 }
8148
8149 @Override
8150 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8151 String resultData, Bundle resultExtras) {
8152 if (DBG) log("Finished sending " + pendingIntent);
8153 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008154 // Release with a delay so the receiving client has an opportunity to put in its
8155 // own request.
8156 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008157 }
8158
James Mattis212df9e2020-12-03 19:57:41 -08008159 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
8160 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
8161 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008162 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008163 // Default request has no msgr. Also prevents callbacks from being invoked for
8164 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8165 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8166 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008167 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008168 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008169 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008170 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008171 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008172 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008173 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008174 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8175 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008176 }
Roshan Pius951c0032020-12-22 15:10:42 -08008177 final boolean includeLocationSensitiveInfo =
8178 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008179 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008180 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008181 final NetworkCapabilities nc =
8182 networkCapabilitiesRestrictedForCallerPermissions(
8183 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8184 putParcelable(
8185 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008186 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008187 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008188 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008189 nri.mCallingAttributionTag));
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008190 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8191 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008192 // For this notification, arg1 contains the blocked status.
8193 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008194 break;
8195 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008196 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008197 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008198 break;
8199 }
8200 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008201 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008202 final NetworkCapabilities netCap =
8203 networkCapabilitiesRestrictedForCallerPermissions(
8204 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8205 putParcelable(
8206 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008207 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008208 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008209 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008210 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008211 break;
8212 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008213 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008214 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8215 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008216 break;
8217 }
junyulaif2c67e42018-08-07 19:50:45 +08008218 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008219 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008220 msg.arg1 = arg1;
8221 break;
8222 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008223 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008224 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008225 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008226 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008227 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008228 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008229 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008230 }
James Mattis45d81842021-01-10 14:24:24 -08008231 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008232 } catch (RemoteException e) {
8233 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008234 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008235 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008236 }
8237
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008238 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8239 bundle.putParcelable(t.getClass().getSimpleName(), t);
8240 }
8241
Chalard Jean0702f982021-09-16 21:50:07 +09008242 /**
8243 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8244 *
8245 * When a request should be assigned to a new network, it is normally lingered to give
8246 * time for apps to gracefully migrate their connections. When both networks are on the same
8247 * radio, but that radio can't do time-sharing efficiently, this may end up being
8248 * counter-productive because any traffic on the old network may drastically reduce the
8249 * performance of the new network.
8250 * The stack supports a configuration to let modem vendors state that their radio can't
8251 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8252 * from one cell network to another can't be done gracefully.
8253 *
8254 * @param oldNai the old network serving the request
8255 * @param newNai the new network serving the request
8256 * @return whether the switch can be graceful
8257 */
8258 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8259 @NonNull final NetworkAgentInfo newSatisfier) {
8260 if (mCellularRadioTimesharingCapable) return true;
8261 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8262 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8263 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8264 }
8265
Paul Jensenaf94b982014-09-30 15:37:41 -04008266 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008267 if (nai.numRequestNetworkRequests() != 0) {
8268 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8269 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008270 // Ignore listening and track default requests.
8271 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008272 loge("Dead network still had at least " + nr);
8273 break;
8274 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008275 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008276 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008277 }
8278
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008279 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8280 if (oldNetwork == null) {
8281 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8282 return;
8283 }
Chalard Jean49707572019-12-10 21:07:02 +09008284 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008285
8286 // If we get here it means that the last linger timeout for this network expired. So there
8287 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008288 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008289
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008290 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008291 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008292 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008293 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008294 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008295 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008296 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008297 }
8298
James Mattise3ef1912020-12-20 11:09:58 -08008299 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8300 boolean isDefaultChanged = false;
8301 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8302 final NetworkReassignment.RequestReassignment reassignment =
8303 changes.getReassignment(defaultRequestInfo);
8304 if (null == reassignment) {
8305 continue;
8306 }
8307 // reassignment only contains those instances where the satisfying network changed.
8308 isDefaultChanged = true;
8309 // Notify system services of the new default.
8310 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8311 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008312
James Mattise3ef1912020-12-20 11:09:58 -08008313 if (isDefaultChanged) {
8314 // Hold a wakelock for a short time to help apps in migrating to a new default.
8315 scheduleReleaseNetworkTransitionWakelock();
8316 }
8317 }
8318
8319 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8320 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8321 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8322 if (DBG) {
8323 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8324 }
Chalard Jean8e382112019-12-03 20:45:30 +09008325
James Mattisd31bdfa2020-12-23 16:37:26 -08008326 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8327 if (newDefaultNetwork != null) {
8328 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008329 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008330
James Mattisd31bdfa2020-12-23 16:37:26 -08008331 // Set an app level managed default and return since further processing only applies to the
8332 // default network.
8333 if (mDefaultRequest != nri) {
8334 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8335 return;
8336 }
8337
8338 makeDefaultNetwork(newDefaultNetwork);
8339
James Mattise3ef1912020-12-20 11:09:58 -08008340 if (oldDefaultNetwork != null) {
8341 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8342 }
8343 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008344 handleApplyDefaultProxy(null != newDefaultNetwork
8345 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8346 updateTcpBufferSizes(null != newDefaultNetwork
8347 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008348 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008349 }
8350
James Mattisd31bdfa2020-12-23 16:37:26 -08008351 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8352 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8353 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8354 try {
8355 if (VDBG) {
8356 log("Setting default network for " + nri
8357 + " using UIDs " + nri.getUids()
8358 + " with old network " + (oldDefaultNetwork != null
8359 ? oldDefaultNetwork.network().getNetId() : "null")
8360 + " and new network " + (newDefaultNetwork != null
8361 ? newDefaultNetwork.network().getNetId() : "null"));
8362 }
8363 if (nri.getUids().isEmpty()) {
8364 throw new IllegalStateException("makeDefaultForApps called without specifying"
8365 + " any applications to set as the default." + nri);
8366 }
8367 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008368 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008369 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008370 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008371 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008372 }
8373 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008374 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008375 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008376 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008377 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008378 }
8379 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008380 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008381 }
8382 }
8383
8384 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8385 try {
8386 if (null != newDefaultNetwork) {
8387 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8388 } else {
8389 mNetd.networkClearDefault();
8390 }
8391 } catch (RemoteException | ServiceSpecificException e) {
8392 loge("Exception setting default network :" + e);
8393 }
8394 }
8395
Chalard Jean05cbe972019-12-09 11:50:38 +09008396 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008397 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008398 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008399 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008400 processNewlySatisfiedListenRequests(nai);
8401 }
8402
8403 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008404 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8405 if (nri.isMultilayerRequest()) {
8406 continue;
8407 }
8408 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008409 if (!nr.isListen()) continue;
8410 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008411 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008412 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8413 }
8414 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008415 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008416
Chalard Jeancd397a22019-11-22 22:33:33 +09008417 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008418 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8419 if (nri.isMultilayerRequest()) {
8420 continue;
8421 }
8422 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008423 if (!nr.isListen()) continue;
8424 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8425 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008426 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008427 }
8428 }
8429 }
8430
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008431 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008432 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008433 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008434 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008435 @Nullable public final NetworkRequest mOldNetworkRequest;
8436 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008437 @Nullable public final NetworkAgentInfo mOldNetwork;
8438 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008439 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008440 @Nullable final NetworkRequest oldNetworkRequest,
8441 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008442 @Nullable final NetworkAgentInfo oldNetwork,
8443 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008444 mNetworkRequestInfo = networkRequestInfo;
8445 mOldNetworkRequest = oldNetworkRequest;
8446 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008447 mOldNetwork = oldNetwork;
8448 mNewNetwork = newNetwork;
8449 }
Chalard Jean49707572019-12-10 21:07:02 +09008450
8451 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008452 final NetworkRequest requestToShow = null != mNewNetworkRequest
8453 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8454 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008455 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8456 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008457 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008458 }
8459
Chalard Jean46a62372019-12-10 21:25:24 +09008460 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008461
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008462 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008463 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008464 }
8465
8466 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008467 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008468 // The code is never supposed to add two reassignments of the same request. Make
8469 // sure this stays true, but without imposing this expensive check on all
8470 // reassignments on all user devices.
8471 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008472 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008473 throw new IllegalStateException("Trying to reassign ["
8474 + reassignment + "] but already have ["
8475 + existing + "]");
8476 }
8477 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008478 }
Chalard Jean46a62372019-12-10 21:25:24 +09008479 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008480 }
8481
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008482 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008483 // the passed request.
8484 @Nullable
8485 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008486 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008487 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008488 }
8489 return null;
8490 }
Chalard Jean49707572019-12-10 21:07:02 +09008491
8492 public String toString() {
8493 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8494 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008495 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008496 for (final RequestReassignment rr : getRequestReassignments()) {
8497 sj.add(rr.toString());
8498 }
8499 return sj.toString();
8500 }
8501
8502 public String debugString() {
8503 final StringBuilder sb = new StringBuilder();
8504 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09008505 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008506 for (final RequestReassignment rr : getRequestReassignments()) {
8507 sb.append("\n ").append(rr);
8508 }
8509 return sb.append("\n").toString();
8510 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008511 }
8512
Chalard Jean24344d72019-12-04 13:32:31 +09008513 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008514 @Nullable final NetworkRequest previousRequest,
8515 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09008516 @Nullable final NetworkAgentInfo previousSatisfier,
8517 @Nullable final NetworkAgentInfo newSatisfier,
8518 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08008519 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09008520 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09008521 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008522 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008523 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09008524 }
James Mattisa076c532020-12-02 14:12:41 -08008525 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean0702f982021-09-16 21:50:07 +09008526 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)) {
8527 // If this network switch can't be supported gracefully, the request is not
8528 // lingered. This allows letting go of the network sooner to reclaim some
8529 // performance on the new network, since the radio can't do both at the same
8530 // time while preserving good performance.
8531 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8532 }
Chalard Jean24344d72019-12-04 13:32:31 +09008533 } else {
8534 if (VDBG || DDBG) log(" accepting network in place of null");
8535 }
junyulai0ac374f2020-12-14 18:41:52 +08008536
8537 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8538 // and immediately satisfies a request then remove the timer. This will happen for
8539 // all networks except in the case of an underlying network for a VCN.
8540 if (newSatisfier.isNascent()) {
8541 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08008542 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008543 }
8544
Chalard Jean5d6e23b2021-03-01 22:00:20 +09008545 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08008546 newSatisfier.unlingerRequest(newRequest.requestId);
8547 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008548 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08008549 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008550 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09008551 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008552 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008553 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08008554 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008555 }
James Mattisa076c532020-12-02 14:12:41 -08008556 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008557 }
James Mattisa076c532020-12-02 14:12:41 -08008558 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008559 }
8560
James Mattisa076c532020-12-02 14:12:41 -08008561 /**
8562 * This function is triggered when something can affect what network should satisfy what
8563 * request, and it computes the network reassignment from the passed collection of requests to
8564 * network match to the one that the system should now have. That data is encoded in an
8565 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8566 * satisfier.
8567 *
8568 * After the reassignment is computed, it is applied to the state objects.
8569 *
8570 * @param networkRequests the nri objects to evaluate for possible network reassignment
8571 * @return NetworkReassignment listing of proposed network assignment changes
8572 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008573 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08008574 private NetworkReassignment computeNetworkReassignment(
8575 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09008576 final NetworkReassignment changes = new NetworkReassignment();
8577
Chalard Jeanc81d4c32021-04-07 17:06:19 +09008578 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09008579 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008580 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattisa076c532020-12-02 14:12:41 -08008581 if (!nai.everConnected) {
8582 continue;
8583 }
Chalard Jean857a1712019-12-10 21:08:07 +09008584 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09008585 }
Chalard Jean857a1712019-12-10 21:08:07 +09008586
James Mattisa076c532020-12-02 14:12:41 -08008587 for (final NetworkRequestInfo nri : networkRequests) {
8588 // Non-multilayer listen requests can be ignored.
8589 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8590 continue;
8591 }
8592 NetworkAgentInfo bestNetwork = null;
8593 NetworkRequest bestRequest = null;
8594 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09008595 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08008596 // Stop evaluating as the highest possible priority request is satisfied.
8597 if (null != bestNetwork) {
8598 bestRequest = req;
8599 break;
8600 }
8601 }
James Mattisd31bdfa2020-12-23 16:37:26 -08008602 if (null == bestNetwork && isDefaultBlocked(nri)) {
8603 // Remove default networking if disallowed for managed default requests.
8604 bestNetwork = mNoServiceNetwork;
8605 }
8606 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008607 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008608 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008609 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008610 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008611 }
8612 return changes;
8613 }
8614
James Mattisa076c532020-12-02 14:12:41 -08008615 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8616 return new HashSet<>(mNetworkRequests.values());
8617 }
8618
Paul Jensenc88b39b2015-06-16 14:27:36 -04008619 /**
James Mattisa076c532020-12-02 14:12:41 -08008620 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008621 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008622 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008623 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008624 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8625 }
8626
8627 /**
8628 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8629 * being disconnected.
8630 */
8631 private void rematchNetworksAndRequests(
8632 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8633 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008634 // TODO: This may be slow, and should be optimized.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008635 final long now = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008636 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jean49707572019-12-10 21:07:02 +09008637 if (VDBG || DDBG) {
8638 log(changes.debugString());
8639 } else if (DBG) {
8640 log(changes.toString()); // Shorter form, only one line of log
8641 }
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008642 applyNetworkReassignment(changes, now);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008643 issueNetworkNeeds();
Chalard Jeand7f762d2019-12-10 19:01:29 +09008644 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008645
Chalard Jeand7f762d2019-12-10 19:01:29 +09008646 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008647 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008648 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008649
8650 // Since most of the time there are only 0 or 1 background networks, it would probably
8651 // be more efficient to just use an ArrayList here. TODO : measure performance
8652 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8653 for (final NetworkAgentInfo nai : nais) {
8654 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8655 }
8656
Chalard Jeand7f762d2019-12-10 19:01:29 +09008657 // First, update the lists of satisfied requests in the network agents. This is necessary
8658 // because some code later depends on this state to be correct, most prominently computing
8659 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008660 for (final NetworkReassignment.RequestReassignment event :
8661 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008662 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8663 event.mOldNetworkRequest, event.mNewNetworkRequest,
8664 event.mOldNetwork, event.mNewNetwork,
8665 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008666 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008667
James Mattise3ef1912020-12-20 11:09:58 -08008668 // Process default network changes if applicable.
8669 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008670
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008671 // Notify requested networks are available after the default net is switched, but
8672 // before LegacyTypeTracker sends legacy broadcasts
8673 for (final NetworkReassignment.RequestReassignment event :
8674 changes.getRequestReassignments()) {
8675 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008676 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008677 } else {
James Mattisa076c532020-12-02 14:12:41 -08008678 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008679 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008680 }
8681 }
8682
junyulai0ac374f2020-12-14 18:41:52 +08008683 // Update the inactivity state before processing listen callbacks, because the background
8684 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008685 // just yet though, because they have to be sent after the listens are processed to keep
8686 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008687 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008688 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008689 // Rematching may have altered the inactivity state of some networks, so update all
8690 // inactivity timers. updateInactivityState reads the state from the network agent
8691 // and does nothing if the state has not changed : the source of truth is controlled
8692 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8693 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008694 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008695 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008696 }
8697 }
8698
Chalard Jeanb10ab412019-12-11 14:12:30 +09008699 for (final NetworkAgentInfo nai : nais) {
8700 if (!nai.everConnected) continue;
8701 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008702 // Process listen requests and update capabilities if the background state has
8703 // changed for this network. For consistency with previous behavior, send onLost
8704 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008705 processNewlyLostListenRequests(nai);
8706 if (oldBackground != nai.isBackgroundNetwork()) {
8707 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008708 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008709 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008710 }
8711
junyulai0ac374f2020-12-14 18:41:52 +08008712 for (final NetworkAgentInfo nai : inactiveNetworks) {
8713 // For nascent networks, if connecting with no foreground request, skip broadcasting
8714 // LOSING for backward compatibility. This is typical when mobile data connected while
8715 // wifi connected with mobile data always-on enabled.
8716 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008717 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008718 }
8719
James Mattise3ef1912020-12-20 11:09:58 -08008720 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008721
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008722 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008723 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008724 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008725 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008726 // This network has active linger timers and no requests, but is not
8727 // lingering. Linger it.
8728 //
8729 // One way (the only way?) this can happen if this network is unvalidated
8730 // and became unneeded due to another network improving its score to the
8731 // point where this network will no longer be able to satisfy any requests
8732 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008733 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008734 notifyNetworkLosing(nai, now);
8735 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008736 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008737 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008738 teardownUnneededNetwork(nai);
8739 }
8740 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008741 }
8742 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008743
Chalard Jean62edfd82019-12-02 18:39:29 +09008744 /**
8745 * Apply a change in background state resulting from rematching networks with requests.
8746 *
8747 * During rematch, a network may change background states by starting to satisfy or stopping
8748 * to satisfy a foreground request. Listens don't count for this. When a network changes
8749 * background states, its capabilities need to be updated and callbacks fired for the
8750 * capability change.
8751 *
8752 * @param nai The network that changed background states
8753 */
8754 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8755 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8756 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8757 updateNetworkPermissions(nai, newNc);
8758 nai.getAndSetNetworkCapabilities(newNc);
8759 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8760 }
8761
Chalard Jeanf0344532019-11-19 19:23:38 +09008762 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008763 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008764 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008765 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8766 changes.getReassignment(mDefaultRequest);
8767 final NetworkAgentInfo oldDefaultNetwork =
8768 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8769 final NetworkAgentInfo newDefaultNetwork =
8770 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008771
Chalard Jean5b409c72021-02-04 13:12:59 +09008772 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008773 // Maintain the illusion : since the legacy API only understands one network at a time,
8774 // if the default network changed, apps should see a disconnected broadcast for the
8775 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09008776 if (oldDefaultNetwork != null) {
8777 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8778 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008779 }
Chalard Jean5b409c72021-02-04 13:12:59 +09008780 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008781 // The new default network can be newly null if and only if the old default
8782 // network doesn't satisfy the default request any more because it lost a
8783 // capability.
Chalard Jean5b409c72021-02-04 13:12:59 +09008784 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08008785 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09008786 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008787 }
8788 }
8789
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008790 // Now that all the callbacks have been sent, send the legacy network broadcasts
8791 // as needed. This is necessary so that legacy requests correctly bind dns
8792 // requests to this network. The legacy users are listening for this broadcast
8793 // and will generally do a dns request so they can ensureRouteToHost and if
8794 // they do that before the callbacks happen they'll use the default network.
8795 //
8796 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8797 // callbacks, but if apps can receive the broadcast before the callback, they still might
8798 // have an inconsistent view of networking.
8799 //
8800 // This *does* introduce a race where if the user uses the new api
8801 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8802 // they may get old info. Reverse this after the old startUsing api is removed.
8803 // This is on top of the multiple intent sequencing referenced in the todo above.
8804 for (NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008805 if (nai.everConnected) {
8806 addNetworkToLegacyTypeTracker(nai);
8807 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008808 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008809 }
8810
Chalard Jean0354d8c2021-01-12 10:58:56 +09008811 private void issueNetworkNeeds() {
8812 ensureRunningOnConnectivityServiceThread();
8813 for (final NetworkOfferInfo noi : mNetworkOffers) {
8814 issueNetworkNeeds(noi);
8815 }
8816 }
8817
8818 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8819 ensureRunningOnConnectivityServiceThread();
8820 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8821 informOffer(nri, noi.offer, mNetworkRanker);
8822 }
8823 }
8824
8825 /**
8826 * Inform a NetworkOffer about any new situation of a request.
8827 *
8828 * This function handles updates to offers. A number of events may happen that require
8829 * updating the registrant for this offer about the situation :
8830 * • The offer itself was updated. This may lead the offer to no longer being able
8831 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8832 * or conversely being strengthened enough to beat the satisfier (and therefore
8833 * start being needed)
8834 * • The network satisfying a request changed (including cases where the request
8835 * starts or stops being satisfied). The new network may be a stronger or weaker
8836 * match than the old one, possibly affecting whether the offer is needed.
8837 * • The network satisfying a request updated their score. This may lead the offer
8838 * to no longer be able to beat it if the current satisfier got better, or
8839 * conversely start being a good choice if the current satisfier got weaker.
8840 *
8841 * @param nri The request
8842 * @param offer The offer. This may be an updated offer.
8843 */
8844 private static void informOffer(@NonNull NetworkRequestInfo nri,
8845 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8846 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8847 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09008848
8849 // Multi-layer requests have a currently active request, the one being satisfied.
8850 // Since the system will try to bring up a better network than is currently satisfying
8851 // the request, NetworkProviders need to be told the offers matching the requests *above*
8852 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8853 // not needed, and the offer is needed for the active request iff the offer can beat
8854 // the satisfier.
8855 // For non-multilayer requests, the logic above gracefully degenerates to only the
8856 // last case.
8857 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8858 // providers that the offer is needed for this request, until the active request is found.
8859 // In a second phase, deal with the currently active request. In a third phase, inform
8860 // the providers that offer is unneeded for the remaining requests.
8861
8862 // First phase : inform providers of all requests above the active request.
8863 int i;
8864 for (i = 0; nri.mRequests.size() > i; ++i) {
8865 final NetworkRequest request = nri.mRequests.get(i);
8866 if (activeRequest == request) break; // Found the active request : go to phase 2
8867 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8868 // Since this request is higher-priority than the one currently satisfied, if the
8869 // offer can satisfy it, the provider should try and bring up the network for sure ;
8870 // no need to even ask the ranker – an offer that can satisfy is always better than
8871 // no network. Hence tell the provider so unless it already knew.
8872 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8873 offer.onNetworkNeeded(request);
8874 }
8875 }
8876
8877 // Second phase : deal with the active request (if any)
8878 if (null != activeRequest && activeRequest.isRequest()) {
8879 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00008880 // If an offer can satisfy the request, it is considered needed if it is currently
8881 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09008882 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00008883 && satisfier.factorySerialNumber == offer.providerId
8884 && activeRequest.canBeSatisfiedBy(offer.caps);
8885 final boolean newNeeded = currentlyServing
8886 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008887 if (newNeeded != oldNeeded) {
8888 if (newNeeded) {
8889 offer.onNetworkNeeded(activeRequest);
8890 } else {
8891 // The offer used to be able to beat the satisfier. Now it can't.
8892 offer.onNetworkUnneeded(activeRequest);
8893 }
8894 }
8895 }
8896
8897 // Third phase : inform the providers that the offer isn't needed for any request
8898 // below the active one.
8899 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8900 final NetworkRequest request = nri.mRequests.get(i);
8901 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8902 // Since this request is lower-priority than the one currently satisfied, if the
8903 // offer can satisfy it, the provider should not try and bring up the network.
8904 // Hence tell the provider so unless it already knew.
8905 if (offer.neededFor(request)) {
8906 offer.onNetworkUnneeded(request);
8907 }
8908 }
8909 }
8910
Chalard Jean61c79252019-11-07 23:07:32 +09008911 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8912 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8913 NetworkRequest nr = nai.requestAt(i);
8914 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8915 // legacy type tracker filters out repeat adds
8916 mLegacyTypeTracker.add(nr.legacyType, nai);
8917 }
8918 }
8919
8920 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09008921 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09008922 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8923 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8924 if (nai.isVPN()) {
8925 mLegacyTypeTracker.add(TYPE_VPN, nai);
8926 }
8927 }
8928
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008929 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04008930 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittia8de5ca2014-12-17 11:14:42 +09008931 if (!nai.everValidated) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09008932 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04008933 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09008934 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008935
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008936 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008937 // Don't repeat publish.
8938 if (newInetCondition == mDefaultInetConditionPublished) return;
8939
8940 mDefaultInetConditionPublished = newInetCondition;
8941 sendInetConditionBroadcast(nai.networkInfo);
8942 }
8943
Chalard Jeand61375d2020-01-14 22:46:36 +09008944 @NonNull
8945 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8946 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008947 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09008948 final boolean suspended =
8949 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8950 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8951 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8952 // state. This is because the network could have been suspended before connecting,
8953 // or it could be disconnecting while being suspended, and in both these cases
8954 // the state should not be overridden. Note that the only detailed state that
8955 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8956 // worry about multiple different substates of CONNECTED.
8957 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8958 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08008959 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8960 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8961 // network agent is created, then goes to suspended, then goes out of suspended without
8962 // ever setting connected. Check if network agent is ever connected to update the state.
8963 newInfo.setDetailedState(nai.everConnected
8964 ? NetworkInfo.DetailedState.CONNECTED
8965 : NetworkInfo.DetailedState.CONNECTING,
8966 info.getReason(),
8967 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09008968 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008969 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09008970 return newInfo;
8971 }
8972
8973 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8974 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8975
Erik Kline99f301b2017-02-15 19:59:17 +09008976 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008977 NetworkInfo oldInfo = null;
8978 synchronized (networkAgent) {
8979 oldInfo = networkAgent.networkInfo;
8980 networkAgent.networkInfo = newInfo;
8981 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008982
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008983 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008984 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8985 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008986 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008987
Robin Leea8c0b6e2016-05-01 23:00:00 +01008988 if (!networkAgent.created
8989 && (state == NetworkInfo.State.CONNECTED
8990 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008991
8992 // A network that has just connected has zero requests and is thus a foreground network.
8993 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8994
Patrick Rohr2857ac42022-01-21 14:58:16 +01008995 // If a rate limit has been configured and is applicable to this network (network
8996 // provides internet connectivity), apply it.
8997 // Note: in case of a system server crash, there is a very small chance that this
8998 // leaves some interfaces rate limited (i.e. if the rate limit had been changed just
8999 // before the crash and was never applied). One solution would be to delete all
9000 // potential tc police filters every time this is called. Since this is an unlikely
9001 // scenario in the first place (and worst case, the interface stays rate limited until
9002 // the device is rebooted), this seems a little overkill.
9003 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9004 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9005 mIngressRateLimit);
9006 }
9007
Luke Huangfdd11f82019-04-09 18:41:49 +08009008 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09009009 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009010 // Initialize the network's capabilities to their starting values according to the
9011 // underlying networks. This ensures that the capabilities are correct before
9012 // anything happens to the network.
9013 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009014 }
Paul Jensen74940202014-08-04 12:21:19 -04009015 networkAgent.created = true;
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009016 networkAgent.onNetworkCreated();
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009017 updateAccessUids(networkAgent, null, networkAgent.networkCapabilities);
Robin Leea8c0b6e2016-05-01 23:00:00 +01009018 }
9019
9020 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
9021 networkAgent.everConnected = true;
9022
lucaslin45e639b2019-04-03 17:09:28 +08009023 // NetworkCapabilities need to be set before sending the private DNS config to
9024 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009025 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9026
Erik Kline9a62f012018-03-21 07:18:33 -07009027 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08009028 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
9029 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009030
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009031 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9032 // command must be sent after updating LinkProperties to maximize chances of
9033 // NetworkMonitor seeing the correct LinkProperties when starting.
9034 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009035 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009036 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009037 }
Chalard Jeand4900722022-02-06 12:25:38 +09009038 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9039 params.networkAgentConfig = networkAgent.networkAgentConfig;
9040 params.networkCapabilities = networkAgent.networkCapabilities;
9041 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9042 true /* parcelSensitiveFields */);
9043 networkAgent.networkMonitor().notifyNetworkConnected(params);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09009044 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009045
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009046 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9047 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9048 // capabilities, so it only needs to be done once on initial connect, not every time the
9049 // network's capabilities change. Note that we do this before rematching the network,
9050 // so we could decide to tear it down immediately afterwards. That's fine though - on
9051 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9052 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009053 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009054
junyulai0ac374f2020-12-14 18:41:52 +08009055 // Before first rematching networks, put an inactivity timer without any request, this
9056 // allows {@code updateInactivityState} to update the state accordingly and prevent
9057 // tearing down for any {@code unneeded} evaluation in this period.
9058 // Note that the timer will not be rescheduled since the expiry time is
9059 // fixed after connection regardless of the network satisfying other requests or not.
9060 // But it will be removed as soon as the network satisfies a request for the first time.
9061 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9062 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009063 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009064
Paul Jensen05e85ee2014-09-11 11:00:39 -04009065 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009066 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009067
9068 // This has to happen after matching the requests, because callbacks are just requests.
9069 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009070 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009071 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009072 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009073 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009074 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009075 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009076 if (networkAgent.isVPN()) {
9077 // As the active or bound network changes for apps, broadcast the default proxy, as
9078 // apps may need to update their proxy data. This is called after disconnecting from
9079 // VPN to make sure we do not broadcast the old proxy data.
9080 // TODO(b/122649188): send the broadcast only to VPN users.
9081 mProxyTracker.sendProxyBroadcast();
9082 }
Yintang Gu5014b522019-06-18 14:24:32 +08009083 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
9084 state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009085 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009086 }
9087 }
9088
Chalard Jean28018572020-12-21 18:36:52 +09009089 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009090 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9091 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009092 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009093 }
9094
Erik Kline99f301b2017-02-15 19:59:17 +09009095 // Notify only this one new request of the current state. Transfer all the
9096 // current state by calling NetworkCapabilities and LinkProperties callbacks
9097 // so that callers can be guaranteed to have as close to atomicity in state
9098 // transfer as can be supported by this current API.
9099 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009100 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009101 if (nri.mPendingIntent != null) {
9102 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9103 // Attempt no subsequent state pushes where intents are involved.
9104 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009105 }
Erik Kline99f301b2017-02-15 19:59:17 +09009106
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009107 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009108 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009109 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9110 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9111 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009112 }
9113
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009114 // Notify the requests on this NAI that the network is now lingered.
9115 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009116 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009117 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9118 }
9119
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009120 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9121 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9122 return vpnBlocked
9123 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9124 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9125 }
9126
9127 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9128 if (blockedReasons == BLOCKED_REASON_NONE) {
9129 mUidBlockedReasons.delete(uid);
9130 } else {
9131 mUidBlockedReasons.put(uid, blockedReasons);
9132 }
9133 }
9134
junyulaif2c67e42018-08-07 19:50:45 +08009135 /**
9136 * Notify of the blocked state apps with a registered callback matching a given NAI.
9137 *
9138 * Unlike other callbacks, blocked status is different between each individual uid. So for
9139 * any given nai, all requests need to be considered according to the uid who filed it.
9140 *
9141 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009142 * @param oldMetered True if the previous network capabilities were metered.
9143 * @param newMetered True if the current network capabilities are metered.
9144 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9145 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009146 */
9147 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009148 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9149 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009150
9151 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9152 NetworkRequest nr = nai.requestAt(i);
9153 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009154
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009155 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9156 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9157 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009158 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009159 : oldVpnBlocked;
9160
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009161 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9162 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9163 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009164 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009165 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009166 }
9167 }
9168 }
9169
9170 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009171 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009172 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009173 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009174 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009175 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009176 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009177 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009178 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009179
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009180 final int oldBlockedState = getBlockedState(
9181 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9182 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9183 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009184 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009185 }
junyulaif2c67e42018-08-07 19:50:45 +08009186 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9187 NetworkRequest nr = nai.requestAt(i);
9188 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009189 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009190 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9191 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009192 }
9193 }
9194 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009195 }
9196
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009197 @VisibleForTesting
9198 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009199 // The NetworkInfo we actually send out has no bearing on the real
9200 // state of affairs. For example, if the default connection is mobile,
9201 // and a request for HIPRI has just gone away, we need to pretend that
9202 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9203 // the state to DISCONNECTED, even though the network is of type MOBILE
9204 // and is still connected.
9205 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9206 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009207 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009208 if (state != DetailedState.DISCONNECTED) {
9209 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009210 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009211 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009212 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07009213 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
9214 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
9215 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
9216 if (info.isFailover()) {
9217 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
9218 nai.networkInfo.setFailover(false);
9219 }
9220 if (info.getReason() != null) {
9221 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
9222 }
9223 if (info.getExtraInfo() != null) {
9224 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
9225 }
9226 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09009227 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08009228 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07009229 if (newDefaultAgent != null) {
9230 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
9231 newDefaultAgent.networkInfo);
9232 } else {
9233 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
9234 }
9235 }
9236 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
9237 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09009238 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009239 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09009240 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009241 }
9242 }
9243 }
9244
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009245 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009246 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009247 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09009248 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09009249 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009250 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
9251 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009252 NetworkRequestInfo nri = mNetworkRequests.get(nr);
9253 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009254 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009255 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009256 } else {
9257 sendPendingIntentForRequest(nri, networkAgent, notifyType);
9258 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009259 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009260 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009261
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009262 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
9263 notifyNetworkCallbacks(networkAgent, notifyType, 0);
9264 }
9265
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009266 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09009267 * Returns the list of all interfaces that could be used by network traffic that does not
9268 * explicitly specify a network. This includes the default network, but also all VPNs that are
9269 * currently connected.
9270 *
9271 * Must be called on the handler thread.
9272 */
junyulaie7c7d2a2021-01-26 15:29:15 +08009273 @NonNull
9274 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009275 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08009276 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08009277 final Set<Integer> activeNetIds = new ArraySet<>();
9278 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9279 if (nri.isBeingSatisfied()) {
9280 activeNetIds.add(nri.getSatisfier().network().netId);
9281 }
9282 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009283 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattis2516da32021-01-31 17:06:19 -08009284 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09009285 defaultNetworks.add(nai.network);
9286 }
9287 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009288 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09009289 }
9290
9291 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009292 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9293 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009294 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009295 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009296 ensureRunningOnConnectivityServiceThread();
9297 String activeIface = null;
9298 LinkProperties activeLinkProperties = getActiveLinkProperties();
9299 if (activeLinkProperties != null) {
9300 activeIface = activeLinkProperties.getInterfaceName();
9301 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009302
junyulai2050bed2021-01-23 09:46:34 +08009303 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009304 try {
junyulaide41fc22021-01-22 22:46:01 +08009305 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
junyulai69114da2021-03-05 14:46:25 +08009306 for (final NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaide41fc22021-01-22 22:46:01 +08009307 snapshots.add(snapshot);
9308 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009309 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9310 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009311 } catch (Exception ignored) {
9312 }
9313 }
9314
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009315 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009316 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009317 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009318 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009319 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009320
9321 if (!TextUtils.isEmpty(settingUrl)) {
9322 return settingUrl;
9323 }
9324
9325 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009326 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009327 if (!TextUtils.isEmpty(settingUrl)) {
9328 return settingUrl;
9329 }
9330
9331 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009332 }
9333
9334 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009335 public void startNattKeepalive(Network network, int intervalSeconds,
9336 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009337 enforceKeepalivePermission();
9338 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009339 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08009340 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08009341 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009342 }
9343
9344 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009345 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009346 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08009347 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07009348 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009349 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009350 mKeepaliveTracker.startNattKeepalive(
9351 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9352 intervalSeconds, cb,
9353 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
9354 } finally {
9355 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9356 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009357 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9358 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009359 }
9360 }
junyulaid05a1922019-01-15 11:32:44 +08009361 }
9362
9363 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009364 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009365 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009366 try {
9367 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009368 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009369 mKeepaliveTracker.startTcpKeepalive(
9370 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9371 } finally {
9372 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9373 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009374 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9375 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009376 }
9377 }
junyulai0835a1e2019-01-08 20:04:33 +08009378 }
9379
9380 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009381 public void stopKeepalive(Network network, int slot) {
9382 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08009383 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009384 }
9385
9386 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009387 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009388 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009389
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009390 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009391 final long token = Binder.clearCallingIdentity();
9392 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009393 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9394 UserHandle.getUserHandleForUid(uid))) {
9395 return;
9396 }
9397
Heemin Seogdb8489d2019-06-12 09:21:44 -07009398 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9399 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009400
9401 // Turn airplane mode off
9402 setAirplaneMode(false);
9403
9404 // restore private DNS settings to default mode (opportunistic)
9405 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9406 UserHandle.getUserHandleForUid(uid))) {
9407 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9408 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9409 }
9410
9411 Settings.Global.putString(mContext.getContentResolver(),
9412 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009413 } finally {
9414 Binder.restoreCallingIdentity(token);
9415 }
Stuart Scottd5463642015-04-02 18:00:02 -07009416 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009417
Ricky Wai7097cc92018-01-23 04:09:45 +00009418 @Override
9419 public byte[] getNetworkWatchlistConfigHash() {
9420 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9421 if (nwm == null) {
9422 loge("Unable to get NetworkWatchlistManager");
9423 return null;
9424 }
9425 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9426 return nwm.getWatchlistConfigHash();
9427 }
9428
Hugo Benichibe0c7652016-05-31 16:28:06 +09009429 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009430 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009431 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009432 }
Hugo Benichif4210292017-04-21 15:07:12 +09009433
9434 private static boolean toBool(int encodedBoolean) {
9435 return encodedBoolean != 0; // Only 0 means false.
9436 }
9437
9438 private static int encodeBool(boolean b) {
9439 return b ? 1 : 0;
9440 }
mswest4632928412018-03-12 10:34:34 -07009441
9442 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009443 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9444 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9445 @NonNull String[] args) {
9446 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9447 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009448 }
9449
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009450 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009451 @Override
9452 public int onCommand(String cmd) {
9453 if (cmd == null) {
9454 return handleDefaultCommands(cmd);
9455 }
9456 final PrintWriter pw = getOutPrintWriter();
9457 try {
9458 switch (cmd) {
9459 case "airplane-mode":
9460 final String action = getNextArg();
9461 if ("enable".equals(action)) {
9462 setAirplaneMode(true);
9463 return 0;
9464 } else if ("disable".equals(action)) {
9465 setAirplaneMode(false);
9466 return 0;
9467 } else if (action == null) {
9468 final ContentResolver cr = mContext.getContentResolver();
9469 final int enabled = Settings.Global.getInt(cr,
9470 Settings.Global.AIRPLANE_MODE_ON);
9471 pw.println(enabled == 0 ? "disabled" : "enabled");
9472 return 0;
9473 } else {
9474 onHelp();
9475 return -1;
9476 }
9477 default:
9478 return handleDefaultCommands(cmd);
9479 }
9480 } catch (Exception e) {
9481 pw.println(e);
9482 }
9483 return -1;
9484 }
9485
9486 @Override
9487 public void onHelp() {
9488 PrintWriter pw = getOutPrintWriter();
9489 pw.println("Connectivity service commands:");
9490 pw.println(" help");
9491 pw.println(" Print this help text.");
9492 pw.println(" airplane-mode [enable|disable]");
9493 pw.println(" Turn airplane mode on or off.");
9494 pw.println(" airplane-mode");
9495 pw.println(" Get airplane mode.");
9496 }
9497 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009498
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09009499 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009500 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
9501 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
9502 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08009503 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009504 }
9505
9506 /**
9507 * @param connectionInfo the connection to resolve.
9508 * @return {@code uid} if the connection is found and the app has permission to observe it
9509 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
9510 * connection is not found.
9511 */
9512 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009513 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
9514 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9515 }
9516
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09009517 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009518 connectionInfo.local, connectionInfo.remote);
9519
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009520 if (uid == INVALID_UID) return uid; // Not found.
9521
9522 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9523 // VPN, if any, that applies to the UID that owns the connection.
9524 if (checkNetworkStackPermission()) return uid;
9525
9526 final NetworkAgentInfo vpn = getVpnForUid(uid);
9527 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009528 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009529 return INVALID_UID;
9530 }
9531
9532 return uid;
9533 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00009534
Benedict Wong493e04b2018-11-09 14:45:34 -08009535 /**
9536 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9537 *
9538 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9539 */
9540 @Override
9541 public IBinder startOrGetTestNetworkService() {
9542 synchronized (mTNSLock) {
9543 TestNetworkService.enforceTestNetworkPermissions(mContext);
9544
9545 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08009546 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08009547 }
9548
9549 return mTNS;
9550 }
9551 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08009552
Cody Kesting73708bf2019-12-18 10:57:50 -08009553 /**
9554 * Handler used for managing all Connectivity Diagnostics related functions.
9555 *
9556 * @see android.net.ConnectivityDiagnosticsManager
9557 *
9558 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9559 */
9560 @VisibleForTesting
9561 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009562 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9563
Cody Kesting73708bf2019-12-18 10:57:50 -08009564 /**
9565 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9566 * android.net.ConnectivityDiagnosticsManager}.
9567 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9568 * NetworkRequestInfo to be registered
9569 */
9570 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9571
9572 /**
9573 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9574 * android.net.ConnectivityDiagnosticsManager}.
9575 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9576 * arg1 = the uid of the caller
9577 */
9578 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9579
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009580 /**
9581 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
9582 * after processing {@link #EVENT_NETWORK_TESTED} events.
9583 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9584 * NetworkMonitor.
9585 * data = PersistableBundle of extras passed from NetworkMonitor.
9586 *
9587 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
9588 */
9589 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
9590
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009591 /**
9592 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9593 * been detected on the network.
9594 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9595 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9596 * arg2 = NetID.
9597 * data = PersistableBundle of extras passed from NetworkMonitor.
9598 */
9599 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9600
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009601 /**
9602 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9603 * the platform. This event will invoke {@link
9604 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9605 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009606 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009607 */
9608 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9609
Cody Kesting73708bf2019-12-18 10:57:50 -08009610 private ConnectivityDiagnosticsHandler(Looper looper) {
9611 super(looper);
9612 }
9613
9614 @Override
9615 public void handleMessage(Message msg) {
9616 switch (msg.what) {
9617 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9618 handleRegisterConnectivityDiagnosticsCallback(
9619 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9620 break;
9621 }
9622 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9623 handleUnregisterConnectivityDiagnosticsCallback(
9624 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9625 break;
9626 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009627 case EVENT_NETWORK_TESTED: {
9628 final ConnectivityReportEvent reportEvent =
9629 (ConnectivityReportEvent) msg.obj;
9630
Aaron Huang959d3642021-01-21 15:47:41 +08009631 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009632 break;
9633 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009634 case EVENT_DATA_STALL_SUSPECTED: {
9635 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08009636 final Pair<Long, PersistableBundle> arg =
9637 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009638 if (nai == null) break;
9639
Aaron Huang959d3642021-01-21 15:47:41 +08009640 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009641 break;
9642 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009643 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009644 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009645 break;
9646 }
9647 default: {
9648 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9649 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009650 }
9651 }
9652 }
9653
9654 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9655 @VisibleForTesting
9656 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9657 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9658 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009659 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009660
9661 @VisibleForTesting
9662 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009663 @NonNull IConnectivityDiagnosticsCallback cb,
9664 @NonNull NetworkRequestInfo nri,
9665 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009666 mCb = cb;
9667 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009668 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009669 }
9670
9671 @Override
9672 public void binderDied() {
9673 log("ConnectivityDiagnosticsCallback IBinder died.");
9674 unregisterConnectivityDiagnosticsCallback(mCb);
9675 }
9676 }
9677
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009678 /**
9679 * Class used for sending information from {@link
9680 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9681 */
9682 private static class NetworkTestedResults {
9683 private final int mNetId;
9684 private final int mTestResult;
9685 private final long mTimestampMillis;
9686 @Nullable private final String mRedirectUrl;
9687
9688 private NetworkTestedResults(
9689 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9690 mNetId = netId;
9691 mTestResult = testResult;
9692 mTimestampMillis = timestampMillis;
9693 mRedirectUrl = redirectUrl;
9694 }
9695 }
9696
9697 /**
9698 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9699 * ConnectivityDiagnosticsHandler}.
9700 */
9701 private static class ConnectivityReportEvent {
9702 private final long mTimestampMillis;
9703 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08009704 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009705
Aaron Huang959d3642021-01-21 15:47:41 +08009706 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9707 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009708 mTimestampMillis = timestampMillis;
9709 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08009710 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009711 }
9712 }
9713
Cody Kestingf1120be2020-08-03 18:01:40 -07009714 /**
9715 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
9716 * ConnectivityDiagnosticsHandler}.
9717 */
9718 private static class ReportedNetworkConnectivityInfo {
9719 public final boolean hasConnectivity;
9720 public final boolean isNetworkRevalidating;
9721 public final int reporterUid;
9722 @NonNull public final NetworkAgentInfo nai;
9723
9724 private ReportedNetworkConnectivityInfo(
9725 boolean hasConnectivity,
9726 boolean isNetworkRevalidating,
9727 int reporterUid,
9728 @NonNull NetworkAgentInfo nai) {
9729 this.hasConnectivity = hasConnectivity;
9730 this.isNetworkRevalidating = isNetworkRevalidating;
9731 this.reporterUid = reporterUid;
9732 this.nai = nai;
9733 }
9734 }
9735
Cody Kesting73708bf2019-12-18 10:57:50 -08009736 private void handleRegisterConnectivityDiagnosticsCallback(
9737 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9738 ensureRunningOnConnectivityServiceThread();
9739
9740 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -08009741 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009742 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9743
James Mattis64b8b0f2020-11-24 17:40:49 -08009744 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9745 // confusing for these networks to change when an NRI is satisfied in another layer.
9746 if (nri.isMultilayerRequest()) {
9747 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9748 + "network requests.");
9749 }
9750
Cody Kesting73708bf2019-12-18 10:57:50 -08009751 // This means that the client registered the same callback multiple times. Do
9752 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -08009753 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009754 if (VDBG) log("Diagnostics callback is already registered");
9755
9756 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9757 // incremented when the NetworkRequestInfo is created as part of
9758 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009759 nri.decrementRequestCount();
Cody Kesting73708bf2019-12-18 10:57:50 -08009760 return;
9761 }
9762
Cody Kesting31f1ff62020-03-05 10:46:02 -08009763 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -08009764
9765 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009766 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009767 } catch (RemoteException e) {
9768 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -08009769 return;
9770 }
9771
9772 // Once registered, provide ConnectivityReports for matching Networks
9773 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9774 synchronized (mNetworkForNetId) {
9775 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9776 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -08009777 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9778 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -08009779 matchingNetworks.add(nai);
9780 }
9781 }
9782 }
9783 for (final NetworkAgentInfo nai : matchingNetworks) {
9784 final ConnectivityReport report = nai.getConnectivityReport();
9785 if (report == null) {
9786 continue;
9787 }
9788 if (!checkConnectivityDiagnosticsPermissions(
9789 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9790 continue;
9791 }
9792
9793 try {
9794 cb.onConnectivityReportAvailable(report);
9795 } catch (RemoteException e) {
9796 // Exception while sending the ConnectivityReport. Move on to the next network.
9797 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009798 }
9799 }
9800
9801 private void handleUnregisterConnectivityDiagnosticsCallback(
9802 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9803 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009804 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009805
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009806 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9807 mConnectivityDiagnosticsCallbacks.remove(iCb);
9808 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009809 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9810 return;
9811 }
9812
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009813 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -08009814
Cody Kesting70fa2b22020-12-02 12:16:56 -08009815 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9816 // (if the Binder died)
9817 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9818 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -08009819 return;
9820 }
9821
Cody Kesting46cb1672020-03-04 13:35:20 -08009822 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9823 // incremented when the NetworkRequestInfo is created as part of
9824 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009825 nri.decrementRequestCount();
Cody Kesting46cb1672020-03-04 13:35:20 -08009826
Cody Kesting31f1ff62020-03-05 10:46:02 -08009827 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009828 }
9829
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009830 private void handleNetworkTestedWithExtras(
9831 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9832 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -08009833 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009834 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009835 final ConnectivityReport report =
9836 new ConnectivityReport(
9837 reportEvent.mNai.network,
9838 reportEvent.mTimestampMillis,
9839 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009840 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009841 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -08009842 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -07009843
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009844 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009845 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009846 for (final IConnectivityDiagnosticsCallback cb : results) {
9847 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -08009848 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009849 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -07009850 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009851 }
9852 }
9853 }
9854
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009855 private void handleDataStallSuspected(
9856 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9857 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -08009858 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009859 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009860 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -08009861 new DataStallReport(
9862 nai.network,
9863 timestampMillis,
9864 detectionMethod,
9865 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009866 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -08009867 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009868 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009869 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009870 for (final IConnectivityDiagnosticsCallback cb : results) {
9871 try {
9872 cb.onDataStallSuspected(report);
9873 } catch (RemoteException ex) {
9874 loge("Error invoking onDataStallSuspected", ex);
9875 }
9876 }
9877 }
9878
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009879 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -07009880 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
9881 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
9882 final ConnectivityReport cachedReport = nai.getConnectivityReport();
9883
9884 // If the Network is being re-validated as a result of this call to
9885 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
9886 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009887 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009888 getMatchingPermissionedCallbacks(
9889 nai,
9890 reportedNetworkConnectivityInfo.isNetworkRevalidating
9891 ? Process.INVALID_UID
9892 : reportedNetworkConnectivityInfo.reporterUid);
9893
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009894 for (final IConnectivityDiagnosticsCallback cb : results) {
9895 try {
Cody Kestingf1120be2020-08-03 18:01:40 -07009896 cb.onNetworkConnectivityReported(
9897 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009898 } catch (RemoteException ex) {
9899 loge("Error invoking onNetworkConnectivityReported", ex);
9900 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009901
9902 // If the Network isn't re-validating, also provide the cached report. If there is no
9903 // cached report, the Network is still being validated and a report will be sent once
9904 // validation is complete. Note that networks which never undergo validation will still
9905 // have a cached ConnectivityReport with RESULT_SKIPPED.
9906 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
9907 try {
9908 cb.onConnectivityReportAvailable(cachedReport);
9909 } catch (RemoteException ex) {
9910 loge("Error invoking onConnectivityReportAvailable", ex);
9911 }
9912 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009913 }
9914 }
9915
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009916 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +09009917 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9918 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009919 sanitized.setUids(null);
9920 sanitized.setAdministratorUids(new int[0]);
9921 sanitized.setOwnerUid(Process.INVALID_UID);
9922 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -08009923 }
9924
Cody Kestingf1120be2020-08-03 18:01:40 -07009925 /**
9926 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
9927 *
9928 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
9929 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009930 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -07009931 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009932 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009933 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009934 mConnectivityDiagnosticsCallbacks.entrySet()) {
9935 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9936 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -07009937
James Mattis64b8b0f2020-11-24 17:40:49 -08009938 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -07009939 if (!nai.satisfies(nri.mRequests.get(0))) {
9940 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009941 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009942
9943 // UID for this callback must either be:
9944 // - INVALID_UID (which sends callbacks to all UIDs), or
9945 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
9946 // notified as a result)
9947 if (uid != Process.INVALID_UID && uid != nri.mUid) {
9948 continue;
9949 }
9950
9951 if (!checkConnectivityDiagnosticsPermissions(
9952 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9953 continue;
9954 }
9955
9956 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009957 }
9958 return results;
9959 }
9960
Cody Kesting7474f672021-05-11 14:22:40 -07009961 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
9962 @NonNull NetworkAgentInfo nai) {
9963 // TODO(b/188483916): replace with a transport-agnostic location-aware check
9964 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
9965 }
9966
Cody Kesting160ef392021-05-05 13:17:22 -07009967 private boolean hasLocationPermission(String packageName, int uid) {
9968 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9969 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9970 // call in a try-catch.
9971 try {
9972 if (!mLocationPermissionChecker.checkLocationPermission(
9973 packageName, null /* featureId */, uid, null /* message */)) {
9974 return false;
9975 }
9976 } catch (SecurityException e) {
9977 return false;
9978 }
9979
9980 return true;
9981 }
9982
9983 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
9984 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +09009985 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -07009986 && virtual.networkCapabilities.getOwnerUid() == uid
9987 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
9988 return true;
9989 }
9990 }
9991
9992 return false;
9993 }
9994
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009995 @VisibleForTesting
9996 boolean checkConnectivityDiagnosticsPermissions(
9997 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9998 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9999 return true;
10000 }
10001
Cody Kesting160ef392021-05-05 13:17:22 -070010002 // Administrator UIDs also contains the Owner UID
10003 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10004 if (!CollectionUtils.contains(administratorUids, callbackUid)
10005 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010006 return false;
10007 }
10008
Cody Kesting7474f672021-05-11 14:22:40 -070010009 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10010 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010011 }
10012
Cody Kestingd199a9d2019-12-17 12:55:28 -080010013 @Override
10014 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010015 @NonNull IConnectivityDiagnosticsCallback callback,
10016 @NonNull NetworkRequest request,
10017 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010018 Objects.requireNonNull(callback, "callback must not be null");
10019 Objects.requireNonNull(request, "request must not be null");
10020 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10021
Cody Kesting73708bf2019-12-18 10:57:50 -080010022 if (request.legacyType != TYPE_NONE) {
10023 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10024 + " Please use NetworkCapabilities instead.");
10025 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010026 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010027 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010028
10029 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10030 // and administrator uids to be safe.
10031 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010032 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010033
10034 final NetworkRequest requestWithId =
10035 new NetworkRequest(
10036 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10037
10038 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10039 //
10040 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10041 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10042 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010043 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010044 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010045 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010046
10047 mConnectivityDiagnosticsHandler.sendMessage(
10048 mConnectivityDiagnosticsHandler.obtainMessage(
10049 ConnectivityDiagnosticsHandler
10050 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10051 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010052 }
10053
10054 @Override
10055 public void unregisterConnectivityDiagnosticsCallback(
10056 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010057 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010058 mConnectivityDiagnosticsHandler.sendMessage(
10059 mConnectivityDiagnosticsHandler.obtainMessage(
10060 ConnectivityDiagnosticsHandler
10061 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010062 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010063 0,
10064 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010065 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010066
10067 @Override
10068 public void simulateDataStall(int detectionMethod, long timestampMillis,
10069 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010070 Objects.requireNonNull(network, "network must not be null");
10071 Objects.requireNonNull(extras, "extras must not be null");
10072
Cody Kestingf53a0752020-04-15 12:33:28 -070010073 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
10074 android.Manifest.permission.NETWORK_STACK);
10075 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
10076 if (!nc.hasTransport(TRANSPORT_TEST)) {
Chalard Jean15228572022-01-28 19:29:12 +090010077 throw new SecurityException("Data Stall simulation is only possible for test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010078 }
10079
10080 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010081 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -070010082 throw new SecurityException("Data Stall simulation is only possible for network "
10083 + "creators");
10084 }
10085
Cody Kesting652e3ec2020-05-21 12:08:21 -070010086 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10087 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10088 // Data Stall information as a DataStallReportParcelable and passing to
10089 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10090 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010091 final DataStallReportParcelable p = new DataStallReportParcelable();
10092 p.timestampMillis = timestampMillis;
10093 p.detectionMethod = detectionMethod;
10094
10095 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10096 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10097 }
10098 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10099 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10100 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10101 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10102 }
10103
Serik Beketayevec8ad212020-12-07 22:43:07 -080010104 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010105 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010106
lucaslin66f44212021-02-23 01:12:55 +080010107 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10108 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010109 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010110 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010111 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010112 }
lucaslin37a16d92021-01-21 19:48:09 +080010113
10114 @Override
10115 public void onInterfaceLinkStateChanged(String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010116 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010117 nai.clatd.interfaceLinkStateChanged(iface, up);
10118 }
10119 }
10120
10121 @Override
10122 public void onInterfaceRemoved(String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010123 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010124 nai.clatd.interfaceRemoved(iface);
10125 }
lucaslin66f44212021-02-23 01:12:55 +080010126 }
10127 }
10128
lucaslin1a8b4c62021-01-21 02:02:55 +080010129 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
10130
10131 /**
10132 * Class used for updating network activity tracking with netd and notify network activity
10133 * changes.
10134 */
10135 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080010136 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080010137 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080010138 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080010139 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
10140 new RemoteCallbackList<>();
10141 // Indicate the current system default network activity is active or not.
10142 @GuardedBy("mActiveIdleTimers")
10143 private boolean mNetworkActive;
10144 @GuardedBy("mActiveIdleTimers")
10145 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
10146 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010147
lucaslin1193a5d2021-01-21 02:04:15 +080010148 private class IdleTimerParams {
10149 public final int timeout;
10150 public final int transportType;
10151
10152 IdleTimerParams(int timeout, int transport) {
10153 this.timeout = timeout;
10154 this.transportType = transport;
10155 }
10156 }
10157
10158 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080010159 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080010160 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080010161 mNetd = netd;
10162 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010163 }
10164
lucaslin66f44212021-02-23 01:12:55 +080010165 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
10166 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
10167 synchronized (mActiveIdleTimers) {
10168 mNetworkActive = active;
10169 // If there are no idle timers, it means that system is not monitoring
10170 // activity, so the system default network for those default network
10171 // unspecified apps is always considered active.
10172 //
10173 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
10174 // any network activity change event. Whenever this event is received,
10175 // the mActiveIdleTimers should be always not empty. The legacy behavior
10176 // is no-op. Remove to refer to mNetworkActive only.
10177 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
10178 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
10179 }
10180 }
10181 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010182
lucaslin1193a5d2021-01-21 02:04:15 +080010183 // The network activity should only be updated from ConnectivityService handler thread
10184 // when mActiveIdleTimers lock is held.
10185 @GuardedBy("mActiveIdleTimers")
10186 private void reportNetworkActive() {
10187 final int length = mNetworkActivityListeners.beginBroadcast();
10188 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
10189 try {
10190 for (int i = 0; i < length; i++) {
10191 try {
10192 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
10193 } catch (RemoteException | RuntimeException e) {
10194 loge("Fail to send network activie to listener " + e);
10195 }
10196 }
10197 } finally {
10198 mNetworkActivityListeners.finishBroadcast();
10199 }
10200 }
10201
10202 @GuardedBy("mActiveIdleTimers")
10203 public void handleReportNetworkActivity() {
10204 synchronized (mActiveIdleTimers) {
10205 reportNetworkActive();
10206 }
10207 }
10208
lucaslin1a8b4c62021-01-21 02:02:55 +080010209 // This is deprecated and only to support legacy use cases.
10210 private int transportTypeToLegacyType(int type) {
10211 switch (type) {
10212 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010213 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080010214 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010215 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080010216 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010217 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080010218 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010219 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080010220 default:
10221 loge("Unexpected transport in transportTypeToLegacyType: " + type);
10222 }
10223 return ConnectivityManager.TYPE_NONE;
10224 }
10225
10226 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
10227 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
10228 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
10229 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
10230 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
10231 final long ident = Binder.clearCallingIdentity();
10232 try {
10233 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
10234 RECEIVE_DATA_ACTIVITY_CHANGE,
10235 null /* resultReceiver */,
10236 null /* scheduler */,
10237 0 /* initialCode */,
10238 null /* initialData */,
10239 null /* initialExtra */);
10240 } finally {
10241 Binder.restoreCallingIdentity(ident);
10242 }
10243 }
10244
10245 /**
10246 * Setup data activity tracking for the given network.
10247 *
10248 * Every {@code setupDataActivityTracking} should be paired with a
10249 * {@link #removeDataActivityTracking} for cleanup.
10250 */
10251 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
10252 final String iface = networkAgent.linkProperties.getInterfaceName();
10253
10254 final int timeout;
10255 final int type;
10256
10257 if (networkAgent.networkCapabilities.hasTransport(
10258 NetworkCapabilities.TRANSPORT_CELLULAR)) {
10259 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010260 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080010261 10);
10262 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10263 } else if (networkAgent.networkCapabilities.hasTransport(
10264 NetworkCapabilities.TRANSPORT_WIFI)) {
10265 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010266 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080010267 15);
10268 type = NetworkCapabilities.TRANSPORT_WIFI;
10269 } else {
10270 return; // do not track any other networks
10271 }
10272
lucaslinb961efc2021-01-21 02:03:17 +080010273 updateRadioPowerState(true /* isActive */, type);
10274
lucaslin1a8b4c62021-01-21 02:02:55 +080010275 if (timeout > 0 && iface != null) {
10276 try {
lucaslin1193a5d2021-01-21 02:04:15 +080010277 synchronized (mActiveIdleTimers) {
10278 // Networks start up.
10279 mNetworkActive = true;
10280 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
10281 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
10282 reportNetworkActive();
10283 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010284 } catch (Exception e) {
10285 // You shall not crash!
10286 loge("Exception in setupDataActivityTracking " + e);
10287 }
10288 }
10289 }
10290
10291 /**
10292 * Remove data activity tracking when network disconnects.
10293 */
10294 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
10295 final String iface = networkAgent.linkProperties.getInterfaceName();
10296 final NetworkCapabilities caps = networkAgent.networkCapabilities;
10297
lucaslinb961efc2021-01-21 02:03:17 +080010298 if (iface == null) return;
10299
10300 final int type;
10301 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10302 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10303 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10304 type = NetworkCapabilities.TRANSPORT_WIFI;
10305 } else {
10306 return; // do not track any other networks
10307 }
10308
10309 try {
10310 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010311 synchronized (mActiveIdleTimers) {
10312 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10313 // The call fails silently if no idle timer setup for this interface
10314 mNetd.idletimerRemoveInterface(iface, params.timeout,
10315 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010316 }
lucaslinb961efc2021-01-21 02:03:17 +080010317 } catch (Exception e) {
10318 // You shall not crash!
10319 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010320 }
10321 }
10322
10323 /**
10324 * Update data activity tracking when network state is updated.
10325 */
10326 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10327 NetworkAgentInfo oldNetwork) {
10328 if (newNetwork != null) {
10329 setupDataActivityTracking(newNetwork);
10330 }
10331 if (oldNetwork != null) {
10332 removeDataActivityTracking(oldNetwork);
10333 }
10334 }
lucaslinb961efc2021-01-21 02:03:17 +080010335
10336 private void updateRadioPowerState(boolean isActive, int transportType) {
10337 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10338 switch (transportType) {
10339 case NetworkCapabilities.TRANSPORT_CELLULAR:
10340 bs.reportMobileRadioPowerState(isActive, NO_UID);
10341 break;
10342 case NetworkCapabilities.TRANSPORT_WIFI:
10343 bs.reportWifiRadioPowerState(isActive, NO_UID);
10344 break;
10345 default:
10346 logw("Untracked transport type:" + transportType);
10347 }
10348 }
lucaslin1193a5d2021-01-21 02:04:15 +080010349
10350 public boolean isDefaultNetworkActive() {
10351 synchronized (mActiveIdleTimers) {
10352 // If there are no idle timers, it means that system is not monitoring activity,
10353 // so the default network is always considered active.
10354 //
10355 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10356 // tracking is disabled (negative idle timer value configured), or no active default
10357 // network. In the latter case, this reports active but it should report inactive.
10358 return mNetworkActive || mActiveIdleTimers.isEmpty();
10359 }
10360 }
10361
10362 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10363 mNetworkActivityListeners.register(l);
10364 }
10365
10366 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10367 mNetworkActivityListeners.unregister(l);
10368 }
lucaslin012f7a12021-01-21 02:04:35 +080010369
10370 public void dump(IndentingPrintWriter pw) {
10371 synchronized (mActiveIdleTimers) {
10372 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10373 pw.println("Idle timers:");
10374 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10375 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10376 final IdleTimerParams params = ent.getValue();
10377 pw.print(" timeout="); pw.print(params.timeout);
10378 pw.print(" type="); pw.println(params.transportType);
10379 }
10380 }
10381 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010382 }
James Mattis47db0582021-01-01 14:13:35 -080010383
Daniel Brightf9e945b2020-06-15 16:10:01 -070010384 /**
10385 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10386 *
10387 * @param socketInfo the socket information
10388 * @param callback the callback to register
10389 */
10390 @Override
10391 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10392 @NonNull final IQosCallback callback) {
10393 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10394 if (nai == null || nai.networkCapabilities == null) {
10395 try {
10396 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10397 } catch (final RemoteException ex) {
10398 loge("registerQosCallbackInternal: RemoteException", ex);
10399 }
10400 return;
10401 }
10402 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10403 }
10404
10405 /**
10406 * Register a {@link IQosCallback} with base {@link QosFilter}.
10407 *
10408 * @param filter the filter to register
10409 * @param callback the callback to register
10410 * @param nai the agent information related to the filter's network
10411 */
10412 @VisibleForTesting
10413 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10414 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
10415 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
10416 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
10417
10418 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
10419 enforceConnectivityRestrictedNetworksPermission();
10420 }
10421 mQosCallbackTracker.registerCallback(callback, filter, nai);
10422 }
10423
10424 /**
10425 * Unregisters the given callback.
10426 *
10427 * @param callback the callback to unregister
10428 */
10429 @Override
10430 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010431 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010432 mQosCallbackTracker.unregisterCallback(callback);
10433 }
James Mattis47db0582021-01-01 14:13:35 -080010434
James Mattis45d81842021-01-10 14:24:24 -080010435 /**
Chalard Jeanfa45a682021-02-25 17:23:40 +090010436 * Request that a user profile is put by default on a network matching a given preference.
10437 *
10438 * See the documentation for the individual preferences for a description of the supported
10439 * behaviors.
10440 *
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010441 * @param profile the user profile for whih the preference is being set.
10442 * @param preferences the list of profile network preferences for the
10443 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010444 * @param listener an optional listener to listen for completion of the operation.
10445 */
10446 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010447 public void setProfileNetworkPreferences(
10448 @NonNull final UserHandle profile,
10449 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090010450 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010451 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010452 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010453
10454 if (preferences.size() == 0) {
10455 preferences.add((new ProfileNetworkPreference.Builder()).build());
10456 }
10457
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010458 PermissionUtils.enforceNetworkStackPermission(mContext);
10459 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010460 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010461 }
10462 if (profile.getIdentifier() < 0) {
10463 throw new IllegalArgumentException("Must explicitly specify a user handle ("
10464 + "UserHandle.CURRENT not supported)");
10465 }
Chalard Jeana21ef9b2021-04-02 19:24:44 +090010466 final UserManager um = mContext.getSystemService(UserManager.class);
10467 if (!um.isManagedProfile(profile.getIdentifier())) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010468 throw new IllegalArgumentException("Profile must be a managed profile");
10469 }
paulhuaa0743d2021-05-26 21:56:03 +080010470
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010471 final List<ProfileNetworkPreferenceList.Preference> preferenceList =
10472 new ArrayList<ProfileNetworkPreferenceList.Preference>();
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010473 boolean allowFallback = true;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010474 for (final ProfileNetworkPreference preference : preferences) {
10475 final NetworkCapabilities nc;
10476 switch (preference.getPreference()) {
10477 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
10478 nc = null;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010479 if (preference.getPreferenceEnterpriseId() != 0) {
10480 throw new IllegalArgumentException(
10481 "Invalid enterprise identifier in setProfileNetworkPreferences");
10482 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010483 break;
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010484 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
10485 allowFallback = false;
10486 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010487 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010488 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
10489 throw new IllegalArgumentException(
10490 "Invalid enterprise identifier in setProfileNetworkPreferences");
10491 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010492 final Set<UidRange> uidRangeSet =
10493 getUidListToBeAppliedForNetworkPreference(profile, preference);
10494 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
10495 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
10496 } else {
10497 throw new IllegalArgumentException(
10498 "Overlapping uid range in setProfileNetworkPreferences");
10499 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010500 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010501 nc.addEnterpriseId(
10502 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010503 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10504 break;
10505 default:
10506 throw new IllegalArgumentException(
10507 "Invalid preference in setProfileNetworkPreferences");
10508 }
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010509 preferenceList.add(new ProfileNetworkPreferenceList.Preference(
10510 profile, nc, allowFallback));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010511 }
10512 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010513 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010514 }
10515
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010516 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
10517 @NonNull final UserHandle profile,
10518 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
10519 final UidRange profileUids = UidRange.createForUser(profile);
10520 Set<UidRange> uidRangeSet = UidRangeUtils.convertListToUidRange(
10521 profileNetworkPreference.getIncludedUids());
10522 if (uidRangeSet.size() > 0) {
10523 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
10524 throw new IllegalArgumentException(
10525 "Allow uid range is outside the uid range of profile.");
10526 }
10527 } else {
10528 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertListToUidRange(
10529 profileNetworkPreference.getExcludedUids());
10530 if (disallowUidRangeSet.size() > 0) {
10531 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
10532 throw new IllegalArgumentException(
10533 "disallow uid range is outside the uid range of profile.");
10534 }
10535 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
10536 disallowUidRangeSet);
10537 } else {
10538 uidRangeSet = new ArraySet<UidRange>();
10539 uidRangeSet.add(profileUids);
10540 }
10541 }
10542 return uidRangeSet;
10543 }
10544
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010545 private boolean isEnterpriseIdentifierValid(
10546 @NetworkCapabilities.EnterpriseId int identifier) {
10547 if ((identifier >= NET_ENTERPRISE_ID_1)
10548 && (identifier <= NET_ENTERPRISE_ID_5)) {
10549 return true;
10550 }
10551 return false;
10552 }
10553
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010554 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
10555 @Nullable final NetworkCapabilities nc) {
10556 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
10557 ensureRequestableCapabilities(nc);
10558 }
10559
10560 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010561 @NonNull final ProfileNetworkPreferenceList prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010562 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010563 for (final ProfileNetworkPreferenceList.Preference pref : prefs.preferences) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010564 // The NRI for a user should contain the request for capabilities.
10565 // If fallback to default network is needed then NRI should include
10566 // the request for the default network. Create an image of it to
10567 // have the correct UIDs in it (also a request can only be part of one NRI, because
10568 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010569 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
10570 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010571 if (pref.allowFallback) {
10572 nrs.add(createDefaultInternetRequestForTransport(
10573 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10574 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010575 if (VDBG) {
10576 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
10577 pref.capabilities.getUids()));
10578 }
10579
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010580 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080010581 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080010582 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010583 result.add(nri);
10584 }
10585 return result;
10586 }
10587
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010588 /**
10589 * Compare if the given UID range sets have the same UIDs.
10590 *
10591 */
10592 private boolean isRangeAlreadyInPreferenceList(
10593 @NonNull List<ProfileNetworkPreferenceList.Preference> preferenceList,
10594 @NonNull Set<UidRange> uidRangeSet) {
10595 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
10596 return false;
10597 }
10598 for (ProfileNetworkPreferenceList.Preference pref : preferenceList) {
10599 if (UidRangeUtils.doesRangeSetOverlap(
10600 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
10601 return true;
10602 }
10603 }
10604 return false;
10605 }
10606
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010607 private void handleSetProfileNetworkPreference(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010608 @NonNull final List<ProfileNetworkPreferenceList.Preference> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010609 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010610 for (final ProfileNetworkPreferenceList.Preference preference : preferenceList) {
10611 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
10612 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
10613 }
paulhu74128522021-09-28 02:29:03 +000010614 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
10615 addPerAppDefaultNetworkRequests(
10616 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010617 // Finally, rematch.
10618 rematchAllNetworksAndRequests();
10619
10620 if (null != listener) {
10621 try {
10622 listener.onComplete();
10623 } catch (RemoteException e) {
10624 loge("Listener for setProfileNetworkPreference has died");
10625 }
10626 }
10627 }
10628
paulhu51f77dc2021-06-07 02:34:20 +000010629 @VisibleForTesting
10630 @NonNull
10631 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
10632 @NonNull final Set<Integer> uids) {
10633 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10634 if (uids.size() == 0) {
10635 // Should not create NetworkRequestInfo if no preferences. Without uid range in
10636 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
10637 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
10638 return nris;
10639 }
10640
10641 final List<NetworkRequest> requests = new ArrayList<>();
10642 // The NRI should be comprised of two layers:
10643 // - The request for the mobile network preferred.
10644 // - The request for the default network, for fallback.
10645 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090010646 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000010647 requests.add(createDefaultInternetRequestForTransport(
10648 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10649 final Set<UidRange> ranges = new ArraySet<>();
10650 for (final int uid : uids) {
10651 ranges.add(new UidRange(uid, uid));
10652 }
10653 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080010654 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080010655 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000010656 return nris;
10657 }
10658
10659 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000010660 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000010661 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
10662 addPerAppDefaultNetworkRequests(
10663 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000010664 // Finally, rematch.
10665 rematchAllNetworksAndRequests();
10666 }
10667
Patrick Rohr2857ac42022-01-21 14:58:16 +010010668 private void handleIngressRateLimitChanged() {
10669 final long oldIngressRateLimit = mIngressRateLimit;
10670 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
10671 mContext);
10672 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
10673 if (canNetworkBeRateLimited(networkAgent)) {
10674 // If rate limit has previously been enabled, remove the old limit first.
10675 if (oldIngressRateLimit >= 0) {
10676 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
10677 }
10678 if (mIngressRateLimit >= 0) {
10679 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10680 mIngressRateLimit);
10681 }
10682 }
10683 }
10684 }
10685
10686 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
10687 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_INTERNET)) {
10688 // rate limits only apply to networks that provide internet connectivity.
10689 return false;
10690 }
10691
10692 final String iface = networkAgent.linkProperties.getInterfaceName();
10693 if (iface == null) {
10694 // This can never happen.
10695 logwtf("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
10696 return false;
10697 }
10698 return true;
10699 }
10700
James Mattis45d81842021-01-10 14:24:24 -080010701 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080010702 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
10703 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080010704 }
10705
10706 /**
10707 * Used by automotive devices to set the network preferences used to direct traffic at an
10708 * application level as per the given OemNetworkPreferences. An example use-case would be an
10709 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
10710 * vehicle via a particular network.
10711 *
10712 * Calling this will overwrite the existing preference.
10713 *
James Mattisda32cfe2021-01-26 16:23:52 -080010714 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090010715 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080010716 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080010717 */
James Mattis47db0582021-01-01 14:13:35 -080010718 @Override
James Mattis45d81842021-01-10 14:24:24 -080010719 public void setOemNetworkPreference(
10720 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010721 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080010722
James Mattisfa270db2021-05-31 17:11:10 -070010723 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10724 // Only bypass the permission/device checks if this is a valid test request.
10725 if (isValidTestOemNetworkPreference(preference)) {
10726 enforceManageTestNetworksPermission();
10727 } else {
10728 enforceAutomotiveDevice();
10729 enforceOemNetworkPreferencesPermission();
10730 validateOemNetworkPreferences(preference);
10731 }
James Mattis45d81842021-01-10 14:24:24 -080010732
James Mattis45d81842021-01-10 14:24:24 -080010733 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
10734 new Pair<>(preference, listener)));
10735 }
10736
James Mattisfa270db2021-05-31 17:11:10 -070010737 /**
10738 * Check the validity of an OEM network preference to be used for testing purposes.
10739 * @param preference the preference to validate
10740 * @return true if this is a valid OEM network preference test request.
10741 */
10742 private boolean isValidTestOemNetworkPreference(
10743 @NonNull final OemNetworkPreferences preference) {
10744 // Allow for clearing of an existing OemNetworkPreference used for testing.
10745 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
10746 // changes after this check is complete. This is an unlikely scenario as calling of this API
10747 // is controlled by the OEM therefore the added complexity is not worth adding given those
10748 // circumstances. That said, it is an edge case to be aware of hence this comment.
10749 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
10750 && isTestOemNetworkPreference(mOemNetworkPreferences);
10751 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
10752 }
10753
10754 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
10755 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
10756 return prefMap.size() == 1
10757 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
10758 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
10759 }
10760
James Mattis45d81842021-01-10 14:24:24 -080010761 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
10762 for (@OemNetworkPreferences.OemNetworkPreference final int pref
10763 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070010764 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
10765 throw new IllegalArgumentException(
10766 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
10767 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080010768 }
10769 }
10770 }
10771
10772 private void handleSetOemNetworkPreference(
10773 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010774 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080010775 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10776 if (DBG) {
10777 log("set OEM network preferences :" + preference.toString());
10778 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010779
James Mattiscb1e0362021-04-06 17:07:42 -070010780 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000010781 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
10782 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
10783 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080010784 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080010785
10786 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010787 try {
10788 listener.onComplete();
10789 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080010790 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010791 }
James Mattis45d81842021-01-10 14:24:24 -080010792 }
10793 }
10794
paulhu74128522021-09-28 02:29:03 +000010795 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080010796 // Skip the requests which are set by other network preference. Because the uid range rules
10797 // should stay in netd.
10798 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080010799 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080010800 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080010801 }
10802
James Mattis3ce3d3c2021-02-09 18:18:28 -080010803 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
10804 ensureRunningOnConnectivityServiceThread();
10805 mDefaultNetworkRequests.addAll(nris);
10806 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
10807 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080010808 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000010809 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
10810 nrisToRegister.addAll(
10811 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
10812 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010813 }
10814
10815 /**
10816 * All current requests that are tracking the default network need to be assessed as to whether
10817 * or not the current set of per-application default requests will be changing their default
10818 * network. If so, those requests will need to be updated so that they will send callbacks for
10819 * default network changes at the appropriate time. Additionally, those requests tracking the
10820 * default that were previously updated by this flow will need to be reassessed.
10821 * @return the nris which will need to be updated.
10822 */
10823 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
10824 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
10825 // Get the distinct nris to check since for multilayer requests, it is possible to have the
10826 // same nri in the map's values for each of its NetworkRequest objects.
10827 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080010828 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010829 // Include this nri if it is currently being tracked.
10830 if (isPerAppTrackedNri(nri)) {
10831 defaultCallbackRequests.add(nri);
10832 continue;
10833 }
10834 // We only track callbacks for requests tracking the default.
10835 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
10836 continue;
10837 }
10838 // Include this nri if it will be tracked by the new per-app default requests.
10839 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010840 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080010841 if (isNriGoingToBeTracked) {
10842 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080010843 }
10844 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080010845 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080010846 }
10847
James Mattis3ce3d3c2021-02-09 18:18:28 -080010848 /**
10849 * Create nris for those network requests that are currently tracking the default network that
10850 * are being controlled by a per-application default.
10851 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
10852 * foundation when creating the nri. Important items include the calling uid's original
10853 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
10854 * requests are assumed to have already been validated as needing to be updated.
10855 * @return the Set of nris to use when registering network requests.
10856 */
10857 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
10858 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
10859 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
10860 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
10861 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010862 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010863
Chalard Jean9473c982021-07-29 20:03:04 +090010864 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080010865 if (trackingNri == mDefaultRequest) {
10866 callbackRequestsToRegister.add(new NetworkRequestInfo(
10867 callbackRequest,
10868 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
10869 continue;
10870 }
10871
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010872 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010873 callbackRequestsToRegister.add(new NetworkRequestInfo(
10874 callbackRequest,
10875 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010876 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090010877 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080010878 }
10879 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080010880 }
10881
Chalard Jean17215832021-03-01 14:06:28 +090010882 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
10883 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090010884 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010885 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090010886 }
10887 }
10888
James Mattis45d81842021-01-10 14:24:24 -080010889 /**
10890 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
10891 */
10892 @VisibleForTesting
10893 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010894 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080010895 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010896 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080010897 final SparseArray<Set<Integer>> uids =
10898 createUidsFromOemNetworkPreferences(preference);
10899 for (int i = 0; i < uids.size(); i++) {
10900 final int key = uids.keyAt(i);
10901 final Set<Integer> value = uids.valueAt(i);
10902 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
10903 // No need to add an nri without any requests.
10904 if (0 == nri.mRequests.size()) {
10905 continue;
10906 }
10907 nris.add(nri);
10908 }
10909
10910 return nris;
10911 }
10912
10913 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
10914 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070010915 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080010916 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080010917 final List<UserHandle> users =
10918 mContext.getSystemService(UserManager.class).getUserHandles(true);
10919 if (null == users || users.size() == 0) {
10920 if (VDBG || DDBG) {
10921 log("No users currently available for setting the OEM network preference.");
10922 }
James Mattisb6b6a432021-06-01 22:30:36 -070010923 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080010924 }
James Mattis45d81842021-01-10 14:24:24 -080010925 for (final Map.Entry<String, Integer> entry :
10926 preference.getNetworkPreferences().entrySet()) {
10927 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070010928 // Add the rules for all users as this policy is device wide.
10929 for (final UserHandle user : users) {
10930 try {
10931 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
10932 if (!prefToUids.contains(pref)) {
10933 prefToUids.put(pref, new ArraySet<>());
10934 }
10935 prefToUids.get(pref).add(uid);
10936 } catch (PackageManager.NameNotFoundException e) {
10937 // Although this may seem like an error scenario, it is ok that uninstalled
10938 // packages are sent on a network preference as the system will watch for
10939 // package installations associated with this network preference and update
10940 // accordingly. This is done to minimize race conditions on app install.
10941 continue;
James Mattis45d81842021-01-10 14:24:24 -080010942 }
James Mattis45d81842021-01-10 14:24:24 -080010943 }
10944 }
James Mattisb6b6a432021-06-01 22:30:36 -070010945 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080010946 }
10947
10948 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10949 @OemNetworkPreferences.OemNetworkPreference final int preference,
10950 @NonNull final Set<Integer> uids) {
10951 final List<NetworkRequest> requests = new ArrayList<>();
10952 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10953 switch (preference) {
10954 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10955 requests.add(createUnmeteredNetworkRequest());
10956 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070010957 requests.add(createDefaultInternetRequestForTransport(
10958 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080010959 break;
10960 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10961 requests.add(createUnmeteredNetworkRequest());
10962 requests.add(createOemPaidNetworkRequest());
10963 break;
10964 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10965 requests.add(createOemPaidNetworkRequest());
10966 break;
10967 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10968 requests.add(createOemPrivateNetworkRequest());
10969 break;
James Mattisfa270db2021-05-31 17:11:10 -070010970 case OEM_NETWORK_PREFERENCE_TEST:
10971 requests.add(createUnmeteredNetworkRequest());
10972 requests.add(createTestNetworkRequest());
10973 requests.add(createDefaultRequest());
10974 break;
10975 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
10976 requests.add(createTestNetworkRequest());
10977 break;
James Mattis45d81842021-01-10 14:24:24 -080010978 default:
10979 // This should never happen.
10980 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10981 + " called with invalid preference of " + preference);
10982 }
10983
James Mattisfa270db2021-05-31 17:11:10 -070010984 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090010985 for (final int uid : uids) {
10986 ranges.add(new UidRange(uid, uid));
10987 }
10988 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080010989 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080010990 }
10991
10992 private NetworkRequest createUnmeteredNetworkRequest() {
10993 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10994 .addCapability(NET_CAPABILITY_NOT_METERED)
10995 .addCapability(NET_CAPABILITY_VALIDATED);
10996 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10997 }
10998
10999 private NetworkRequest createOemPaidNetworkRequest() {
11000 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11001 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11002 .addCapability(NET_CAPABILITY_OEM_PAID)
11003 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11004 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11005 }
11006
11007 private NetworkRequest createOemPrivateNetworkRequest() {
11008 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
11009 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11010 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
11011 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11012 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11013 }
11014
11015 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070011016 final NetworkCapabilities netcap = new NetworkCapabilities();
11017 netcap.addCapability(NET_CAPABILITY_INTERNET);
11018 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
11019 return netcap;
11020 }
11021
11022 private NetworkRequest createTestNetworkRequest() {
11023 final NetworkCapabilities netcap = new NetworkCapabilities();
11024 netcap.clearAll();
11025 netcap.addTransportType(TRANSPORT_TEST);
11026 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080011027 }
James Mattis47db0582021-01-01 14:13:35 -080011028 }
markchien738ad912021-12-09 18:15:45 +080011029
11030 @Override
11031 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
11032 enforceNetworkStackOrSettingsPermission();
11033
11034 try {
11035 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011036 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011037 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011038 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011039 }
Ken Chenf5f51332022-01-28 10:08:16 +080011040 } catch (RemoteException | ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011041 throw new IllegalStateException(e);
11042 }
11043 }
11044
11045 @Override
11046 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
11047 enforceNetworkStackOrSettingsPermission();
11048
11049 try {
11050 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011051 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011052 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011053 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011054 }
Ken Chenf5f51332022-01-28 10:08:16 +080011055 } catch (RemoteException | ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011056 throw new IllegalStateException(e);
11057 }
11058 }
markchiene1561fa2021-12-09 22:00:56 +080011059
11060 @Override
11061 public void updateFirewallRule(final int chain, final int uid, final boolean allow) {
11062 enforceNetworkStackOrSettingsPermission();
11063
11064 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011065 mBpfNetMaps.setUidRule(chain, uid,
markchiene1561fa2021-12-09 22:00:56 +080011066 allow ? INetd.FIREWALL_RULE_ALLOW : INetd.FIREWALL_RULE_DENY);
Ken Chenf5f51332022-01-28 10:08:16 +080011067 } catch (RemoteException | ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080011068 throw new IllegalStateException(e);
11069 }
11070 }
markchien98a6f952022-01-13 23:43:53 +080011071
11072 @Override
11073 public void setFirewallChainEnabled(final int chain, final boolean enable) {
11074 enforceNetworkStackOrSettingsPermission();
11075
11076 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011077 mBpfNetMaps.setChildChain(chain, enable);
Ken Chenf5f51332022-01-28 10:08:16 +080011078 } catch (RemoteException | ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080011079 throw new IllegalStateException(e);
11080 }
11081 }
11082
markchien00a0bed2022-01-13 23:46:13 +080011083 @Override
11084 public void replaceFirewallChain(final int chain, final int[] uids) {
11085 enforceNetworkStackOrSettingsPermission();
11086
11087 try {
11088 switch (chain) {
11089 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
Wayne Ma2fde98c2022-01-17 18:04:05 +080011090 mBpfNetMaps.replaceUidChain("fw_dozable", true /* isAllowList */, uids);
markchien00a0bed2022-01-13 23:46:13 +080011091 break;
11092 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Wayne Ma2fde98c2022-01-17 18:04:05 +080011093 mBpfNetMaps.replaceUidChain("fw_standby", false /* isAllowList */, uids);
markchien00a0bed2022-01-13 23:46:13 +080011094 break;
11095 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
Wayne Ma2fde98c2022-01-17 18:04:05 +080011096 mBpfNetMaps.replaceUidChain("fw_powersave", true /* isAllowList */, uids);
markchien00a0bed2022-01-13 23:46:13 +080011097 break;
11098 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
Wayne Ma2fde98c2022-01-17 18:04:05 +080011099 mBpfNetMaps.replaceUidChain("fw_restricted", true /* isAllowList */, uids);
markchien00a0bed2022-01-13 23:46:13 +080011100 break;
Robert Horvath1db49e12022-01-27 19:54:29 +010011101 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
11102 mBpfNetMaps.replaceUidChain("fw_low_power_standby", true /* isAllowList */,
11103 uids);
11104 break;
markchien00a0bed2022-01-13 23:46:13 +080011105 default:
11106 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
11107 + chain);
11108 }
Ken Chenf5f51332022-01-28 10:08:16 +080011109 } catch (RemoteException | ServiceSpecificException e) {
markchien00a0bed2022-01-13 23:46:13 +080011110 throw new IllegalStateException(e);
11111 }
11112 }
markchien9c806112022-01-11 23:28:23 +080011113
11114 @Override
11115 public void swapActiveStatsMap() {
11116 enforceNetworkStackOrSettingsPermission();
11117 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011118 mBpfNetMaps.swapActiveStatsMap();
Ken Chenf5f51332022-01-28 10:08:16 +080011119 } catch (RemoteException | ServiceSpecificException e) {
markchien9c806112022-01-11 23:28:23 +080011120 throw new IllegalStateException(e);
11121 }
11122 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070011123}